<?php

use Mtc\Shop\Category;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Event;
use Mtc\Shop\Events\ModelFormFooter;
use MtcPharmacy\Multisite\Classes\MultisiteManager;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$errors = [];

init_request_values([
    'form_id' => null,
]);

$message = '';
$id = !empty($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0;
$sub_id = !empty($_REQUEST['sub_id']) ? (int)$_REQUEST['sub_id'] : 0;
if (!empty($_SESSION['message_category'])) {
    $message = $_SESSION['message_category'];
    unset($_SESSION['message_category']);
}

try {
    $category = Category::findOrFail($id);
    $add_edit = 'Edit';

    $mm = new MultisiteManager($category);
    $mm->ensureTheCorrectAdminPageLoaded();

} catch (ModelNotFoundException $e) {
    $category = new Category();
    $category->sub_id = $sub_id;
    $add_edit = 'Add';
    if ($id > 0) {
        $errors[] = 'Failed to find category, new one will be created on save';
    }
}

$page_meta['title'] = $add_edit . ' Category';

if (!empty($_REQUEST['action'])
    && $_REQUEST['action']=='update'
) {
    if (empty($_REQUEST['name'])) {
        $errors['name'] = 'You must enter a category name';
    }
    if (filter_input(INPUT_POST, 'slug') && Category::slugExists(filter_input(INPUT_POST, 'slug'), $id)) {
        $errors['slug'] = 'This URL Slug is already taken by a different category';
    }

    if (empty($errors)) {
        $category->fill($_REQUEST);


        $category->is_online_doctor = !empty($_REQUEST['is_online_doctor']) ? 1 : 0;
        $category->hide_pharmacy_items = !empty($_REQUEST['hide_pharmacy_items']) ? 1 : 0;

        //Category image
        if (!empty($_FILES['category_image']['size'])) {
            $folders = $image_folders['category_images'];
            $file_data = upload_image('category_image', $folders);
            if (!empty($filedata['error'])) {
                $errors[] = $filedata['error'];
            } else {
                $category->image = $file_data['name'];
            }
        } elseif (!empty($_REQUEST['delete_image']) && !empty($category->image)) {
            foreach ($image_folders['category_images'] as $folder) {
                if (file_exists(SITE_PATH . '/'.$folder['path'].'/' . $category->image)) {
                    unlink(SITE_PATH . '/' . $folder['path'] . '/' . $category->image);
                }
            }
            $category->image = '';
        }

        //Category thumb image
        if (!empty($_FILES['category_thumb_image']['size'])) {
            $folders = $image_folders['category_thumb_images'];
            $file_data = upload_image('category_thumb_image', $folders);
            if (!empty($filedata['error'])) {
                $errors[] = $filedata['error'];
            } else {
                $category->thumb_image = $file_data['name'];
            }
        } elseif (!empty($_REQUEST['delete_thumb_image']) && !empty($category->image)) {
            foreach ($image_folders['category_thumb_images'] as $folder) {
                if (file_exists(SITE_PATH . '/'.$folder['path'].'/' . $category->image)) {
                    unlink(SITE_PATH . '/' . $folder['path'] . '/' . $category->image);
                }
            }
            $category->thumb_image = '';
        }

        $category->save();

        if (isset($mm)) {
            $mm->normaliseSlugs($category->slug);
        }

        $assessment_form = \Mtc\Shop\Assessment\Form::find(request()->input('form_id'));
        $category->assignAssessmentForm($assessment_form);

        $message = 'Category Updated';
        if ($add_edit == 'Add') {
            $_SESSION['message_category'] = 'Category Added';
            header('Location: /shop/admin/categories/edit.category.php?id=' . $category->id);
            exit();
        }
    }
}

require $path .'core/admin/templates/adminheader.html.php';
?>

<?php Event::dispatch('AdminBeforeBreadcrumbs', [ $category->exists ? $category : null ]); ?>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li><a href="manage.categories.php">Categories</a> /</li>
        <li class="end"><?= clean_page($add_edit) ?> Category</li>
    </ul>

    <h1><?= $category->name ?: '(New Category)' ?></h1>
    <br />

<?php
require 'tabnav.php';
if (sizeof($errors) > 0) {
    showerrors($errors);
}
if (!empty($message)) {
    echo showmsg($message, "success", $path);
}

$form_params = [
    'id' => $id
];
?>
    <form action="<?= Util::add_query_arg($form_params) ?>"
          method="post"
          enctype="multipart/form-data"
          class="style">

        <fieldset>
            <div class="row">
                <input type="hidden" name="action" value="update" />
                <input type="hidden" name="id" value="<?= clean_page($category->id) ?>" />
                <input type="submit" value="Save category" />
                <?php if (!empty($category->id)) { ?>
                    <a href="<?= browse_url($category->id) ?>"
                       class="btn actionButton secondaryActionButton"
                       target="_blank">
                        View this category
                    </a>
                <?php } ?>
            </div>
        </fieldset>

        <fieldset class="show">
            <h1>
                <a class="show el">
                    Assessment Form
                    <i class="fa fa-caret-right"></i>
                </a>
            </h1>

            <div class="row">
                <p><small class="warning">This change will affect all products in the category!</small></p>
            </div>

            <div class="row">
                <label for="form_id">Assessment Form</label>
                <select name="form_id" id="form_id">
                    <option value="0">None</option>
                    <?php
                    foreach ((new \Mtc\Shop\Assessment\Form())->orderBy('name')->get() as $form) {
                        $selected = ($form->id === (int)$_REQUEST['form_id'] || $form->id === (int)$category->form_id) ? 'selected' : '';
                        echo "<option value='{$form->id}' {$selected}>{$form->name}</option>";
                    }
                    ?>
                </select>
            </div>
        </fieldset>


        <fieldset class="show">
            <h1>
                <a class="show el">
                    Category Information
                    <i class="fa fa-caret-right"></i>
                </a>
            </h1>
            <?php

            if (CATEGORIES_SUB === true) {
                ?>
                <div class="row">
                    <label for="sub_id">
                        Parent Category
                    </label>
                    <select name="sub_id" id="sub_id">
                        <option value="0">
                            Root
                        </option>
                        <?php
                        echo Category::renderList([
                            'selected' => $category->sub_id,
                            'template' => 'option',
                            'exclude' => $category->id,
                            'show_subs' => true
                        ]);
                        ?>
                    </select>
                </div>
                <?php
            }
            ?>
            <div class="row">
                <label for="name">
                    Name
                </label>
                <input type="text"
                       name="name"
                       id="name"
                       value="<?= clean_page($category->name);?>">
            </div>

            <div class="row">
                <label for="name">
                    Display Name
                </label>
                <input type="text"
                       name="display_name"
                       id="display_name"
                       value="<?= clean_page($category->display_name);?>">
            </div>

            <div class="row">
                <label for="slug">
                    Slug
                </label>
                <input type="text"
                       name="slug"
                       id="slug"
                       value="<?= clean_page($category->slug);?>">
            </div>

            <div class="row">
                <label for="is_online_doctor">Starting Price</label>
                <input type="number"
                       name="starting_price"
                       id="starting_price"
                       value="<?= !empty($category->starting_price) ? clean_page($category->starting_price) : '0.00'; ?>"
                       step="0.01"
                >
            </div>

            <div class="row">
                <label for="is_online_doctor">Landing Page</label>
                <input type="checkbox"
                       name="is_online_doctor"
                       id="is_online_doctor"
                       value="1"
                    <?= $category->is_online_doctor ? 'checked' : ''; ?>
                >
                <div class="defaultValue">
                    <small>Enables landing page for this category.</small>
                </div>
            </div>

            <div class="row">
                <label for="hide_pharmacy_items">Hide Pharmacy Items</label>
                <input type="checkbox"
                       name="hide_pharmacy_items"
                       id="hide_pharmacy_items"
                       value="1"
                    <?= $category->hide_pharmacy_items ? 'checked' : ''; ?>
                >
            </div>
            <?php
            if (CATEGORIES_DESCRIPTION === true) {
                ?>

                <div class="row">
                    <label for="description_small">
                        Description Short
                    </label>
                    <textarea name="description_small"
                              id="description_small"
                              class="tinymce_simple"><?= clean_page($category->description_small) ?></textarea>
                </div>


                <?php
            }
            ?>

        </fieldset>

        <?php
        if (CATEGORIES_IMAGE === true) {
            ?>
            <fieldset class="<?= !empty($category->id) ? 'show' : '' ?>">
                <h1>
                    <a class="show el">
                        Category Image <i class="fa fa-caret-right"></i>
                    </a>
                </h1>
                <?php
                if (!empty($category->image)) {
                    ?>
                    <div class="row">
                        <label>Image</label>
                        <img src="/<?= $image_folders['category_images']['thumbs']['path'] . '/' . clean_page($category->image) ?>" width="200" />
                    </div>
                    <div class="row">
                        <label for="image_alt">Image Alt</label>
                        <input type="text"
                               id="image_alt"
                               name="image_alt"
                               value="<?= clean_page($category->image_alt) ?>"/>
                    </div>

                    <div class="row">
                        <label for="delete_image">
                            Delete Image
                        </label>
                        <input type="checkbox"
                               name="delete_image"
                               id="delete_image"/>
                    </div>
                    <?php
                }
                ?>
                <div class="row">
                    <label for="image">Upload</label>
                    <input id="image" type="file" name="category_image"/>
                </div>
            </fieldset>

            <fieldset class="<?= !empty($category->id) ? 'show' : '' ?>">
                <h1>
                    <a class="show el">
                        Category Thumb Image <i class="fa fa-caret-right"></i>
                    </a>
                </h1>
                <?php
                if (!empty($category->thumb_image)) {
                    ?>
                    <div class="row">
                        <label>Image</label>
                        <img src="/<?= $image_folders['category_thumb_images']['home_image']['path'] . '/' . clean_page($category->thumb_image) ?>" width="200" />
                    </div>
                    <div class="row">
                        <label for="thumb_image_alt">
                            Image Alt
                        </label>
                        <input type="text"
                               id="thumb_image_alt"
                               name="thumb_image_alt"
                               value="<?= clean_page($category->thumb_image_alt) ?>"/>
                    </div>

                    <div class="row">
                        <label for="delete_thumb_image">
                            Delete Image
                        </label>
                        <input type="checkbox"
                               name="delete_thumb_image"
                               id="delete_thumb_image"/>
                    </div>
                    <?php
                }
                ?>
                <div class="row">
                    <label for="image">Upload</label>
                    <input id="image" type="file" name="category_thumb_image"/>
                </div>
            </fieldset>
            <?php
        }

        if (EDITABLE_META_DATA === true) {
            ?>
            <fieldset class="<?= !empty($category->id) ? 'show' : '' ?>">
                <h1>
                    <a class="show el">
                        SEO <i class="fa fa-caret-right"></i>
                    </a>
                </h1>

                <div class="row">
                    <label for="seo_title">Page Title</label>
                    <input type="text"
                           id="seo_title"
                           name="seo_title"
                           value="<?= clean_page($category->seo_title) ?>"
                           class="long">
                </div>

                <div class="row">
                    <label for="seo_keywords">Meta Keywords</label>
                    <input name="seo_keywords"
                           id="seo_keywords"
                           type="text"
                           value="<?= clean_page($category->seo_keywords) ?>"
                           class="long"/>
                </div>

                <div class="row">
                    <label for="seo_description">Meta Description</label>
                    <input name="seo_description"
                           id="seo_description"
                           type="text"
                           value="<?= clean_page($category->seo_description) ?>"
                           class="long"/>
                </div>
            </fieldset>
            <?php
        }
        ?>


        <fieldset class="<?= $adminuser->isMtcAdmin() ? (!empty($category->id) ? 'show' : '') : 'hideme'  ?>">
            <h1>
                <a class="show el">
                    Custom Fields <i class="fa fa-caret-right"></i>
                </a>
            </h1>

            <div class="row">
                <label for="custom_field_set_id">
                    Field Set
                </label>
                <select name="custom_field_set_id" id="custom_field_set_id">
                    <option value="">Select</option>

                    <?php
                    $custom_field_sets = DB::table('custom_fields_sets')->get();
                    foreach ($custom_field_sets as $custom_field_set) {
                        $selected = $custom_field_set->id == $category->custom_field_set_id ? 'selected' : '';
                        ?>
                        <option value="<?= clean_page($custom_field_set->id) ?>" <?= $selected; ?>>
                            <?= clean_page($custom_field_set->name) ?>
                        </option>
                        <?php
                    }
                    ?>
                </select>
            </div>

        </fieldset>

        <?php
        Event::dispatch(new ModelFormFooter($category));
        ?>

        <div class="row">

            <input type="hidden" name="action" value="update" />
            <input type="hidden" name="id" value="<?= clean_page($category->id) ?>" />
            <input type="submit" value="Save category" />
            <?php
            if (!empty($category->id)) {
                ?>
                <a href="<?= browse_url($category->id) ?>"
                   class="btn actionButton secondaryActionButton"
                   target="_blank">
                    View this category
                </a>
                <?php
            }
            ?>
        </div>
    </form>
<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
