<?php

use Mtc\Shop\Brand;

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

init_request_values([
    'id' => null,
    'freeitem' => null,
]);

$page_meta['title'] = 'Manage Discounts';
$display_success_add = false;
$display_success_update = false;

$discount = new DiscountOffer();

if (!empty($_REQUEST['id'])) {

    //prepare for update existing
    $discount->Get($_REQUEST['id']);
    $action_name = 'Update';
    $_SESSION['discount'] = serialize($discount);
} else {

    //prepare for adding new
    $action_name = "Add";
    unset($_SESSION['discount']);
}

//getting existing discount details from session
if (isset($_SESSION['discount']))
{
    $discount = unserialize($_SESSION['discount']);
}

if ($_REQUEST['action'] == 'update') {
    if (empty($_REQUEST['name'])) {
        $errors['name'] = 'Please enter discount name';
    }

    if (empty($_REQUEST['type'])) {
        $errors['type'] = 'Please enter discount type';
    }

    $discount->name = clean_page($_REQUEST['name']);
    $discount->type = clean_page($_REQUEST['type']);
    $discount->value1 = clean_page($_REQUEST['value1']);
    $discount->value2 = clean_page($_REQUEST['value2']);
    $discount->disabled = 0;
    if (!empty($_REQUEST['disabled'])) {
        $discount->disabled = 1;
    }
    $discount->firstorder = 0;
    if (!empty($_REQUEST['firstorder'])) {
        $discount->firstorder = 1;
    }
    $discount->restrictions_min_value = clean_page($_REQUEST['restrictions_min_value']);
    $discount->freeitem = clean_page($_REQUEST['freeitem']);
    $discount->allstock = 0;

    if (!empty($_REQUEST['allstock'])) {
        $discount->allstock = 1;
    }
    $_SESSION['discount'] = serialize($discount);

    //adding restrictions

    //check if unresolved errors from other fields first
    if (empty($errors)) {

        //brands
        if ($_REQUEST['submit'] == 'Add Brand') {
            if (!empty($_REQUEST['brand'])) {

                //check for duplicate
                if (in_array($_REQUEST['brand'], $discount->restrictions_brand)) {
                    $errors['duplicate_brand'] = 'This brand is added already';
                } else {
                    $discount->restrictions_brand[] = clean_page($_REQUEST['brand']);
                    $_SESSION['discount']           = serialize($discount);
                }
            } else {
                $errors['wrong_brand'] = 'Please select brand first';
            }

        }

        //categories
        if ($_REQUEST['submit'] == 'Add Category') {
            if (!empty($_REQUEST['category'])) {

                //check for duplicates
                if (in_array($_REQUEST['category'], $discount->restrictions_categories)) {
                    $errors['duplicate_category'] = 'This category is added already';
                } else {
                    $discount->restrictions_categories[] = clean_page($_REQUEST['category']);
                    $_SESSION['discount']                = serialize($discount);
                }
            } else {
                $errors['wrong_category'] = 'Please select category first';
            }
        }

        //items
        if ($_REQUEST['submit'] == 'Add Item') {
            if (!empty($_REQUEST['item'])) {

                //check for duplicates
                if (in_array($_REQUEST['item'], $discount->restrictions_items)) {
                    $errors['duplicate_item'] = 'This item is added already';
                } else {
                    $discount->restrictions_items[] = clean_page($_REQUEST['item']);
                    $_SESSION['discount']           = serialize($discount);
                }
            } else {
                $errors['wrong_item'] = 'Please select item first';
            }
        }


        if ($_REQUEST['id'] > 0) {

            //updating discount
            $discount->Update();
            $display_success_update = true;
            $_SESSION['discount']   = serialize($discount);

        } else {

            //adding as new discount
            $discount->Add();
            $display_success_add  = true;
            $_REQUEST['id']       = $discount->id;
            $_SESSION['discount'] = serialize($discount);
        }
    }
}

//deleting restrictions: brands
if ($_REQUEST['action'] == 'remove_brand') {
    unset($discount->restrictions_brand[$_REQUEST['brand']]);
    $discount->Update();
    $display_success_update = true;
    $_SESSION['discount'] = serialize($discount);
}

