<?php

use Mtc\Core\PaginationTemplate;
use Mtc\Shop\Category;
use Illuminate\Support\Facades\DB;
use MtcPharmacy\Multisite\Classes\MultisiteConstants;
use MtcPharmacy\Multisite\Classes\MultisiteManager;
use MtcPharmacy\Multisite\Classes\MultisiteSite;
use App\MultisiteHelper;


$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
$page_meta['title'] = 'Manage Categories';

$errors = [];

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

$message = filter_input(INPUT_GET, 'message');

$per_page = 25;
$page = !empty($_REQUEST['page']) ? (int)$_REQUEST['page'] : 1;
$sub_id = !empty($_REQUEST['sub_id']) ? (int)$_REQUEST['sub_id'] : 0;

if (CATEGORIES_HIDE === true) {
    $hidepage = [
        'action' => 'hidepage',
    ];
    $showpage = [
        'action' => 'showpage',
    ];
    $hideall = [
        'action' => 'hideall',
    ];
    $showall = [
        'action' => 'showall',
    ];
}

if (!empty($_REQUEST['action'])
    && $_REQUEST['action'] == 'update'
    && !empty($_REQUEST['ids'])
    && count($_REQUEST['ids']) > 0
) {
    foreach ($_REQUEST['ids'] as $id) {
        Category::query()->where('id', $id)
            ->update([
                'hide' => !empty($_REQUEST[$id . '_hide']) ? 1 : 0,
            ]);
    }
    $message = 'Categories updated';
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'export_categories__multisite') {
    MultisiteHelper::export(
        MultisiteConstants::ENTITY_TYPE_SHOP_CATEGORY,
        $_REQUEST
    );
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'import_categories') {
    $response = MultisiteHelper::import(
        MultisiteConstants::ENTITY_TYPE_SHOP_CATEGORY,
        $_REQUEST
    );
    if (! $response['errors']) {
        $query_params = $_GET;
        $query_params['success'] = 'import_successful';
        $_SESSION['flash_messages']['success'] = $response['success'];
        header('Location: manage.categories.php?' . http_build_query($query_params));
        exit;
    } else {
        $errors = $response['errors'];
    }
}

if (!empty($_REQUEST['action'])
    && $_REQUEST['action'] == 'delete'
    && !empty($_REQUEST['delete_id'])
) {
    // We need to remove current category and all its children
    $categories = Category::getFlatTree($_REQUEST['delete_id']);

    foreach ($categories as $category) {
        if (!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);
                }
            }
        }
        DB::table('items_categories')
            ->where('cat_id', $category->id)
            ->delete();
        $category->delete();
    }
    $message = 'Category and all its children removed';
}

$categories = Category::query()
    ->selectRaw('categories.*')
    ->orderBy('order', 'ASC')
    ->orderBy('name', 'ASC');

if (filter_input(INPUT_GET, 'action') === 'search') {
    $categories->where('name', 'LIKE', '%' . $_REQUEST['name'] . '%');
} else {
    $categories->childOf($sub_id);
}

MultisiteManager::decorateQueryBaseOnly($categories, MultisiteConstants::ENTITY_TYPE_SHOP_CATEGORY);

$pagination_items = $categories->get()->slice(($page - 1) * $per_page, $per_page)->all();

