<?php
session_start();
if (!isset($_SESSION['unohs'])) { header("location:index.php"); exit; }
include "../deepanshu/conn.php";

$message = '';

// ✅ নতুন Promo-Code তৈরি করা
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create') {
    $code = strtoupper(trim($_POST['code'] ?? ''));
    $bonusAmount = (float)($_POST['bonus_amount'] ?? 0);
    $usageLimit = (int)($_POST['usage_limit'] ?? 1);
    $expiryDate = trim($_POST['expiry_date'] ?? '');

    if ($code === '' || $bonusAmount <= 0 || $usageLimit <= 0) {
        $message = "❌ সব Field সঠিকভাবে পূরণ করো (Code, Bonus-Amount, Usage-Limit)";
    } else {
        $checkStmt = $conn->prepare("SELECT id FROM promo_codes WHERE code = ?");
        $checkStmt->bind_param("s", $code);
        $checkStmt->execute();
        if ($checkStmt->get_result()->num_rows > 0) {
            $message = "❌ এই Code ('$code') আগে থেকেই আছে, অন্য নাম দাও";
        } else {
            $expiryValue = $expiryDate !== '' ? $expiryDate : null;
            $stmt = $conn->prepare("INSERT INTO promo_codes (code, bonus_amount, usage_limit, expiry_date, is_active) VALUES (?, ?, ?, ?, 1)");
            $stmt->bind_param("sdis", $code, $bonusAmount, $usageLimit, $expiryValue);
            $stmt->execute();
            $message = "✅ নতুন Promo-Code ('$code') সফলভাবে তৈরি হয়েছে";
        }
    }
}

// ✅ Active/Inactive Toggle করা
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $conn->query("UPDATE promo_codes SET is_active = 1 - is_active WHERE id = $id");
    header("Location: admin_promo_codes.php");
    exit;
}

// ✅ Delete করা
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM promo_codes WHERE id = $id");
    header("Location: admin_promo_codes.php");
    exit;
}

$codes = $conn->query("SELECT * FROM promo_codes ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title>Promo-Code Management</title>
<style>
    body { background: #0a0a0a; color: #fff; font-family: sans-serif; padding: 20px; }
    h2 { color: #ffd54f; margin-bottom: 20px; }
    .msg { padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; }
    .msg-ok { background: rgba(34,214,122,.15); border: 1px solid rgba(34,214,122,.3); color: #22D67A; }
    .msg-err { background: rgba(255,92,122,.15); border: 1px solid rgba(255,92,122,.3); color: #FF5C7A; }

    .create-form { background: #171420; border: 1px solid #333; border-radius: 12px; padding: 20px; margin-bottom: 30px; }
    .create-form h3 { color: #ffd54f; margin-bottom: 16px; font-size: 15px; }
    .form-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 12px; }
    .form-row label { font-size: 11px; color: #9691B0; display: block; margin-bottom: 4px; text-transform: uppercase; }
    .form-row input { width: 100%; padding: 10px; border-radius: 6px; border: 1px solid #333; background: #0a0a0a; color: #fff; font-size: 13px; }
    .btn-create { padding: 12px 30px; border-radius: 8px; border: none; background: #ffd54f; color: #000; font-weight: 700; cursor: pointer; font-size: 14px; }

    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 12px; border-bottom: 1px solid #222; text-align: left; font-size: 13px; }
    th { color: #ffd54f; background: #171420; }
    .code-text { font-weight: 800; color: #9B5DE5; font-family: monospace; }
    .status-active { color: #22D67A; font-weight: 700; }
    .status-inactive { color: #FF5C7A; font-weight: 700; }
    .btn-sm { padding: 5px 12px; border-radius: 6px; border: none; font-size: 11px; font-weight: 700; cursor: pointer; margin-right: 6px; text-decoration: none; display: inline-block; }
    .btn-toggle { background: #4EA8FF; color: #fff; }
    .btn-delete { background: #FF5C7A; color: #fff; }
</style>
</head>
<body>

<h2>🎫 Promo-Code Management</h2>

<?php if ($message): ?>
    <div class="msg <?= strpos($message, '✅') === 0 ? 'msg-ok' : 'msg-err' ?>"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="create-form">
    <h3>➕ নতুন Promo-Code তৈরি করো</h3>
    <form method="POST">
        <input type="hidden" name="action" value="create">
        <div class="form-row">
            <div>
                <label>Code (যেমন WELCOME50)</label>
                <input type="text" name="code" required maxlength="30" placeholder="SUMMER100">
            </div>
            <div>
                <label>Bonus-Amount (৳)</label>
                <input type="number" name="bonus_amount" required step="0.01" min="1" placeholder="100">
            </div>
            <div>
                <label>Usage-Limit (কতজন ব্যবহার করতে পারবে)</label>
                <input type="number" name="usage_limit" required min="1" placeholder="500" value="1">
            </div>
            <div>
                <label>মেয়াদ শেষ (ঐচ্ছিক)</label>
                <input type="date" name="expiry_date">
            </div>
        </div>
        <button type="submit" class="btn-create">Code তৈরি করো</button>
    </form>
</div>

<h3 style="color:#ffd54f; margin-bottom:14px;">📋 সব Promo-Code</h3>
<table>
    <tr>
        <th>Code</th>
        <th>Bonus</th>
        <th>ব্যবহৃত / সীমা</th>
        <th>মেয়াদ</th>
        <th>Status</th>
        <th>তৈরি হয়েছে</th>
        <th>Action</th>
    </tr>
    <?php while ($row = $codes->fetch_assoc()): ?>
    <tr>
        <td><span class="code-text"><?= htmlspecialchars($row['code']) ?></span></td>
        <td>৳<?= number_format($row['bonus_amount'], 2) ?></td>
        <td><?= $row['used_count'] ?> / <?= $row['usage_limit'] ?></td>
        <td><?= $row['expiry_date'] ? htmlspecialchars($row['expiry_date']) : 'কখনো না' ?></td>
        <td><span class="<?= $row['is_active'] ? 'status-active' : 'status-inactive' ?>"><?= $row['is_active'] ? 'Active' : 'Inactive' ?></span></td>
        <td><?= htmlspecialchars($row['created_at']) ?></td>
        <td>
            <a href="?toggle=<?= $row['id'] ?>" class="btn-sm btn-toggle"><?= $row['is_active'] ? 'বন্ধ করো' : 'চালু করো' ?></a>
            <a href="?delete=<?= $row['id'] ?>" class="btn-sm btn-delete" onclick="return confirm('নিশ্চিত? এই Code মুছে ফেলবে।')">Delete</a>
        </td>
    </tr>
    <?php endwhile; ?>
</table>

</body>
</html>
