<?php
use Mtc\Shop\Coupon;
use Mtc\Shop\Coupon\Condition as CouponCondition;
use Mtc\Shop\Coupon\Code as CouponCode;
use Illuminate\Database\Eloquent\ModelNotFoundException;

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

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

try {
    $coupon = Coupon::findOrFail($id);
    $add_edit = 'Edit';
} catch (ModelNotFoundException $e) {
    $coupon = new Coupon();
    $coupon->from_date = date('Y-m-d');
    $coupon->exp_date = date('Y-m-d', time() + Util::SECONDS_IN_A_DAY);
    $add_edit = 'Add';
    if ($id > 0) {
        $errors[] = 'Failed to find coupon, new one will be created on save';
    }
}

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


if (!empty($_POST['action']) && $_POST['action'] == 'add') {
    //Removes all non-alphanumeric characters
    $code = preg_replace('/[^\da-z]/i', '', $_POST['code']);

    if (empty($_POST['code'])) {
        $errors['code'] = 'You did not enter a code for the coupon.';
    } elseif (empty($_POST['id']) && (Coupon::exists($code) || CouponCode::exists($code))) {
        $errors['code'] = 'There is already a coupon with that code.';
    }

    if (empty($_POST['from_date'])) {
        $errors['from_date'] = 'You did not enter a start date for the coupon';
    } elseif (!validate_date($_POST['from_date'])) {
        $errors['from_date'] = 'You did not enter a valid start date for the coupon';
    }

    if (empty($_POST['exp_date'])) {
        $errors['exp_date'] = 'You did not enter an expiry date for the coupon';
    } elseif (!validate_date($_POST['exp_date'])) {
        $errors['exp_date'] = 'You did not enter a valid expiry date for the coupon';
    }

    if ((empty($_REQUEST['id']) || $coupon->structure === 'single') && (empty($_POST['redemptions']) || !is_numeric($_POST['redemptions']))) {
        $errors['redemptions'] = 'Please enter a number for the amount of redemptions';
    }

    if (!(isset($_POST['value']) && is_numeric($_POST['value']))) {
        $errors['value'] = 'Please enter a value for the coupon';
    }

    $coupon->fill($_POST);
    $coupon->from_date = substr(date_dmy_to_db($_POST['from_date']),0,10);
    $coupon->exp_date = substr(date_dmy_to_db($_POST['exp_date']),0,10);
    $coupon->code = $code;

    if (empty($errors)) {
        $coupon->save();
        foreach (CouponCondition::$types as $type) {
            if (!empty($_POST[$type])) {
                CouponCondition::updateByType($coupon, $type, $_POST[$type]);
            }
        }

        $message = 'Coupon Updated';
        if ($add_edit == 'Add') {
            if ($coupon->structure == 'multi') {
                //Generate coupon codes
                CouponCode::generateBulk($coupon,['number' => $_POST['redemptions']]);
            }
            $_SESSION['message_coupon'] = 'Coupon Added';
            header('Location: /shop/admin/coupons/edit.coupon.php?id=' . $coupon->id);
            exit();
        }
    }
}

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


    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li><a href="manage.coupons.php">Manage Coupons</a> /</li>
        <li class="end"><?= clean_page($add_edit) ?> Coupon</li>
    </ul>

    <h1><?= clean_page($add_edit) ?> Coupon</h1>