if (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'hidepage') {
    foreach ($pagination_items as $category) {
        Category::query()->where('id', $category->id)
            ->update(['hide' => 1]);
    }
    $message = 'All Categories on this page are set to be hidden';
    $params = [
        'page' => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/categories/manage.categories.php?' . http_build_query($params));
    exit;
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'showpage') {
    foreach ($pagination_items as $category) {
        Category::query()->where('id', $category->id)
            ->update(['hide' => 0]);
    }
    $message = 'All Categories on this page are set to be shown';
    $params = [
        'page' => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/categories/manage.categories.php?' . http_build_query($params));
    exit;

}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'hideall') {
    $allcatagories = $categories->get();
    foreach ($allcatagories as $category) {
        Category::query()->where('id', $category->id)
            ->update(['hide' => 1]);
    }
    $message = 'All Categories are set to be hidden';
    $params = [
        'page' => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/categories/manage.categories.php?' . http_build_query($params));
    exit;
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'showall') {
    $allcategories = $categories->get();
    foreach ($allcategories as $category) {
        Category::query()->where('id', $category->id)
            ->update(['hide' => 0]);
    }
    $message = 'All Categories are set to be shown';
    $params = [
        'page' => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/categories/manage.categories.php?' . http_build_query($params));
    exit;
}

$query_string = '';
$append = [];

if (!empty($sub_id)) {
    $append['sub_id'] = $sub_id;
}
if (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'search') {
    $append['action'] = 'search';
    $append['name'] = $_REQUEST['name'];
    $query_string = '?action=search&name=' . $_REQUEST['name'];
}

if (!empty($append)) {
    $query_string = '?' . http_build_query($append);
}

$pagination = new PaginationTemplate([
    'item_count' => $categories->count(),
    'per_page' => $per_page,
    'active_page' => $page,
    'show_view_all' => false,
    'page_url' => '/shop/admin/categories/manage.categories.php' . $query_string,
]);
$pagination = $pagination->render($twig);

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

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li><a href="/shop/admin/categories/manage.categories.php">Categories</a> /</li>
    </ul>

    <h1>Categories</h1>

<?php
include 'tabnav.php';

if (empty($errors) && isset($GLOBALS['flash_messages']) && !empty($GLOBALS['flash_messages']['success'])) {
    echo showmsg($GLOBALS['flash_messages']['success'], 'success', $path);
}

if (!empty($errors)) {
    showerrors($errors);
}
if (!empty($message)) {
    echo showmsg($message, 'success', $path);
}

?>
    <form action="manage.categories.php" method="get" class="style">
        <fieldset class="show">
            <h1><a class="show el">Search <i class="fa fa-caret-right"></i></a></h1>

            <div class="row">
                <label for="name">Name</label>
                <input type="text" name="name" id="name" value="<?= clean_page($_REQUEST['name']) ?>">
            </div>

            <input type="hidden" name="action" value="search">
            <div class="search-button"><input type="submit" value="Search" class="BUTTON"/></div>
        </fieldset>
    </form>
<?php

if (count($pagination_items) > 0) {
    ?>

    <form action="" method="post">
        <?= $pagination; ?>
        <table class="manage-items">
            <tr>
                <th class="center">Order</th>
                <th>Category</th>
                <th>Is Online Doctor?</th>
                <?php
                if (CATEGORIES_SUB === true) {
                    ?>
                    <th>Parent Category</th>
                    <th>Sub Categories</th>
                    <?php
                }


                if (CATEGORIES_HIDE === true) {
                    ?>
                    <th class="center">Hide<br/>
                        <small>
                            <a href="<?= Util::add_query_arg($hidepage) ?>"
                               class="alert"
                               title="Are you sure you want to set everything on this page to be hidden?">
                                <small>Hide All</small>
                            </a>
                            <br/>
                            <a href="<?= Util::add_query_arg($showpage) ?>"
                               class="alert"
                               title="Are you sure you want to set everything on this page to be viewable?">
                                <small>Show&nbsp;All</small>
                            </a>
                        </small>
                    </th>
                    <?php
                }
                ?>
                <th class="center">Edit</th>
                <th class="center">Delete</th>
            </tr>
            <tbody class="tabular ui-sortable">
            <?php
            foreach ($pagination_items as $category) {
                ?>
                <tr id="rorder-<?= clean_page($category->id) ?>">
                    <td class="center order">
                        <i class="fa fa-arrows"></i>
                    </td>
                    <td>
                        <a href="edit.category.php?id=<?= clean_page($category->id); ?>">
                            <?= clean_page($category->name); ?>
                        </a>
                        <input type="hidden"
                               name="ids[]"
                               value="<?= clean_page($category->id) ?>"/>
                    </td>
                    <td>
                        <i class="fa fa-<?= $category->is_online_doctor ? 'check' : 'remove' ?>"></i>
                    </td>
                    <?php
                    if (CATEGORIES_SUB === true) {
                        ?>
                        <td>
                            <?= clean_page($category->parent->name ?? 'Root') ?>
                        </td>
                        <td>


                        <?php

                            $direct_children_query = $category->children();
                            MultisiteManager::decorateQueryBaseOnly($direct_children_query, MultisiteConstants::ENTITY_TYPE_SHOP_CATEGORY);
                            $direct_children = $direct_children_query->get();

                        ?>

                            <a href="manage.categories.php?sub_id=<?= clean_page($category->id) ?>">
                            View sub-categories (<?= $direct_children->count() ?>)
                            </a>

                            <br />

                            <?php if ($direct_children->count()): ?>
                                <?php $number_of_subitems_to_display = 6; ?>
                                <ul>
                                    <?php foreach ($direct_children->take($number_of_subitems_to_display) as $sub_item): ?>
                                        <li>&nbsp;- <?= $sub_item->name ?></li>
                                    <?php endforeach ?>

                                    <?php if ($direct_children->count() > $number_of_subitems_to_display): ?>
                                        <li>&nbsp;- (more)</li>
                                    <?php endif ?>
                                </ul>
                            <?php else: ?>
                                &nbsp;&nbsp;&nbsp;(empty)
                            <?php endif ?>

                        </td>
                        <?php
                    }



                    if (CATEGORIES_HIDE === true) {
                        ?>
                        <td class="center">
                            <input type="checkbox"
                                   name="<?= clean_page($category->id); ?>_hide"
                                   value="1"
                                <?= $category->hide == 1 ? 'checked="checked"' : '' ?>/>
                        </td>
                    <?php } ?>
                    <td class="center">
                        <a href="edit.category.php?id=<?= clean_page($category->id); ?>"
                           class="edit">
                            <i class="fa fa-pencil"></i>
                        </a>
                    </td>
                    <td class="center">
                        <?php
                        $delete_params = [
                            'sub_id' => $sub_id,
                            'action' => 'delete',
                            'delete_id' => $category->id,
                            'page' => $page
                        ]
                        ?>
                        <a href="<?= Util::add_query_arg($delete_params) ?>"
                           class="alert error"
                           title="Are you sure you want to delete this category?">
                            <i class="fa fa-times-circle"></i>
                        </a>
                    </td>
                </tr>
                <?php
            }
            ?>
            </tbody>
        </table>
        <p>
            <?php
            if (CATEGORIES_HIDE === true) {
            ?>
            <input type="hidden" name="action" value="update">
            <input type="submit" value="Update"/>
            <input type="hidden" id="orderbytable" value="categories"/>
            <input type="hidden" id="orderbyfield" value="order"/>

            <?php
            echo $pagination;
            if (CATEGORIES_HIDE === true) {
            ?>
            <br/>
            <br/>
        <div class="style">
            <fieldset class="show">
                <h1><a class="show el">Advanced Options <i class="fa fa-caret-right"></i></a></h1>
                <h5>Site-Wide Hide Settings</h5>
                <div class="row">

                    <a href="<?= Util::add_query_arg($hideall) ?>"
                       class="alert"
                       title="This will set ALL Categories on the site to be hidden, are you sure you want to do that?">
                        Hide All Categories
                    </a>
                    <br/>
                    <b class="error">Warning:</b> This will set all Categories across the site to be set to
                    <b>hidden</b>
                </div>

                <div class="row">
                    <a href="<?= Util::add_query_arg($showall) ?>"
                       class="alert"
                       title="This will set ALL Categories on the site to be viewable, are you sure you want to do that?">
                        Show All Categories
                    </a>
                    <br/>
                    <b class="error">Warning:</b> This will set all Categories across the site to be set to
                    <b>visible</b>
                </div>
            </fieldset>
        </div>
    <?php
    }
    }
    ?>
        <input type="hidden" name="page" value="<?= $page ?>"/>
        <input type="hidden" name="sub_id" value="<?= $sub_id ?>"/>
        </p>
    </form>
    <?php
} elseif ($_REQUEST['action'] == 'search') {
    ?>
    <p>No categories found matching your search criteria</p>
    <?php
} else {
    ?>
    <p>There are currently no categories added</p>
    <?php
}

?>


<form method="post" class="style">
    <h2>Export <?php //(multisite)?></h2>

    <div class="row">
        <input type="hidden" name="action" value="export_categories__multisite"/>
        <?php foreach (MultisiteSite::all() as $site_data): ?>
            <button
                type="submit"
                name="multisite__site_id"
                value="<?= $site_data->id ?>"
                class="btn"
            >
                <?= 'Export' //$site_data->name ?>
            </button>
        <?php endforeach ?>
    </div>
</form>

<form method="post" enctype="multipart/form-data" class="style">
    <h2>Import</h2>
    <fieldset>
        <div class="row">
            <label for="select_file">File selection</label>
            <input type="file" name="import" />
        </div>
        <div class="row">
            <input type="hidden" name="action" value="import_categories"/>
            <button
                type="submit"
                class="btn"
            >
                Import
            </button>
        </div>
    </fieldset>
</form>


<?php require_once $path . 'core/admin/templates/adminfooter.html.php'; ?>
