<?php
/**
 * @author: Uldis Zvirbulis <uldis.zvirbulis@mtcmedia.co.uk>
 * @version: 3/14/2017
 */

use Mtc\Shop\Coupon;
use Mtc\Shop\Coupon\Code as CouponCode;
use Illuminate\Database\Eloquent\Model;

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

$page_meta['title'] = 'Manage Coupon Codes';

$errors = [];
$append = "";
if (!empty($_REQUEST['action'])) {
    if ($_REQUEST['action'] === 'delete' && is_numeric($_REQUEST['delete_id'])) {
        CouponCode::find($_REQUEST['delete_id'])->delete();
    } elseif ($_REQUEST['action'] === 'generate_codes') {
        $coupon_id = (int)$_REQUEST['coupon_id'];
        $number_of_codes = (int)$_REQUEST['number_of_codes'];
        $coupon = new Coupon();
        if (empty($coupon_id)) {
            $errors['coupon_id'] = 'Please specify coupon.';
        } else {
            $coupon = Coupon::find($coupon_id);
            if ($coupon->structure !== 'multi') {
                $errors['structure'] = 'Codes can only be generated for Multi codes coupons';
            }
        }
        if (empty($number_of_codes)) {
            $errors['number_of_codes'] = 'Please set a number of coupon codes to be generated.';
        }
        if (empty($errors)) {
            CouponCode::generateBulk($coupon, ['number' => $number_of_codes]);
            header('location: /shop/admin/coupons/manage.coupons.codes.php?coupon_id=' . $coupon_id);
            exit;
        }
    } elseif ($_REQUEST['action'] === 'export_csv') {
        $coupon_codes = CouponCode::search($_REQUEST)->get();
        if (!empty($coupon_codes)) {
            //$rows = [];
            $rows[] = ['Coupon', 'Code', 'Order ID'];
            foreach ($coupon_codes as $coupon_code) {
                $rows[] = [
                    $coupon_code->coupon->name,
                    $coupon_code->code,
                    $coupon_code->order_id,
                ];
            }

            $filename = "coupon_codes_export_" . date("Y-m-d") . ".csv";

            $download_file = fopen($filename, 'w');
            foreach ($rows as $row) {
                fputcsv($download_file, $row, ',');
            }
            fclose($download_file);

            \Util::force_download($filename, file_get_contents($filename));
            unlink($filename);
            exit;
        }

    }
}

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

$coupons = Coupon::where('structure', '=', 'multi')->orderBy('id', 'DESC')->get();

if (!empty($_REQUEST['coupon_id'])) {
    $append .= "&coupon_id=" . $_REQUEST['coupon_id'];
}

if (!empty($_REQUEST['code'])) {
    $append .= "&code=" . $_REQUEST['code'];
}

if (!empty($_REQUEST['status'])) {
    $append .= "&status=" . $_REQUEST['status'];
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == "search") {
    $append .= "&action=search";
}

$rowsPerPage = 25;
$pageNum = empty($_GET['page']) ? 1 : $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$pagestoshow = 10;

$coupon_codes = CouponCode::search($_REQUEST);
$totalnumrows = $coupon_codes->count();
$coupon_codes = $coupon_codes->orderBy('code', 'ASC')->skip($offset)->take($rowsPerPage)->get();

?>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li class="end">Manage Coupon Codes</li>
    </ul>

    <h1>Manage Coupon Codes</h1>
<?php
include __DIR__ . '/tabnav.php';
if (!empty($message)) {
    echo showmsg($message, "success", $path);
}
if (!empty($errors)) {
    showerrors($errors);
}
?>
    <form action="" 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="coupon_id">Coupon</label>
                <select name="coupon_id" id="coupon_id">
                    <option value="">All</option>
                    <?php
                    foreach ($coupons as $coupon) {
                        ?>
                        <option value="<?= clean_page($coupon->id) ?>"
                            <?= (!empty($_REQUEST['coupon_id']) && $coupon->id == $_REQUEST['coupon_id']) ? "selected" : ''; ?>>
                            <?= clean_page($coupon->name . ' (' . $coupon->code . ')'); ?>
                        </option>
                        <?php
                    }
                    ?>
                </select>
            </div>

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

            <div class="row">
                <label for="status">Status</label>
                <select name="status" id="status">
                    <option value="all">All</option>
                    <option value="unused" <?= (!empty($_REQUEST['status']) && $_REQUEST['status'] === 'unused') ? 'selected' : ''; ?>>Unused</option>
                    <option value="used" <?= (!empty($_REQUEST['status']) && $_REQUEST['status'] === 'used') ? 'selected' : ''; ?>>Used</option>
                </select>
            </div>

            <input type="hidden" name="action" value="search">
            <div class="row">
                <div class="search-button"><input type="submit" value="Search" class="BUTTON"/></div>
            </div>
        </fieldset>
    </form>
    <form action="" method="get" class="style">
        <fieldset class="">
            <h1><a class="show el">Generate new codes <i class="fa fa-caret-right"></i></a></h1>

            <div class="row">
                <label for="coupon_id">Coupon</label>
                <select name="coupon_id" id="coupon_id">
                    <?php
                    foreach ($coupons as $coupon) {
                        ?>
                        <option value="<?= clean_page($coupon->id) ?>"
                            <?= (!empty($_REQUEST['coupon_id']) && $coupon->id == $_REQUEST['coupon_id']) ? "selected" : ''; ?>>
                            <?= clean_page($coupon->name . ' (' . $coupon->code . ')'); ?>
                        </option>
                        <?php
                    }
                    ?>
                </select>
            </div>

            <div class="row">
                <label for="code">Number of codes</label>
                <input type="text" name="number_of_codes" id="number_of_codes" value="">
            </div>

            <input type="hidden" name="action" value="generate_codes">
            <div class="row save-button">
                <input type="submit" value="Generate"/>
            </div>
        </fieldset>
    </form>
<?php
if ($coupon_codes->count() > 0) {
    ?>
    <table class="manage-items">
        <tr>
            <th>Coupon</th>
            <th>Code</th>
            <th class="center">Order</th>
            <th class="center">Delete</th>
        </tr>
        <tbody class="tabular">
        <?php
        $flag = 1;
        foreach ($coupon_codes as $coupon_code) {
            $flag = !$flag;
            ?>
            <tr id="rorder-<?=$coupon_code->id?>">
                <td>
                    <a href="edit.coupon.php?id=<?= $coupon_code->coupon_id;?>">
                        <?= clean_page($coupon_code->coupon->name);?>
                    </a>
                </td>
                <td><?= clean_page($coupon_code->code);?></td>
                <td class="center">
                    <a href="/shop/admin/orders/manage.order.php?id=<?= $coupon_code->order_id;?>">
                        <?=$coupon_code->order_id > 0 ? $coupon_code->order_id : '-'; ?>
                    </a>
                </td>
                <td class="center">
                    <a href="manage.coupons.codes.php?action=delete&delete_id=<?= $coupon_code->id;?>"
                       class="alert error"
                       title="Are you sure you want to delete this coupon code?">
                        <i class="fa fa-times-circle"></i>
                    </a>
                </td>
            </tr>
            <?php
        }
        ?>
        </tbody>
    </table>
    <form action="" method="post">
        <div class="row">
            <input type="hidden" name="action" value="export_csv"/><input type="submit" value="Export CSV" class="submit"/>
        </div>
    </form>
    <?php
} elseif (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'search') {
    ?>
    <p>No coupon codes found matching your search criteria</p>
    <?php
}

include $path . 'core/admin/templates/pagination.php';

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