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

$page_meta['title'] = 'Manage Discounts';

$type_names = [
    'percent' => 'Percent off',
    'set'     => 'Set Discount',
    'freedel' => 'Free Delivery',
];

if ($_REQUEST['action'] == 'delete' && is_numeric($_REQUEST['delete_id'])) {
    \Mtc\Shop\DiscountOffer::query()
        ->where('id', '=', $_REQUEST['delete_id'])
        ->delete();
}

$query = \Mtc\Shop\DiscountOffer::query();

$totalnumrows = $query->count();

if (empty($_GET['page'])) {
    $_GET['page'] = 1;
}
$rowsPerPage = 5;
$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$pagestoshow = 10;

$discountOffers = $query->skip($offset)
    ->limit($rowsPerPage)
    ->orderByDesc('date_added')
    ->get();

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

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

<h1>Manage Discounts</h1>

<?php
require_once 'tabnav.php';

$type_names = [
    'nforn'      => 'N for price of n',
    'nforpricen' => 'N for price of &pound; n',
    'amountoff'  => '&pound;n off',
    'percentoff' => 'n% off',
];

if ($discountOffers->count() > 0) {
    ?>

    <table class="manage-items">
        <tr>
            <th>Name</th>
            <th>Redemptions</th>
            <th>Type</th>
            <th class="center">Edit</th>
            <th class="center">Delete</th>
        </tr>
        <tbody class="tabular">

        <?php
        foreach ($discountOffers as $discountOffer) {
            $data = $discountOffer->toArray();
            ?>

            <tr id="rorder-<?= clean_page($data['id']) ?>">
                <td>
                    <a href="edit.discount.php?id=<?= clean_page($data['id']) ?>"><?= clean_page($data['name']) ?></a>
                </td>
                <td>
                    <?= clean_page($data['redemptions']) ?>
                </td>
                <td>
                    <?= $type_names[$data['type']] ?>
                </td>
                <td class="center">
                    <a href="edit.discount.php?id=<?= clean_page($data['id']) ?>" class="edit">
                        <i class="fa fa-pencil"></i>
                    </a>
                </td>
                <td class="center">
                    <a href="manage.discounts.php?action=delete&delete_id=<?= clean_page($data['id']) ?>"
                       class="alert error" title="Are you sure you want to delete this discount?">
                        <i class="fa fa-times-circle"></i>
                    </a>
                </td>
            </tr>
            <?php
        }
        ?>

        </tbody>
    </table>

<?php
} else {
    ?>

    <p>You have not added any discounts.</p>

    <?php
}

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