<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_admin();

$pageTitle = 'Coupons';
$success = '';
$error = '';
$editCoupon = null;

if (isset($_GET['created'])) {
    $success = 'Coupon created successfully.';
}

if (isset($_GET['updated'])) {
    $success = 'Coupon updated successfully.';
}

if (isset($_GET['deleted'])) {
    $success = 'Coupon deleted successfully.';
}

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];

    $stmt = $pdo->prepare("SELECT * FROM coupons WHERE id = ? LIMIT 1");
    $stmt->execute([$editId]);
    $editCoupon = $stmt->fetch();

    if (!$editCoupon) {
        $error = 'Coupon not found.';
    }
}

if (isset($_GET['delete'])) {
    $deleteId = (int) $_GET['delete'];

    $stmt = $pdo->prepare("DELETE FROM coupons WHERE id = ?");
    $stmt->execute([$deleteId]);

    redirect(ADMIN_URL . '/coupons.php?deleted=1');
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $couponId = (int) ($_POST['coupon_id'] ?? 0);

        $couponCode = strtoupper(trim($_POST['coupon_code'] ?? ''));
        $couponType = $_POST['coupon_type'] ?? 'percentage';
        $couponValue = (float) ($_POST['coupon_value'] ?? 0);
        $minOrderAmount = (float) ($_POST['min_order_amount'] ?? 0);
        $maxDiscountAmount = $_POST['max_discount_amount'] !== '' ? (float) $_POST['max_discount_amount'] : null;
        $usageLimit = $_POST['usage_limit'] !== '' ? (int) $_POST['usage_limit'] : null;
        $startDate = $_POST['starts_at'] !== '' ? $_POST['starts_at'] : null;
        $endDate = $_POST['expires_at'] !== '' ? $_POST['expires_at'] : null;
        $status = $_POST['status'] ?? 'active';

        if ($couponCode === '') {
            $error = 'Coupon code is required.';
        } elseif (!preg_match('/^[A-Z0-9_-]+$/', $couponCode)) {
            $error = 'Coupon code can only contain letters, numbers, hyphen, and underscore.';
        } elseif (!in_array($couponType, ['percentage', 'fixed'], true)) {
            $error = 'Invalid discount type.';
        } elseif ($couponValue <= 0) {
            $error = 'Discount value must be greater than zero.';
        } elseif ($couponType === 'percentage' && $couponValue > 100) {
            $error = 'Percentage discount cannot be greater than 100.';
        } elseif (!in_array($status, ['active', 'inactive', 'expired'], true)) {
            $error = 'Invalid status.';
        } else {
            if ($couponId > 0) {
                $check = $pdo->prepare("SELECT id FROM coupons WHERE coupon_code = ? AND id != ? LIMIT 1");
                $check->execute([$couponCode, $couponId]);
            } else {
                $check = $pdo->prepare("SELECT id FROM coupons WHERE coupon_code = ? LIMIT 1");
                $check->execute([$couponCode]);
            }

            if ($check->fetch()) {
                $error = 'This coupon code already exists.';
            } else {
                if ($couponId > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE coupons
                        SET coupon_code = ?,
                            coupon_type = ?,
                            coupon_value = ?,
                            min_order_amount = ?,
                            max_discount_amount = ?,
                            usage_limit = ?,
                            starts_at = ?,
                            expires_at = ?,
                            status = ?
                        WHERE id = ?
                    ");

                    $stmt->execute([
                        $couponCode,
                        $couponType,
                        $couponValue,
                        $minOrderAmount,
                        $maxDiscountAmount,
                        $usageLimit,
                        $startDate,
                        $endDate,
                        $status,
                        $couponId
                    ]);

                    redirect(ADMIN_URL . '/coupons.php?updated=1');
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO coupons (
                            coupon_code,
                            coupon_type,
                            coupon_value,
                            min_order_amount,
                            max_discount_amount,
                            usage_limit,
                            used_count,
                            starts_at,
                            expires_at,
                            status
                        ) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $couponCode,
                        $couponType,
                        $couponValue,
                        $minOrderAmount,
                        $maxDiscountAmount,
                        $usageLimit,
                        $startDate,
                        $endDate,
                        $status
                    ]);

                    redirect(ADMIN_URL . '/coupons.php?created=1');
                }
            }
        }
    }
}

