<?php
include 'header.php';
require_once '../db/config.php';

// Ensure user is admin
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$pdo = db();
$feedback = [];

// Handle POST requests for creating or toggling coupons
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Create a new coupon
    if (isset($_POST['create_coupon'])) {
        $code = trim($_POST['code']);
        $discount = trim($_POST['discount_percentage']);

        if (!empty($code) && is_numeric($discount) && $discount > 0 && $discount <= 100) {
            try {
                $stmt = $pdo->prepare("INSERT INTO coupons (code, discount_percentage) VALUES (:code, :discount)");
                $stmt->execute(['code' => $code, 'discount' => $discount]);
                $feedback = ['type' => 'success', 'message' => 'Coupon created successfully.'];
            } catch (PDOException $e) {
                if ($e->getCode() == '23505') { // Unique violation
                    $feedback = ['type' => 'danger', 'message' => 'Error: Coupon code already exists.'];
                } else {
                    $feedback = ['type' => 'danger', 'message' => 'Error creating coupon.'];
                }
            }
        } else {
            $feedback = ['type' => 'danger', 'message' => 'Invalid input. Please provide a valid code and a discount percentage between 0 and 100.'];
        }
    }

    // Toggle coupon status
    if (isset($_POST['toggle_status'])) {
        $coupon_id = $_POST['coupon_id'];
        $current_status = $_POST['current_status'];
        $new_status = $current_status ? 'false' : 'true';

        $stmt = $pdo->prepare("UPDATE coupons SET is_active = :status WHERE id = :id");
        $stmt->execute(['status' => $new_status, 'id' => $coupon_id]);
        $feedback = ['type' => 'success', 'message' => 'Coupon status updated.'];
    }
}

// Fetch all coupons
$coupons = $pdo->query("SELECT * FROM coupons ORDER BY created_at DESC")->fetchAll();

?>

<div class="container mt-4">
    <h2>Coupon Management</h2>

    <?php if (!empty($feedback)): ?>
        <div class="alert alert-<?php echo $feedback['type']; ?>" role="alert">
            <?php echo htmlspecialchars($feedback['message']); ?>
        </div>
    <?php endif; ?>

    <!-- Create Coupon Form -->
    <div class="card mb-4">
        <div class="card-header">Create New Coupon</div>
        <div class="card-body">
            <form action="coupons.php" method="POST">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="code">Coupon Code</label>
                            <input type="text" name="code" id="code" class="form-control" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="discount_percentage">Discount (%)</label>
                            <input type="number" name="discount_percentage" id="discount_percentage" class="form-control" step="0.01" min="0.01" max="100" required>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" name="create_coupon" class="btn btn-primary w-100">Create</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Coupons Table -->
    <div class="card">
        <div class="card-header">Existing Coupons</div>
        <div class="card-body">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Discount</th>
                        <th>Status</th>
                        <th>Created At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($coupons as $coupon): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($coupon['code']); ?></td>
                            <td><?php echo number_format($coupon['discount_percentage'], 2); ?>%</td>
                            <td>
                                <?php if ($coupon['is_active']): ?>
                                    <span class="badge bg-success">Active</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo $coupon['created_at']; ?></td>
                            <td>
                                <form action="coupons.php" method="POST">
                                    <input type="hidden" name="coupon_id" value="<?php echo $coupon['id']; ?>">
                                    <input type="hidden" name="current_status" value="<?php echo $coupon['is_active']; ?>">
                                    <button type="submit" name="toggle_status" class="btn btn-sm <?php echo $coupon['is_active'] ? 'btn-warning' : 'btn-success'; ?>">
                                        <?php echo $coupon['is_active'] ? 'Deactivate' : 'Activate'; ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