//deleting restrictions: categories
if ($_REQUEST['action'] == 'remove_category') {
    unset($discount->restrictions_categories[$_REQUEST['cat_id']]);
    $discount->Update();
    $display_success_update = true;
    $_SESSION['discount'] = serialize($discount);
}

//deleting restrictions: items
if ($_REQUEST['action'] == 'remove_item') {
    unset($discount->restrictions_items[$_REQUEST['item_id']]);
    $discount->Update();
    $display_success_update = true;
    $_SESSION['discount'] = serialize($discount);
}


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

<form action="edit.discount.php" method="POST">


<!-- Script for lovely discount type change, item selector and clear button -->
<script src=../js/discount_offers.js></script>

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="manage.discounts.php">Manage Discounts</a> /</li>
    <li class="end">Discount</li>
</ul>

<h1>Discount / Offer</h1>

<?php
require_once 'tabnav.php';
if ($display_success_add === true)
{
    if (empty($errors) && isset($_REQUEST['action'])) {
        echo showmsg("Your discount / offer has been saved.", "success", $path);
    }
}
if ($display_success_update === true)
{
    if (empty($errors) && isset($_REQUEST['action'])) {
        echo showmsg("Your discount / offer has been updated.", "success", $path);
    }
}

if (!empty($errors)) {
    showerrors($errors);
}
?>

<fieldset class="show">
    <h1><a class="show el">General Options <i class="fa fa-caret-down"></i></a></h1>

    <!-- Discount name -->
    <div class="row">
        <label for="name">Name</label>
        <input type="text" name="name" id="name" value="<?= clean_page($discount->name) ?>" />
    </div>

    <!-- Discount type -->
    <div class="row">
        <label for="type">Type</label>

        <select name="type" id="type" >
            <option value="">Select Discount Type</option>
            <option value="nforn" <?= ($discount->type == 'nforn') ? 'selected' : '' ?>>N for price of n</option>
            <option value="nforpricen" <?= ($discount->type == 'nforpricen') ? 'selected' : '' ?>>N for price of &pound;n</option>
            <option value="amountoff" <?= ($discount->type == 'amountoff') ? 'selected' : '' ?>>&pound;n off</option>
            <option value="percentoff" <?= ($discount->type == 'percentoff') ? 'selected' : '' ?>>n% off</option>
        </select>
    </div>

    <!-- Values 1 and 2 -->
    <div class="row" id="row_value1">
        <label for="value1">Value 1</label>
        <input type="text" name="value1"
               id="value1" value="<?= clean_page($discount->value1) ?>"/>
    </div>

    <div class="row" id="row_value2">
        <label for="value2">Value 2</label>
        <input type="text" name="value2"
               id="value2" value="<?= clean_page($discount->value2) ?>"/>
    </div>

    <!-- Order Value -->
    <div class="row">
        <label for="restrictions_min_value">Min Order Value (&pound;)</label>
        <input type="text" name="restrictions_min_value"
               id="restrictions_min_value"
               value="<?= clean_page($discount->restrictions_min_value) ?>"/>
    </div>

    <!-- First Order? -->
    <div class="row">
        <label for="firstorder">First Order</label>
        <input type="checkbox" name="firstorder"
               id="firstorder" <?= ($discount->firstorder == 1) ? 'checked' : '' ?> />
    </div>

    <!-- Disabled? -->
    <div class="row">
        <label for="disabled">Disabled</label>
        <input type="checkbox" name="disabled"
               id="disabled" <?= ($discount->disabled == 1) ? 'checked' : ''  ?> />
    </div>

    <!-- All items? -->
    <div class="row">
        <label for="allstock">Applies to all stock including sale items</label>
        <input type="checkbox" name="allstock"
               id="allstock" <?= ($discount->allstock == 1) ? 'checked' : '' ?> />
    </div>

</fieldset>