$coupons = $pdo->query("
    SELECT *
    FROM coupons
    ORDER BY id DESC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Coupons</h1>
            <div class="admin-user">Create and manage discount codes for checkout.</div>
        </div>

        <?php if ($editCoupon): ?>
            <a href="<?= e(ADMIN_URL); ?>/coupons.php" class="admin-btn admin-btn-light">Cancel Edit</a>
        <?php endif; ?>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2><?= $editCoupon ? 'Edit Coupon' : 'Add New Coupon'; ?></h2>

        <form method="POST">
            <?= csrf_field(); ?>

            <input type="hidden" name="coupon_id" value="<?= e($editCoupon['id'] ?? 0); ?>">

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Coupon Code *</label>
                    <input
                        type="text"
                        name="coupon_code"
                        value="<?= e($editCoupon['coupon_code'] ?? ''); ?>"
                        placeholder="WELCOME10"
                        required
                    >
                </div>

                <div class="admin-field">
                    <label>Discount Type *</label>
                    <select name="coupon_type">
                        <option value="percentage" <?= ($editCoupon['coupon_type'] ?? 'percentage') === 'percentage' ? 'selected' : ''; ?>>
                            Percentage
                        </option>
                        <option value="fixed" <?= ($editCoupon['coupon_type'] ?? '') === 'fixed' ? 'selected' : ''; ?>>
                            Fixed Amount
                        </option>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Discount Value *</label>
                    <input
                        type="number"
                        step="0.01"
                        name="coupon_value"
                        value="<?= e($editCoupon['coupon_value'] ?? ''); ?>"
                        required
                    >
                </div>

                <div class="admin-field">
                    <label>Minimum Order Amount</label>
                    <input
                        type="number"
                        step="0.01"
                        name="min_order_amount"
                        value="<?= e($editCoupon['min_order_amount'] ?? 0); ?>"
                    >
                </div>

                <div class="admin-field">
                    <label>Maximum Discount Amount</label>
                    <input
                        type="number"
                        step="0.01"
                        name="max_discount_amount"
                        value="<?= e($editCoupon['max_discount_amount'] ?? ''); ?>"
                    >
                </div>

                <div class="admin-field">
                    <label>Usage Limit</label>
                    <input
                        type="number"
                        name="usage_limit"
                        value="<?= e($editCoupon['usage_limit'] ?? ''); ?>"
                        placeholder="Leave empty for unlimited"
                    >
                </div>

                <div class="admin-field">
                    <label>Start Date</label>
                    <input
                        type="date"
                        name="starts_at"
                        value="<?= !empty($editCoupon['starts_at']) ? e(date('Y-m-d', strtotime($editCoupon['starts_at']))) : ''; ?>"
                    >
                </div>

                <div class="admin-field">
                    <label>End Date</label>
                    <input
                        type="date"
                        name="expires_at"
                        value="<?= !empty($editCoupon['expires_at']) ? e(date('Y-m-d', strtotime($editCoupon['expires_at']))) : ''; ?>"
                    >
                </div>

                <div class="admin-field">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?= ($editCoupon['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>
                            Active
                        </option>
                        <option value="inactive" <?= ($editCoupon['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>
                            Inactive
                        </option>
                        <option value="expired" <?= ($editCoupon['status'] ?? '') === 'expired' ? 'selected' : ''; ?>>
                            Expired
                        </option>
                    </select>
                </div>
            </div>

            <button type="submit" class="admin-btn">
                <?= $editCoupon ? 'Update Coupon' : 'Create Coupon'; ?>
            </button>
        </form>
    </section>

    <section class="admin-panel">
        <h2>All Coupons</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Code</th>
                    <th>Type</th>
                    <th>Value</th>
                    <th>Min Order</th>
                    <th>Max Discount</th>
                    <th>Limit</th>
                    <th>Used</th>
                    <th>Dates</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$coupons): ?>
                    <tr>
                        <td colspan="10">No coupons created yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($coupons as $coupon): ?>
                    <tr>
                        <td><strong><?= e($coupon['coupon_code']); ?></strong></td>

                        <td><?= e(ucfirst($coupon['coupon_type'])); ?></td>

                        <td>
                            <?php if ($coupon['coupon_type'] === 'percentage'): ?>
                                <?= e(number_format((float) $coupon['coupon_value'], 2)); ?>%
                            <?php else: ?>
                                <?= e(format_price($coupon['coupon_value'])); ?>
                            <?php endif; ?>
                        </td>

                        <td><?= e(format_price($coupon['min_order_amount'] ?? 0)); ?></td>

                        <td>
                            <?= !empty($coupon['max_discount_amount'])
                                ? e(format_price($coupon['max_discount_amount']))
                                : 'No max'; ?>
                        </td>

                        <td><?= e($coupon['usage_limit'] ?? 'Unlimited'); ?></td>

                        <td><?= e($coupon['used_count'] ?? 0); ?></td>

                        <td>
                            <?= !empty($coupon['starts_at']) ? e(date('d M Y', strtotime($coupon['starts_at']))) : 'No start'; ?><br>
                            <small>
                                <?= !empty($coupon['expires_at']) ? e(date('d M Y', strtotime($coupon['expires_at']))) : 'No end'; ?>
                            </small>
                        </td>

                        <td><?= e(ucfirst($coupon['status'])); ?></td>

                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/coupons.php?edit=<?= e($coupon['id']); ?>">
                                Edit
                            </a>

                            <a
                                class="admin-btn"
                                href="<?= e(ADMIN_URL); ?>/coupons.php?delete=<?= e($coupon['id']); ?>"
                                onclick="return confirm('Delete this coupon?');"
                            >
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>