<?php
// Safely start session
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

// Require database configuration
require_once 'config.php';

$user_number = $_SESSION['number'] ?? $_SESSION['mobile'] ?? $_SESSION['phone'] ?? $_SESSION['username'] ?? null; 

// ---------------------------------------------------------
// AJAX CLAIM HANDLER
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'claim_gift') {
    header('Content-Type: application/json');
    if (!isset($pdo) || !$user_number) {
        echo json_encode(['success' => false, 'message' => 'Not logged in or DB error']);
        exit;
    }

    $code = trim($_POST['code'] ?? '');
    
    if (empty($code)) {
        echo json_encode(['success' => false, 'message' => 'Please enter a gift code']);
        exit;
    }

    try {
        $pdo->beginTransaction();

        // 1. Check if code exists and is active
        $stmt = $pdo->prepare("SELECT id, amount, max_claims, claims_used FROM giftcodes WHERE code = ? AND status = 1 FOR UPDATE");
        $stmt->execute([$code]);
        $gift = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$gift) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Invalid or expired gift code']);
            exit;
        }

        // 2. Check if claim limit reached
        if ($gift['claims_used'] >= $gift['max_claims']) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'This gift code has been fully claimed']);
            exit;
        }

        // 3. Check if user already claimed this code
        $stmt_check = $pdo->prepare("SELECT id FROM giftcode_claims WHERE user_number = ? AND giftcode_id = ?");
        $stmt_check->execute([$user_number, $gift['id']]);
        if ($stmt_check->fetch()) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'You have already claimed this gift code']);
            exit;
        }

        $amount = $gift['amount'];

        // 4. Record the claim
        $stmt_insert = $pdo->prepare("INSERT INTO giftcode_claims (user_number, giftcode_id, amount) VALUES (?, ?, ?)");
        $stmt_insert->execute([$user_number, $gift['id'], $amount]);

        // 5. Update giftcode usage
        $stmt_update_gift = $pdo->prepare("UPDATE giftcodes SET claims_used = claims_used + 1 WHERE id = ?");
        $stmt_update_gift->execute([$gift['id']]);

        // 6. Credit user balance AND apply 1x wager
        $stmt_update_user = $pdo->prepare("UPDATE users SET balance = balance + ?, wager = wager + ? WHERE number = ?");
        $stmt_update_user->execute([$amount, $amount, $user_number]);

        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Successfully claimed Rs' . number_format($amount, 2)]);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'An error occurred, please try again.']);
    }
    exit;
}
// ---------------------------------------------------------