<fieldset class="show">

    <h1><a class="show el">Restrictions - Brands <i class="fa fa-caret-down"></i></a></h1>

    <?php

    //Restricted Brands - list
    if (!empty($discount->restrictions_brand)) {
    ?>

        <table class="manage-items">

            <?php

            //delete links
            foreach ($discount->restrictions_brand as $key => $brand_id) {
            ?>

                <tbody class="tabular ui-sortable">
                <tr>
                    <td><?= clean_page(brand_name($brand_id)) ?></td>


                    <td class="center">
                        <a href="edit.discount.php?action=remove_brand&brand=<?= clean_page($key) ?>&id=<?= clean_page($_REQUEST['id']) ?>"
                           class="alert picto error"
                           title="Are you sure you want to remove this restriction?">
                            <i class="fa fa-times-circle"></i>
                        </a>
                    </td>

                </tr>
                </tbody>

            <?php
            }
            ?>

        </table>

    <?php
    }
    ?>

    <!-- Brand select list -->
    <div class="row">
        <label for="brand">Brand</label>
        <select name="brand" id="brand">
            <option value="">Select</option>

            <?php
            $brands = Brand::query()
                ->where('deleted', '=', 0)
                ->orderBy('name')
                ->get();
            foreach ($brands as $brand) {

                //check if already added and exclude from select dropdown if true
                if (!in_array($brand->id, $discount->restrictions_brand)) {
                ?>

                    <option value="<?= clean_page($brand->id) ?>"><?= clean_page($brand->name) ?></option>

            <?php
                }
            }
            ?>

        </select>

        <input type="submit" name="submit" value="Add Brand"/>

    </div>

</fieldset>

<fieldset class="show">
    <h1><a class="show el">Restrictions - Categories <i class="fa fa-caret-down"></i></a></h1>

    <?php

    //Restricted categories - list
    if (!empty($discount->restrictions_categories)) {
    ?>

        <table class="manage-items">

            <?php
            foreach ($discount->restrictions_categories as $key => $cat_id) {

            ?>

                <tbody class="tabular ui-sortable">
                <tr>
                    <td><?= clean_page(category_name($cat_id)) ?></td>

                    <!-- Delete links -->
                    <td class="center">
                        <a href="edit.discount.php?action=remove_category&cat_id=<?= clean_page($key) ?>&id=<?= clean_page($_REQUEST['id']) ?>"
                           class="alert picto error"
                           title="Are you sure you want to remove this restriction?">
                            <i class="fa fa-times-circle"></i>
                        </a>
                    </td>
                </tr>
                </tbody>

            <?php
            }
            ?>

        </table>

    <?php
    }
    ?>

    <div class="row">
        <label for="category">Category</label>
        <select name="category" id="category">
            <option value="">Select Category</option>

            <!-- array param to check if already added and exclude from select dropdown if true -->
            <?= get_the_categories(0,1,$discount->restrictions_categories) ?>
        </select>

        <input type="submit" name="submit" value="Add Category" id="category"/>
    </div>

</fieldset>

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

    <?php

    //Restricted items - list
    if (!empty($discount->restrictions_items)) {
    ?>

        <table class="manage-items">

            <?php
            foreach ($discount->restrictions_items as $key => $item_id) {
            ?>

                <tbody class="tabular ui-sortable">
                <tr>
                    <td><?= clean_page(item_name($item_id)) ?></td>

                    <!-- Delete links -->
                    <td class="center">
                        <a href="edit.discount.php?action=remove_item&item_id=<?= clean_page($key) ?>&id=<?= clean_page($_REQUEST['id']) ?>"
                           class="alert picto error"
                           title="Are you sure you want to remove this restriction?">
                            <i class="fa fa-times-circle"></i>
                        </a>
                    </td>
                </tr>
                </tbody>

            <?php
            }
            ?>

        </table>

    <?php
    }
    ?>


    <div class="row">
        <label for="item">Item</label>
        <input type="hidden" name="item"
               id="item" value="<?= clean_page($item->complimented[$i] ?? null) ?>"/>
        <input type="text" name="item_name"
               id="item_name" value="" readonly="" class="INPUT1 short"/>

        <!-- Manage products.mini for selecting items -->
        <a class="btn" id="browse_button">Browse</a>

        <!-- Clear -->
        <a class="btn cancel" id="clear_button">Clear</a>

        <input type="submit" name="submit" value="Add Item" class="INPUT1 btn"/>

    </div>

</fieldset>


<input type="hidden" name="action" value="update" />
<input type="hidden" name="id" value="<?= clean_page($_REQUEST['id']) ?>"/>

<br />
<br />

<input type="submit" name="submit" value="Save" />

</form>

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