<?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 Mtc\Cms\Models\AssetGalleryIcon;
use MtcPharmacy\Multisite\Classes\MultisiteManager;
use App\CategoryInfo;


$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;



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


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


        //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();

        CategoryInfo::saveForItem($category->id);

        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 (count($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">Online Doctor category</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
            }
            ?>

            <div class="row">
                <label for="faq">
                    Overview Title
                </label>
                <input name="overview_title"
                       id="overview_title"
                       value="<?= clean_page($category->overview_title) ?>">
            </div>

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


            <div class="row">
                <label for="faq">
                    Causes Title
                </label>
                <input name="causes_title"
                       id="causes_title"
                       value="<?= clean_page($category->causes_title) ?>">
            </div>

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


            <div class="row">
                <label for="faq">
                    Symptoms Title
                </label>
                <input name="symptoms_title"
                       id="symptoms_title"
                       value="<?= clean_page($category->symptoms_title) ?>">
            </div>

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


            <div class="row">
                <label for="faq">
                    Treatments Title
                </label>
                <input name="treatments_title"
                       id="treatments_title"
                       value="<?= clean_page($category->treatments_title) ?>">
            </div>

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



        </fieldset>


        <?php /*
    <fieldset class="show js_movable">
        <h1>
            <a class="show el">
                Category Info sections<i class="fa fa-caret-right"></i>
            </a>
        </h1>

        <?php
        if(!empty($category->id)) {
            echo CategoryInfo::renderInfoRecordsForm($category->id);
        }
        ?>

    </fieldset>
*/?>

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


        <div class="row">
            <label for="background_colour">
                Background Colour
            </label>
            <input name="background_colour"
                   id="background_colour"
                   value="<?= $category->background_colour ?>"
                   type="color"
                   style="padding: 0 2px"
            />
        </div>

        <div class="row">
            <label for="url_to_category_products">
                URL to category products
            </label>
            <input name="url_to_category_products"
                   id="url_to_category_products"
                   value="<?= $category->url_to_category_products ?>"
                   type="text"
            />
        </div>

        <div class="row">
            <label for="product_list_title">
                Product List Title
            </label>
            <input name="product_list_title"
                   id="product_list_title"
                   value="<?= $category->product_list_title ?>">
        </div>

        <div class="row">
            <label for="product_list_subtitle">
                Product List Subtitle
            </label>
            <input name="product_list_subtitle"
                   id="product_list_subtitle"
                   value="<?= $category->product_list_subtitle ?>">
        </div>

    </fieldset>
*/?>

        <fieldset class="<?= !empty($category->id) ? 'show' : '' ?>">
            <h1>
                <a class="show el">
                    Description Block <i class="fa fa-caret-right"></i>
                </a>
            </h1>


            <div class="row">
                <label for="faq">
                    Description Title
                </label>
                <input name="description_title"
                       id="description_title"
                       value="<?= clean_page($category->description_title) ?>">
            </div>


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


            <?php
            if (!empty($category->description_image)) {
                ?>
                <div class="row">
                    <label>Description Image</label>
                    <img src="/<?= $image_folders['category_images']['thumbs']['path'] . '/' . clean_page($category->description_image) ?>" width="200" />
                </div>
                <div class="row">
                    <label for="image_alt">Description Image Alt</label>
                    <input type="text"
                           id="description_image_alt"
                           name="description_image_alt"
                           value="<?= clean_page($category->description_image_alt) ?>"/>
                </div>

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

        <?php /*
    <fieldset class="<?= !empty($category->id) ? 'show' : '' ?>">
        <h1>
            <a class="show el">
                FAQs Content <i class="fa fa-caret-right"></i>
            </a>
        </h1>


        <div class="row">
            <label for="faq">
                FAQs Title
            </label>
            <input name="faq_title"
                   id="faq_title"
                   value="<?= clean_page($category->faq_title) ?>">
        </div>

        <div class="row">
            <label for="faq">
                FAQS Intro
            </label>
            <textarea name="faq"
                      id="faq"
                      class="tinymce_simple"><?= clean_page($category->faq) ?></textarea>
        </div>


        <?php
        if (!empty($category->faq_image)) {
            ?>
            <div class="row">
                <label>FAQs Image</label>
                <img src="/<?= $image_folders['category_images']['thumbs']['path'] . '/' . clean_page($category->faq_image) ?>" width="200" />
            </div>
            <div class="row">
                <label for="image_alt">FAQs Image Alt</label>
                <input type="text"
                       id="faq_image_alt"
                       name="faq_image_alt"
                       value="<?= clean_page($category->faq_image_alt) ?>"/>
            </div>

            <div class="row">
                <label for="delete_image">
                    Delete Image
                </label>
                <input type="checkbox"
                       name="faq_delete_image"
                       id="faq_delete_image"/>
            </div>
            <?php
        }
        ?>
        <div class="row">
            <label for="image">Upload</label>
            <input id="faq_image" type="file" name="faq_category_image"/>
        </div>
    </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
        }
        ?>


        <?php if ($category->id): ?>

            <fieldset class="show js-vue-environment">
                <h1>
                    <a class="show el">
                        Display Tags 1<i class="fa fa-caret-right"></i>
                    </a>
                </h1>

                <display-tags-manager
                        data-url="<?= route('admin-shop-category-display-tags', [ $category->id ], false) ?>"
                        save-data-url="<?= route('admin-shop-category-display-tags-save', [ $category->id ], false) ?>"
                        :available-icons='<?= json_encode(AssetGalleryIcon::getAvailable()) ?>'
                ></display-tags-manager>
            </fieldset>

        <?php endif ?>

        <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';