// Fetch User's Claim History
$claim_history = [];
if ($user_number && isset($pdo)) {
    try {
        $stmt = $pdo->prepare("SELECT amount, claimed_at FROM giftcode_claims WHERE user_number = ? ORDER BY id DESC LIMIT 50");
        $stmt->execute([$user_number]);
        $claim_history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // Ignore if table doesn't exist yet
    }
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
    <title>Reward Redemption Code</title>
    <!-- FontAwesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>

        /* ========================================================
           HEADER
           ======================================================== */
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px 20px;
            background-color: var(--bg-header);
            position: sticky;
            top: 0;
            z-index: 10;
            border-bottom: 1px solid var(--border-color);
        }

        .header-title {
            font-size: 18px;
            font-weight: 700;
            flex-grow: 1;
            text-align: center;
        }

        .header .btn-icon {
            color: var(--text-main);
            font-size: 20px;
            cursor: pointer;
            text-decoration: none;
            width: 24px;
            display: flex;
            justify-content: center;
        }

        .header .btn-icon.right {
            color: var(--primary-orange);
            font-size: 18px;
        }

        /* ========================================================
           PAGE CONTENT
           ======================================================== */
        .page-content {
            padding: 15px;
        }

        .banner-img {
            width: 100%;
            border-radius: 8px;
            display: block;
            margin-bottom: 20px;
            border: 1px solid var(--border-color);
        }

        /* ========================================================
           REDEMPTION CARD
           ======================================================== */
        .redemption-card {
            background-color: var(--bg-header);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
        }

        .redemption-title {
            font-size: 14px;
            color: var(--text-main);
            margin-bottom: 15px;
            font-weight: 500;
        }

        .input-group {
            margin-bottom: 20px;
        }

        .gift-input {
            width: 100%;
            padding: 14px 15px;
            background-color: #26160d; 
            border: 1px solid var(--border-color);
            color: var(--text-main);
            border-radius: 8px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.2s;
        }

        .gift-input::placeholder {
            color: #6a5a52;
        }

        .gift-input:focus {
            border-color: var(--primary-orange);
        }

        .btn-confirm {
            width: 100%;
            background-color: var(--primary-orange);
            color: var(--text-main);
            border: none;
            padding: 14px;
            border-radius: 30px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            box-shadow: 0 4px 0 #b86a12; 
            transition: transform 0.1s, box-shadow 0.1s;
        }

        .btn-confirm:active {
            transform: translateY(4px);
            box-shadow: 0 0 0 #b86a12;
        }

        .btn-confirm:disabled {
            background-color: var(--border-color);
            color: var(--text-muted);
            box-shadow: none;
            cursor: not-allowed;
            transform: none;
        }

        /* ========================================================
           WHATSAPP JOIN CARD
           ======================================================== */
        .wa-join-card {
            display: flex;
            align-items: center;
            background-color: var(--bg-header);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 15px;
            margin-bottom: 20px;
            text-decoration: none;
            transition: background-color 0.2s;
        }

        .wa-join-card:active {
            background-color: var(--bg-dark);
        }

        .wa-icon-wrapper {
            width: 34px;
            height: 34px;
            background-color: #25D366; /* Official WhatsApp Green */
            color: #ffffff;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 20px;
            margin-right: 12px;
            flex-shrink: 0;
        }

        .wa-text {
            flex: 1;
            color: var(--text-main);
            font-size: 13px;
            font-weight: 500;
            line-height: 1.4;
        }

        .wa-arrow {
            color: var(--text-muted);
            font-size: 14px;
            margin-left: 10px;
        }

        /* ========================================================
           HISTORY SECTION
           ======================================================== */
        .history-header {
            display: flex;
            background-color: #2c1d16;
            border-radius: 8px;
            padding: 12px 15px;
            margin-bottom: 15px;
            border: 1px solid var(--border-color);
        }

        .col-left, .col-right {
            flex: 1;
            font-size: 14px;
            color: var(--text-main);
            font-weight: 500;
        }

        .col-left { text-align: left; }
        .col-right { text-align: right; }

        .history-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .history-item {
            display: flex;
            padding: 12px 15px;
            background-color: var(--bg-header);
            border: 1px solid var(--border-color);
            border-radius: 8px;
        }

        .history-item .date {
            flex: 1;
            text-align: left;
            font-size: 13px;
            color: var(--text-muted);
        }

        .history-item .amount {
            flex: 1;
            text-align: right;
            font-size: 14px;
            font-weight: 700;
            color: #32c149;
        }

        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px 0;
            opacity: 0.6;
        }

        .empty-icon {
            width: 80px;
            margin-bottom: 15px;
        }

        .empty-text {
            color: var(--text-muted);
            font-size: 14px;
        }

        /* ========================================================
           MODALS
           ======================================================== */
        .modal-overlay {
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: 100;
            display: none;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .modal {
            position: fixed;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%) scale(0.9);
            background-color: var(--bg-header);
            border: 1px solid var(--border-color);
            width: 85%; max-width: 350px;
            border-radius: 12px;
            z-index: 101;
            display: none;
            flex-direction: column;
            box-shadow: 0 10px 30px rgba(0,0,0,0.8);
            opacity: 0;
            transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }

        .modal.show, .modal-overlay.show { display: flex; opacity: 1; }
        .modal.show { transform: translate(-50%, -50%) scale(1); }

        .modal-header {
            display: flex; justify-content: space-between; align-items: center;
            padding: 16px 20px;
            border-bottom: 1px solid var(--border-color);
            font-size: 16px; font-weight: 700; color: var(--text-main);
        }

        .modal-body {
            padding: 20px;
            line-height: 1.6;
            color: #d0c8c4;
            font-size: 14px;
        }

        .close-btn { cursor: pointer; color: var(--text-muted); font-size: 18px; }

        /* ========================================================
           TOAST NOTIFICATION (iPhone dark style)
           ======================================================== */
        #toast-container {
            position: fixed;
            bottom: 50px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
            display: flex;
            flex-direction: column;
            gap: 10px;
            pointer-events: none;
            width: max-content;
            max-width: 90%;
        }

        .toast {
            background-color: rgba(28, 28, 30, 0.95);
            -webkit-backdrop-filter: blur(10px);
            backdrop-filter: blur(10px);
            color: var(--text-main);
            padding: 12px 24px;
            border-radius: 30px;
            font-size: 13px;
            font-weight: 400;
            text-align: center;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        }

        .toast.show { opacity: 1; transform: translateY(0); }

    </style>
