<?php require_once('header.php'); ?>

<?php

if(isset($_POST['form1'])) {

    $valid = 1;
    $error_message = '';
    $success_message = '';

    /*
    |--------------------------------------------------------------------------
    | CATEGORY DATA
    |--------------------------------------------------------------------------
    */

    $category_name = trim($_POST['top_category_name'] ?? '');
    $short_name = trim($_POST['short_name'] ?? '');
    $description = trim($_POST['description'] ?? '');

    $meta_title = trim($_POST['meta_title'] ?? '');
    $meta_keyword = trim($_POST['meta_keyword'] ?? '');
    $meta_description = trim($_POST['meta_description'] ?? '');

    $show_on_menu = isset($_POST['show_on_menu'])
        ? (int)$_POST['show_on_menu']
        : 0;


    /*
    |--------------------------------------------------------------------------
    | FEATURES
    |--------------------------------------------------------------------------
    */

    $features = $_POST['features'] ?? [];

    if(!is_array($features)) {
        $features = [];
    }

    $features = array_map('trim', $features);

    $features = array_filter($features, function($value) {
        return $value !== '';
    });

    $features = array_values($features);

    $features_json = json_encode(
        $features,
        JSON_UNESCAPED_UNICODE
    );


    /*
    |--------------------------------------------------------------------------
    | APPLICATIONS
    |--------------------------------------------------------------------------
    */

    $applications = $_POST['applications'] ?? [];

    if(!is_array($applications)) {
        $applications = [];
    }

    $applications = array_map('trim', $applications);

    $applications = array_filter($applications, function($value) {
        return $value !== '';
    });

    $applications = array_values($applications);

    $applications_json = json_encode(
        $applications,
        JSON_UNESCAPED_UNICODE
    );


    /*
    |--------------------------------------------------------------------------
    | CATEGORY NAME VALIDATION
    |--------------------------------------------------------------------------
    */

    if($category_name == '') {

        $valid = 0;

        $error_message .=
            "Top Category Name can not be empty<br>";

    } else {

        $statement = $pdo->prepare("
            SELECT id
            FROM tbl_top_category
            WHERE top_category_name=?
            LIMIT 1
        ");

        $statement->execute([
            $category_name
        ]);

        if($statement->rowCount()) {

            $valid = 0;

            $error_message .=
                "Top Category Name already exists<br>";

        }
    }


    /*
    |--------------------------------------------------------------------------
    | SLUG
    |--------------------------------------------------------------------------
    */

    $slug = strtolower(
        trim($category_name)
    );

    $slug = preg_replace(
        '/[^a-z0-9]+/',
        '-',
        $slug
    );

    $slug = trim(
        $slug,
        '-'
    );


    /*
    |--------------------------------------------------------------------------
    | CHECK SLUG
    |--------------------------------------------------------------------------
    */

    if($slug != '') {

        $statement = $pdo->prepare("
            SELECT id
            FROM tbl_top_category
            WHERE top_category_slug=?
            LIMIT 1
        ");

        $statement->execute([
            $slug
        ]);

        if($statement->rowCount()) {

            $valid = 0;

            $error_message .=
                "Category slug already exists<br>";

        }
    }


    /*
    |--------------------------------------------------------------------------
    | BANNER
    |--------------------------------------------------------------------------
    */

    $banner = '';

    if(
        isset($_FILES['banner']) &&
        $_FILES['banner']['name'] != ''
    ) {

        $banner_original =
            $_FILES['banner']['name'];

        $banner_tmp =
            $_FILES['banner']['tmp_name'];

        $banner_ext =
            strtolower(
                pathinfo(
                    $banner_original,
                    PATHINFO_EXTENSION
                )
            );


        if(
            !in_array(
                $banner_ext,
                [
                    'jpg',
                    'jpeg',
                    'png',
                    'gif',
                    'webp'
                ]
            )
        ) {

            $valid = 0;

            $error_message .=
                'You must upload jpg, jpeg, gif, webp or png file<br>';

        } else {

            $banner =
                'category-' .
                time() .
                '-' .
                uniqid() .
                '.' .
                $banner_ext;


            /*
            |--------------------------------------------------------------------------
            | UPLOAD LOCATION
            |--------------------------------------------------------------------------
            */

            $upload_directory =
                __DIR__ .
                '/assets/images/category/';


            if(!is_dir($upload_directory)) {

                mkdir(
                    $upload_directory,
                    0755,
                    true
                );

            }


            $upload_path =
                $upload_directory .
                $banner;


            if(
                !move_uploaded_file(
                    $banner_tmp,
                    $upload_path
                )
            ) {

                $valid = 0;

                $error_message .=
                    'Banner upload failed<br>';

            }

        }
    }


    /*
    |--------------------------------------------------------------------------
    | INSERT
    |--------------------------------------------------------------------------
    */

    if($valid == 1) {

        try {

            $statement = $pdo->prepare("

                INSERT INTO tbl_top_category
                (
                    top_category_name,
                    top_category_slug,
                    short_name,
                    banner,
                    description,
                    features,
                    applications,
                    show_on_menu,
                    meta_title,
                    meta_keyword,
                    meta_description,
                    status
                )

                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?
                )

            ");


            $statement->execute([

                $category_name,

                $slug,

                $short_name,

                $banner,

                $description,

                $features_json,

                $applications_json,

                $show_on_menu,

                $meta_title,

                $meta_keyword,

                $meta_description,

                1

            ]);


            $success_message =
                'Top Category is added successfully.';


            /*
            |--------------------------------------------------------------------------
            | CLEAR FORM
            |--------------------------------------------------------------------------
            */

            $_POST = [];


        } catch(PDOException $e) {

            /*
            |--------------------------------------------------------------------------
            | DELETE IMAGE IF DATABASE INSERT FAILS
            |--------------------------------------------------------------------------
            */

            if($banner != '') {

                $uploaded_file =
                    __DIR__ .
                    '/assets/images/category/' .
                    $banner;

                if(is_file($uploaded_file)) {

                    @unlink(
                        $uploaded_file
                    );

                }

            }


            $error_message =
                'Database Error: ' .
                $e->getMessage();

        }

    }

}

?>

<section class="content-header">

    <div class="content-header-left">

        <h1>
            Add Top Level Category
        </h1>

    </div>


    <div class="content-header-right">

        <a
            href="top-category.php"
            class="btn btn-primary btn-sm"
        >
            View All
        </a>

    </div>

</section>


<section class="content">

    <div class="row">

        <div class="col-md-12">


            <?php if(!empty($error_message)): ?>

                <div class="callout callout-danger">

                    <p>
                        <?php echo $error_message; ?>
                    </p>

                </div>

            <?php endif; ?>


            <?php if(!empty($success_message)): ?>

                <div class="callout callout-success">

                    <p>
                        <?php echo $success_message; ?>
                    </p>

                </div>

            <?php endif; ?>


            <form
                class="form-horizontal"
                action=""
                method="post"
                enctype="multipart/form-data"
            >

                <div class="box box-info">

                    <div class="box-body">


                        <!-- CATEGORY NAME -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Top Category Name
                                <span>*</span>

                            </label>


                            <div class="col-sm-4">

                                <input
                                    type="text"
                                    class="form-control"
                                    name="top_category_name"
                                    value="<?php
                                    echo isset($_POST['top_category_name'])
                                        ? htmlspecialchars(
                                            $_POST['top_category_name']
                                        )
                                        : '';
                                    ?>"
                                    required
                                >

                            </div>

                        </div>


                        <!-- SHORT NAME -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Short Name

                            </label>


                            <div class="col-sm-4">

                                <input
                                    type="text"
                                    class="form-control"
                                    name="short_name"
                                    value="<?php
                                    echo isset($_POST['short_name'])
                                        ? htmlspecialchars(
                                            $_POST['short_name']
                                        )
                                        : '';
                                    ?>"
                                    placeholder="Enter short name"
                                >

                            </div>

                        </div>


                        <!-- DESCRIPTION -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Description

                            </label>


                            <div class="col-sm-6">

                                <textarea
                                    class="form-control"
                                    rows="5"
                                    name="description" id="editor2"
                                    placeholder="Enter category description"
                                ><?php
                                echo isset($_POST['description'])
                                    ? htmlspecialchars(
                                        $_POST['description']
                                    )
                                    : '';
                                ?></textarea>

                            </div>

                        </div>


                        <!-- BANNER -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Banner <span>*</span>

                            </label>


                            <div class="col-sm-4">

                                <input
                                    type="file"
                                    class="form-control"
                                    name="banner"
                                    accept=".jpg,.jpeg,.png,.gif,.webp"
                                >

                            </div>

                        </div>


                        <!-- FEATURES -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Features

                            </label>


                            <div class="col-sm-6">

                                <div id="features-wrapper">

                                    <?php

                                    $old_features =
                                        $_POST['features'] ?? [''];

                                    if(
                                        !is_array($old_features) ||
                                        empty($old_features)
                                    ) {

                                        $old_features = [''];

                                    }

                                    ?>


                                    <?php foreach(
                                        $old_features
                                        as $feature
                                    ): ?>

                                        <div
                                            class="feature-row"
                                            style="
                                                display:flex;
                                                gap:10px;
                                                margin-bottom:10px;
                                            "
                                        >

                                            <input
                                                type="text"
                                                class="form-control"
                                                name="features[]"
                                                value="<?php
                                                echo htmlspecialchars(
                                                    $feature
                                                );
                                                ?>"
                                                placeholder="Enter feature"
                                            >


                                            <button
                                                type="button"
                                                class="btn btn-danger remove-feature"
                                            >
                                                ×
                                            </button>

                                        </div>

                                    <?php endforeach; ?>

                                </div>


                                <button
                                    type="button"
                                    class="btn btn-primary btn-sm"
                                    id="add-feature"
                                >
                                    + Add Feature
                                </button>

                            </div>

                        </div>


                        <!-- APPLICATIONS -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Applications

                            </label>


                            <div class="col-sm-6">

                                <div id="applications-wrapper">

                                    <?php

                                    $old_applications =
                                        $_POST['applications'] ?? [''];

                                    if(
                                        !is_array($old_applications) ||
                                        empty($old_applications)
                                    ) {

                                        $old_applications = [''];

                                    }

                                    ?>


                                    <?php foreach(
                                        $old_applications
                                        as $application
                                    ): ?>

                                        <div
                                            class="application-row"
                                            style="
                                                display:flex;
                                                gap:10px;
                                                margin-bottom:10px;
                                            "
                                        >

                                            <input
                                                type="text"
                                                class="form-control"
                                                name="applications[]"
                                                value="<?php
                                                echo htmlspecialchars(
                                                    $application
                                                );
                                                ?>"
                                                placeholder="Enter application"
                                            >


                                            <button
                                                type="button"
                                                class="btn btn-danger remove-application"
                                            >
                                                ×
                                            </button>

                                        </div>

                                    <?php endforeach; ?>

                                </div>


                                <button
                                    type="button"
                                    class="btn btn-primary btn-sm"
                                    id="add-application"
                                >
                                    + Add Application
                                </button>

                            </div>

                        </div>


                        <!-- SHOW ON MENU -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Show on Menu? <span>*</span>

                            </label>


                            <div class="col-sm-4">

                                <select
                                    name="show_on_menu"
                                    class="form-control"
                                    style="width:auto;"
                                >

                                    <option
                                        value="0"
                                        <?php
                                        echo (
                                            isset(
                                                $_POST['show_on_menu']
                                            ) &&
                                            $_POST['show_on_menu'] == 0
                                        )
                                        ? 'selected'
                                        : '';
                                        ?>
                                    >
                                        No
                                    </option>


                                    <option
                                        value="1"
                                        <?php
                                        echo (
                                            isset(
                                                $_POST['show_on_menu']
                                            ) &&
                                            $_POST['show_on_menu'] == 1
                                        )
                                        ? 'selected'
                                        : '';
                                        ?>
                                    >
                                        Yes
                                    </option>

                                </select>

                            </div>

                        </div>


                        <!-- META TITLE -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Meta Title <span>*</span>

                            </label>


                            <div class="col-sm-4">

                                <input
                                    type="text"
                                    class="form-control"
                                    name="meta_title"
                                    value="<?php
                                    echo isset($_POST['meta_title'])
                                        ? htmlspecialchars(
                                            $_POST['meta_title']
                                        )
                                        : '';
                                    ?>"
                                >

                            </div>

                        </div>


                        <!-- META KEYWORD -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Meta Keyword <span>*</span>

                            </label>


                            <div class="col-sm-4">

                                <textarea
                                    class="form-control"
                                    rows="5"
                                    name="meta_keyword"
                                ><?php
                                echo isset($_POST['meta_keyword'])
                                    ? htmlspecialchars(
                                        $_POST['meta_keyword']
                                    )
                                    : '';
                                ?></textarea>

                            </div>

                        </div>


                        <!-- META DESCRIPTION -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Meta Description <span>*</span>

                            </label>


                            <div class="col-sm-4">

                                <textarea
                                    class="form-control"
                                    rows="5"
                                    name="meta_description"
                                ><?php
                                echo isset($_POST['meta_description'])
                                    ? htmlspecialchars(
                                        $_POST['meta_description']
                                    )
                                    : '';
                                ?></textarea>

                            </div>

                        </div>


                        <!-- SUBMIT -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label"></label>


                            <div class="col-sm-6">

                                <button
                                    type="submit"
                                    class="btn btn-success pull-left"
                                    name="form1"
                                >
                                    Submit
                                </button>

                            </div>

                        </div>


                    </div>

                </div>

            </form>

        </div>

    </div>

</section>


<script>

document.addEventListener(
    'DOMContentLoaded',
    function() {


        /*
        |--------------------------------------------------------------------------
        | ADD FEATURE
        |--------------------------------------------------------------------------
        */

        document
        .getElementById('add-feature')
        .addEventListener(
            'click',
            function() {

                const wrapper =
                    document.getElementById(
                        'features-wrapper'
                    );


                const row =
                    document.createElement('div');


                row.className =
                    'feature-row';


                row.style.cssText =
                    'display:flex;gap:10px;margin-bottom:10px;';


                row.innerHTML = `
                    <input
                        type="text"
                        class="form-control"
                        name="features[]"
                        placeholder="Enter feature"
                    >

                    <button
                        type="button"
                        class="btn btn-danger remove-feature"
                    >
                        ×
                    </button>
                `;


                wrapper.appendChild(row);

            }
        );


        /*
        |--------------------------------------------------------------------------
        | ADD APPLICATION
        |--------------------------------------------------------------------------
        */

        document
        .getElementById('add-application')
        .addEventListener(
            'click',
            function() {

                const wrapper =
                    document.getElementById(
                        'applications-wrapper'
                    );


                const row =
                    document.createElement('div');


                row.className =
                    'application-row';


                row.style.cssText =
                    'display:flex;gap:10px;margin-bottom:10px;';


                row.innerHTML = `
                    <input
                        type="text"
                        class="form-control"
                        name="applications[]"
                        placeholder="Enter application"
                    >

                    <button
                        type="button"
                        class="btn btn-danger remove-application"
                    >
                        ×
                    </button>
                `;


                wrapper.appendChild(row);

            }
        );


        /*
        |--------------------------------------------------------------------------
        | REMOVE FEATURE
        |--------------------------------------------------------------------------
        */

        document.addEventListener(
            'click',
            function(event) {

                if(
                    event.target.classList.contains(
                        'remove-feature'
                    )
                ) {

                    const rows =
                        document.querySelectorAll(
                            '.feature-row'
                        );


                    if(rows.length > 1) {

                        event.target
                            .closest('.feature-row')
                            .remove();

                    }

                }

            }
        );


        /*
        |--------------------------------------------------------------------------
        | REMOVE APPLICATION
        |--------------------------------------------------------------------------
        */

        document.addEventListener(
            'click',
            function(event) {

                if(
                    event.target.classList.contains(
                        'remove-application'
                    )
                ) {

                    const rows =
                        document.querySelectorAll(
                            '.application-row'
                        );


                    if(rows.length > 1) {

                        event.target
                            .closest('.application-row')
                            .remove();

                    }

                }

            }
        );

    }
);

</script>


<?php require_once('footer.php'); ?>