<?php
include 'tabnav.php';
if (!empty($message)) {
    echo showmsg($message, "success", $path);
}
if (sizeof($errors) > 0) {
    showerrors($errors);
}
$url_params = [
    'id' => $coupon->id
];
?>

    <form action="<?= Util::add_query_arg($url_params) ?>"
          method="post"
          class="style">
        <fieldset class="show">
            <h1>
                <a class="show el">
                    General Options
                    <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($coupon->name) ?>">
            </div>
            <div class="row">
                <label for="code">Code</label>
                <input type="text"
                       name="code"
                       id="code"
                       value="<?= clean_page($coupon->code) ?>">
            </div>
            <div class="row">
                <label for="type">Type</label>
                <select name="type" id="type">
                    <?php
                    foreach (Coupon::$coupon_types as $key => $type) {
                        ?>
                        <option value="<?= clean_page($key) ?>"
                            <?= $key == $coupon->type ? "selected" : ''?>>
                            <?=$type?>
                        </option>
                        <?php
                    }
                    ?>
                </select>
            </div>
            <?php
            if (empty($_REQUEST['id'])) {
                ?>
                <div class="row">
                    <label for="structure">Coupon structure</label>
                    <select name="structure" id="structure">
                        <?php
                        foreach (Coupon::$coupon_structures as $key => $structure) {
                            ?>
                            <option value="<?= clean_page($key) ?>" <?= $key == $coupon->structure ? "selected" : ''; ?>>
                                <?= clean_page($structure); ?>
                            </option>
                            <?php
                        }
                        ?>
                    </select>
                </div>
                <?php
            }
            ?>
            <div class="row">
                <label for="from_date">Start Date</label>
                <input type="text"
                       name="from_date"
                       value="<?= date_convert_db_to_dmy($coupon->from_date);?>"
                       id="from_date"
                       class="datepicker">
            </div>
            <div class="row">
                <label for="exp_date">Expiry Date</label>
                <input type="text"
                       name="exp_date"
                       value="<?= date_convert_db_to_dmy($coupon->exp_date);?>"
                       id="exp_date"
                       class="datepicker">
            </div>
            <?php if (empty($_REQUEST['id']) || $coupon->structure == 'single') { ?>
                <div class="row">
                    <label for="redemptions">
                        <?php
                        if (empty($_REQUEST['id'])) {
                            echo "Redemptions / Number of codes";
                        } else {
                            echo "Redemptions";
                        }
                        ?>
                    </label>
                    <input type="text"
                           name="redemptions"
                           id="redemptions"
                           value="<?= clean_page($coupon->redemptions) ?>">
                </div>
            <?php } ?>
            <div class="row">
                <label for="value">Value (&pound; / % )</label>
                <input type="text"
                       name="value"
                       id="value"
                       value="<?= clean_page($coupon->value) ?>">
            </div>
            <div class="row">
                <label for="min_price">Minimum Spend (&pound;)</label>
                <input type="text"
                       name="min_price"
                       id="min_price"
                       value="<?= clean_page($coupon->min_price) ?>" />
            </div>
            <div class="row checkboxes">
                <label class="master">
                    Include Free Delivery
                </label>

                <input type="radio"
                       name="free_delivery"
                       id="free_delivery_no"
                       value="0"
                    <?= $coupon->free_delivery == 0 ? 'checked' : '' ?>/>
                <label for="free_delivery_no">
                    No
                </label>

                <input type="radio"
                       name="free_delivery"
                       id="free_delivery_uk"
                       value="2"
                    <?= $coupon->free_delivery == 2 ? 'checked' : '' ?>/>
                <label for="free_delivery_uk">
                    UK Only
                </label>

                <input type="radio"
                       name="free_delivery"
                       id="free_delivery_all"
                       value="1"
                    <?= $coupon->free_delivery == 1 ? 'checked' : '' ?>/>
                <label for="free_delivery_all">
                    Anywhere
                </label>
            </div>
            <?php
            if (COUPONS_ADVANCED === true) {
                ?>
                <div class="row">
                    <label for="non_sale_only">
                        Exclude Sale Items
                    </label>
                    <input type="radio"
                           id="non_sale_only_yes"
                           name="non_sale_only"
                           value="1"
                        <?= $coupon->non_sale_only == 1 ? 'checked' : '' ?>/>
                    <label for="non_sale_only_yes">
                        Yes
                    </label>

                    <input type="radio"
                           id="non_sale_only_no"
                           name="non_sale_only"
                           value="0"
                        <?= $coupon->non_sale_only == 0 ? 'checked' : '' ?>/>
                    <label for="non_sale_only_no">
                        No
                    </label>
                </div>
                <div class="row">
                    <label for="first_order">
                        Apply only to orders by new customers
                    </label>
                    <input type="radio"
                           id="first_order_yes"
                           name="first_order"
                           value="1"
                        <?= $coupon->first_order == 1 ? 'checked' : '' ?>/>
                    <label for="first_order_yes">
                        Yes
                    </label>

                    <input type="radio"
                           id="first_order_no"
                           name="first_order"
                           value="0"
                        <?= $coupon->first_order == 0 ? 'checked' : '' ?>/>
                    <label for="first_order_no">
                        No
                    </label>
                </div>
                <?php
            }
            ?>
        </fieldset>
        <?php
        if (COUPONS_ADVANCED === true) {
            if (COUPONS_MAX_ITEM_COUNT > 0) {
                $items = $coupon->conditions()
                    ->where('type', 'item')
                    ->get();
                ?>
                <fieldset>
                    <h1>
                        <a class="show el">
                            Apply to Specific Item
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>
                    <?php
                    for ($i = 1; $i <= COUPONS_MAX_ITEM_COUNT; $i++) {
                        $item_id = 0;
                        if (!empty($items[$i - 1])) {
                            $item_id = !empty($items[$i - 1]->value) ? $items[$i - 1]->value : 0;
                        }
                        $item_name = !empty($item_id) ? item_name($item_id) : '';
                        ?>
                        <div class="row">
                            <label for="item_id">
                                Item <?= COUPONS_MAX_ITEM_COUNT > 1 ? $i : '' ?>
                            </label>
                            <input type="hidden"
                                   name="item[]"
                                   id="item_<?= $i ?>"
                                   value="<?= clean_page($item_id) ?>"
                                   class="INPUT1"/>
                            <input type="text"
                                   name="item_name[]"
                                   id="item_<?= $i ?>_name"
                                   value="<?= clean_page($item_name) ?>"
                                   class="short"/>
                            <a class="btn js_findItem"
                               data-field="item_<?= $i ?>">
                                Browse
                            </a>
                            <a class="btn cancel js_cancelSelection"
                               data-field="item_<?= $i ?>">
                                Clear
                            </a>
                        </div>
                        <?php
                    }
                    ?>
                </fieldset>
                <?php
            }
            if (COUPONS_MAX_CATEGORY_COUNT > 0) {
                $categories = $coupon->conditions()
                    ->where('type', 'category')
                    ->excluded(0)
                    ->get();
                ?>
                <fieldset>
                    <h1>
                        <a class="show el">
                            Apply to Specific Categories
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>

                    <?php
                    for ($i = 0; $i < COUPONS_MAX_CATEGORY_COUNT; $i++) {
                        $category_label = 'Category ' . ($i + 1);
                        $category = $categories[$i] ?? null;
                        ?>
                        <div class="row">
                            <label for="category_<?= $i ?>"><?= $category_label ?></label>
                            <select name="category[<?= $i; ?>]" id="category_<?= $i ?>">
                                <option value="">No Category</option>
                                <?= get_the_categories(clean_page($category['value'] ?? null)) ?>
                            </select>
                        </div>
                    <?php } ?>
                </fieldset>
                <?php
            }
            if (COUPONS_MAX_EXCLUDE_CATEGORY_COUNT > 0) {
                $categories = $coupon->conditions()
                    ->where('type', 'category')
                    ->excluded(1)
                    ->get();
                ?>
                <fieldset>
                    <h1>
                        <a class="show el">
                            Exclude Categories
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>
                    <?php
                    for ($i = 0; $i < COUPONS_MAX_EXCLUDE_CATEGORY_COUNT; $i++) {
                        $category_label = 'Category ' . ($i + 1);
                        $category = $categories[$i] ?? null;
                        ?>
                        <div class="row">
                            <label for="exclude_category_<?= $i ?>"><?= $category_label ?></label>
                            <select name="exclude_category[<?= $i; ?>]" id="exclude_category_<?= $i ?>">
                                <option value="">No Category</option>
                                <?= get_the_categories(clean_page($category['value'] ?? null)) ?>
                            </select>
                        </div>
                    <?php } ?>
                </fieldset>
                <?php
            }
            if (COUPONS_MAX_BRAND_COUNT > 0) {
                $brands = $coupon->conditions()
                    ->where('type', 'brand')
                    ->excluded(0)
                    ->get();
                ?>
                <fieldset>
                    <h1>
                        <a class="show el">
                            Apply to Specific Brands
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>
                    <?php
                    for ($i = 1; $i <= COUPONS_MAX_BRAND_COUNT; $i++) {
                        $brand_id = 0;
                        if (!empty($brands[$i - 1])) {
                            $brand_id = !empty($brands[$i - 1]->value) ? $brands[$i - 1]->value : 0;
                        }
                        $brand_name = !empty($brand_id) ? brand_name($brand_id) : '';
                        ?>
                        <div class="row">
                            <label for="brand">
                                Brand <?= COUPONS_MAX_BRAND_COUNT > 1 ? $i : '' ?>
                            </label>
                            <input type="hidden"
                                   name="brand[]"
                                   id="brand_<?= $i ?>"
                                   value="<?= clean_page($brand_id) ?>"
                                   class="short"/>
                            <input type="text"
                                   name="brand_name[]"
                                   id="brand_<?= $i ?>_name"
                                   value="<?= clean_page($brand_name) ?>"
                                   class="short"/>

                            <a class="btn js_findBrand"
                               data-field="brand_<?= $i ?>">
                                Browse
                            </a>
                            <a class="btn cancel js_cancelSelection"
                               data-field="brand_<?= $i ?>">
                                Clear
                            </a>
                        </div>
                        <?php
                    }
                    ?>
                </fieldset>
                <?php
            }
            if (COUPONS_MAX_EXCLUDE_BRAND_COUNT > 0) {
                $brands = $coupon->conditions()
                    ->where('type', 'brand')
                    ->excluded(1)
                    ->get();
                ?>
                <fieldset>
                    <h1>
                        <a class="show el">
                            Exclude Brands
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>
                    <?php
                    for ($i = 1; $i <= COUPONS_MAX_EXCLUDE_BRAND_COUNT; $i++) {
                        $brand_id = 0;
                        if (!empty($brands[$i - 1])) {
                            $brand_id = !empty($brands[$i - 1]->value) ? $brands[$i - 1]->value : 0;
                        }
                        $brand_name = !empty($brand_id) ? brand_name($brand_id) : '';
                        ?>
                        <div class="row">
                            <label for="exclude_brand">
                                Brand <?= COUPONS_MAX_EXCLUDE_BRAND_COUNT > 1 ? $i : '' ?>
                            </label>
                            <input type="hidden"
                                   name="exclude_brand[]"
                                   id="exclude_brand_<?= $i ?>"
                                   value="<?= clean_page($brand_id) ?>"
                                   class="short"/>
                            <input type="text"
                                   name="exclude_brand_name[]"
                                   id="exclude_brand_<?= $i ?>_name"
                                   value="<?= clean_page($brand_name) ?>"
                                   class="short"/>
                            <a class="btn js_findBrand"
                               data-field="exclude_brand_<?= $i ?>">
                                Browse
                            </a>
                            <a class="btn cancel js_cancelSelection"
                               data-field="exclude_brand_<?= $i ?>">
                                Clear
                            </a>
                        </div>
                        <?php
                    }
                    ?>
                </fieldset>
                <?php
            }
        }
        ?>

        <input type="hidden"
               name="action"
               value="add"/>
        <input type="hidden"
               name="id"
               value="<?= clean_page($coupon->id) ?>"/>

        <div class="save-button">
            <input type="submit" value="Save"/>
        </div>
    </form>
<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
