<?php
/**
 * Admin - Add Coupon
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Add Coupon';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $code = strtoupper(sanitize($_POST['code'] ?? ''));
        $description = sanitize($_POST['description'] ?? '');
        $discount_type = sanitize($_POST['discount_type'] ?? 'percentage');
        $discount_value = floatval($_POST['discount_value'] ?? 0);
        $min_amount = floatval($_POST['min_amount'] ?? 0);
        $max_discount = floatval($_POST['max_discount'] ?? 0) ?: null;
        $max_uses = intval($_POST['max_uses'] ?? 0) ?: null;
        $user_limit = intval($_POST['user_limit'] ?? 0) ?: null;
        $applies_to = sanitize($_POST['applies_to'] ?? 'all');
        $starts_at = !empty($_POST['starts_at']) ? $_POST['starts_at'] : null;
        $expires_at = !empty($_POST['expires_at']) ? $_POST['expires_at'] : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (empty($code)) $errors[] = 'Coupon code is required';
        if ($discount_value <= 0) $errors[] = 'Discount value must be greater than 0';
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("INSERT INTO coupons 
                    (code, description, discount_type, discount_value, min_amount, max_discount, max_uses, user_limit, applies_to, starts_at, expires_at, is_active, created_by) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $code, $description, $discount_type, $discount_value, $min_amount, $max_discount, $max_uses, $user_limit, $applies_to, $starts_at, $expires_at, $is_active, $_SESSION['admin_id']
                ]);
                redirect(BASE_URL . 'admin/coupons.php', 'success', 'Coupon added successfully');
            } catch (PDOException $e) {
                $errors[] = 'Failed to add coupon: ' . $e->getMessage();
            }
        }
    }
}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Add Coupon</h2>
    <a href="coupons.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-2"></i>Back</a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger"><?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?></div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Coupon Code <span class="text-danger">*</span></label>
                    <input type="text" name="code" class="form-control text-uppercase" required placeholder="e.g., SAVE20">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Discount Type</label>
                    <select name="discount_type" class="form-select">
                        <option value="percentage">Percentage (%)</option>
                        <option value="fixed">Fixed Amount (₹)</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Discount Value <span class="text-danger">*</span></label>
                    <input type="number" name="discount_value" class="form-control" step="0.01" min="0" required>
                </div>
                <div class="col-12">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="2" placeholder="Optional description"></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Minimum Order Amount</label>
                    <input type="number" name="min_amount" class="form-control" step="0.01" value="0">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Maximum Discount (for percentage)</label>
                    <input type="number" name="max_discount" class="form-control" step="0.01" placeholder="No limit">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Max Total Uses</label>
                    <input type="number" name="max_uses" class="form-control" placeholder="Unlimited">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Max Uses Per User</label>
                    <input type="number" name="user_limit" class="form-control" placeholder="Unlimited">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Applies To</label>
                    <select name="applies_to" class="form-select">
                        <option value="all">All Products</option>
                        <option value="plans">Subscription Plans Only</option>
                        <option value="services">Services Only</option>
                        <option value="software">Software Only</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Start Date</label>
                    <input type="date" name="starts_at" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Expiry Date</label>
                    <input type="date" name="expires_at" class="form-control">
                </div>
                <div class="col-12">
                    <div class="form-check">
                        <input type="checkbox" name="is_active" class="form-check-input" id="statusCheck" checked>
                        <label class="form-check-label" for="statusCheck">Active</label>
                    </div>
                </div>
            </div>
            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="bi bi-save me-2"></i>Save Coupon</button>
                <a href="coupons.php" class="btn btn-outline-secondary ms-2">Cancel</a>
            </div>
        </form>
    </div>
</div>

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