</head>
<body>

    <!-- HIDDEN HEADER INCLUDE -->
    <div style="display: none; visibility: hidden; opacity: 0; width: 0; height: 0; overflow: hidden; position: absolute;">
        <?php include 'external/header.php'; ?>
    </div>

    <!-- Visual Feedback Container -->
    <div id="toast-container"></div>

    <!-- Rules Modal -->
    <div class="modal-overlay" id="modalOverlay" onclick="closeAllModals()"></div>
    <div class="modal" id="rulesModal">
        <div class="modal-header">
            <h3>Gift Code Rules</h3>
            <i class="fa-solid fa-times close-btn" onclick="closeAllModals()"></i>
        </div>
        <div class="modal-body">
            <ul style="padding-left: 15px; color: var(--text-muted); display: flex; flex-direction: column; gap: 10px;">
                <li>When you successfully claim a gift code, the bonus amount will be credited directly to your <strong>balance</strong>.</li>
                <li>You will simultaneously receive a <strong>1x wager requirement</strong> equal to the gift amount.</li>
                <li>Each gift code can only be claimed once per user account.</li>
                <li>Gift codes have limited quantities and will expire once the maximum claim limit is reached.</li>
            </ul>
        </div>
    </div>

    <!-- Header -->
    <div class="header">
        <a href="earn.php" class="btn-icon"><i class="fa-solid fa-angle-left"></i></a>
        <div class="header-title">Reward Redemption Code</div>
        <div class="btn-icon right" onclick="openModal('rulesModal')"><i class="fa-solid fa-clipboard-list"></i></div>
    </div>

    <div class="page-content">
        <!-- Banner -->
        <img src="https://pakclub.club/img/6004/other/055138596-30420-file_20260409055138483.webp" class="banner-img" alt="Bonus Banner">

        <!-- Redemption Card -->
        <div class="redemption-card">
            <div class="redemption-title">Hi! We have a gift for you</div>
            <div class="input-group">
                <input type="text" id="giftcode-input" class="gift-input" placeholder="Please enter the gift code" autocomplete="off">
            </div>
            <button class="btn-confirm" id="btn-submit" onclick="submitGiftCode()">Confirm</button>
        </div>

        <!-- WhatsApp Join Card -->
        <a href="https://whatsapp.com/channel/0029Vb7Phpp1NCrddQ1bQK0a" target="_blank" class="wa-join-card">
            <div class="wa-icon-wrapper">
                <i class="fa-brands fa-whatsapp"></i>
            </div>
            <div class="wa-text">Join WhatsApp channel for daily free giftcodes</div>
            <div class="wa-arrow">
                <i class="fa-solid fa-angle-right"></i>
            </div>
        </a>

        <!-- History Table Header -->
        <div class="history-header">
            <div class="col-left">Claim Time</div>
            <div class="col-right">Bonus</div>
        </div>

        <!-- History Data / Empty State -->
        <div class="history-list">
            <?php if (empty($claim_history)): ?>
                <div class="empty-state">
                    <img src="https://pakclub.club/images/empty-bg-CagnIzRR.webp" class="empty-icon" alt="Empty">
                    <div class="empty-text">No Records</div>
                </div>
            <?php else: ?>
                <?php foreach ($claim_history as $claim): ?>
                    <div class="history-item">
                        <div class="date"><?php echo date('Y-m-d H:i:s', strtotime($claim['claimed_at'])); ?></div>
                        <div class="amount">+Rs<?php echo number_format($claim['amount'], 2); ?></div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Modal Logic
        function openModal(modalId) {
            document.getElementById('modalOverlay').classList.add('show');
            document.getElementById(modalId).classList.add('show');
            document.body.style.overflow = 'hidden';
        }

        function closeAllModals() {
            document.getElementById('modalOverlay').classList.remove('show');
            const modals = document.querySelectorAll('.modal');
            modals.forEach(m => m.classList.remove('show'));
            document.body.style.overflow = 'auto';
        }

        // Toast Logic
        function showToast(message) {
            const container = document.getElementById('toast-container');
            const existingToasts = container.querySelectorAll('.toast');
            for (let t of existingToasts) {
                if (t.innerText.trim() === message.trim()) return; 
            }

            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.innerText = message;
            container.appendChild(toast);
            
            setTimeout(() => toast.classList.add('show'), 10);
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => toast.remove(), 300);
            }, 2500);
        }

        // Submit AJAX
        function submitGiftCode() {
            const input = document.getElementById('giftcode-input');
            const code = input.value.trim();
            const btn = document.getElementById('btn-submit');

            if (code === "") {
                showToast("Please enter the gift code");
                input.focus();
                return;
            }

            btn.disabled = true;
            btn.innerText = "Claiming...";

            const formData = new FormData();
            formData.append('action', 'claim_gift');
            formData.append('code', code);

            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if(data.success) {
                    showToast(data.message);
                    input.value = "";
                    btn.innerText = "Success!";
                    // Reload to reflect new balance and history
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(data.message);
                    btn.disabled = false;
                    btn.innerText = "Confirm";
                }
            })
            .catch(err => {
                showToast('Network error occurred');
                btn.disabled = false;
                btn.innerText = "Confirm";
            });
        }
    </script>

</body>
</html>