<?php
session_start();
require_once 'config.php';

// Check Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$userId = $_SESSION['user_id'];
global $pdo;

// 1. AUTO-CREATE TABLE FOR CLAIMS
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `first_gift_claims` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `user_id` int(11) NOT NULL,
        `deposit_amount` decimal(10,2) NOT NULL,
        `bonus_amount` decimal(10,2) NOT NULL,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        UNIQUE KEY `user_id` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(Exception $e) {}


// 2. CHECK ELIGIBILITY & STATUS
// A. Check if user has an 'approved' deposit
$stmt = $pdo->prepare("SELECT amount FROM deposit_requests WHERE user_id = ? AND status = 'approved' ORDER BY id ASC LIMIT 1");
$stmt->execute([$userId]);
$firstDeposit = $stmt->fetch(PDO::FETCH_ASSOC);

// B. Check if user has already claimed the gift
$stmt2 = $pdo->prepare("SELECT * FROM first_gift_claims WHERE user_id = ?");
$stmt2->execute([$userId]);
$hasClaimed = $stmt2->fetch(PDO::FETCH_ASSOC);

$btnStatus = 0; // 0 = No deposit (Ineligible), 1 = Claimable, 2 = Already Claimed
$bonusAmount = 0;

if ($hasClaimed) {
    $btnStatus = 2; // Application successful
} elseif ($firstDeposit) {
    $btnStatus = 1; // Claimable
    // 30% of first deposit, capped at 150 limit
    $bonusAmount = min($firstDeposit['amount'] * 0.30, 150.00); 
}

// 3. HANDLE AJAX CLAIM REQUEST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'claim') {
    header('Content-Type: application/json');
    
    if ($btnStatus === 1) {
        try {
            $pdo->beginTransaction();
            
            // Insert claim record
            $ins = $pdo->prepare("INSERT INTO first_gift_claims (user_id, deposit_amount, bonus_amount) VALUES (?, ?, ?)");
            $ins->execute([$userId, $firstDeposit['amount'], $bonusAmount]);
            
            // Update User Wallet
            $upd = $pdo->prepare("UPDATE wallets SET main_balance = main_balance + ? WHERE user_id = ?");
            $upd->execute([$bonusAmount, $userId]);
            
            $pdo->commit();
            echo json_encode(['success' => true, 'msg' => "Congratulations! ₹{$bonusAmount} Bonus Added."]);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'msg' => 'Server error while claiming.']);
        }
    } else {
        echo json_encode(['success' => false, 'msg' => 'You are not eligible or already claimed.']);
    }
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>First Gift - 91CLUB</title>
    <style>
        @font-face { font-family: 'Bahnschrift'; src: url('https://91appt.com/assets/woff2/bahnschrift-610d57ac.woff2') format('woff2'); font-display: swap; }
        :root { --bg-body: #F7F8FA; --primary: #F3595B; }
        * { font-family: -apple-system, sans-serif; box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent;}
        .bahnschrift { font-family: 'Bahnschrift', sans-serif !important; }
        
        body { background-color: var(--bg-body); color: #333; max-width: 480px; margin: 0 auto; padding-top: 50px; min-height: 100vh;}

        /* Header */
        .header { position: fixed; top: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px; height: 50px; background: #fff; display: flex; justify-content: center; align-items: center; z-index: 1000; box-shadow: 0 1px 5px rgba(0,0,0,0.05);}
        .back-btn { position: absolute; left: 15px; font-size: 20px; color: #666; cursor: pointer; text-decoration: none;}
        .title { font-size: 16px; font-weight: bold; }

        /* Banner Section */
        .gift-banner { background: linear-gradient(135deg, #FFA940, #FF7B23); padding: 25px 20px; color: white; position: relative; overflow: hidden;}
        .banner-title { font-size: 22px; font-weight: 900; margin-bottom: 10px; position: relative; z-index: 2;}
        .banner-desc { font-size: 11px; margin-bottom: 10px; font-weight: 500; position: relative; z-index: 2;}
        .banner-list { list-style: none; font-size: 10px; margin-bottom: 15px; position: relative; z-index: 2;}
        .banner-list li { margin-bottom: 5px; display: flex; align-items: flex-start; gap: 5px;}
        .banner-list li::before { content: '✓'; display: block; background: rgba(255,255,255,0.2); width: 12px; height: 12px; border-radius: 50%; text-align: center; line-height: 12px; font-size: 8px; flex-shrink: 0; margin-top: 1px;}
        .btn-act-details { background: rgba(255,255,255,0.2); border: 1px solid white; border-radius: 20px; padding: 4px 12px; font-size: 10px; display: inline-block; position: relative; z-index: 2;}
        .gift-img { position: absolute; right: -10px; bottom: -10px; width: 150px; opacity: 0.9; z-index: 1;}

        /* Container */
        .content-wrap { padding: 20px 15px; }

        /* Event Time Box */
        .time-box { background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05); margin-bottom: 20px; border: 1px solid #f0f0f0;}
        .time-top { background: var(--primary); color: white; text-align: center; padding: 12px; font-size: 14px; font-weight: bold;}
        .time-bot { color: var(--primary); text-align: center; padding: 15px; font-size: 18px; font-weight: bold; font-family: 'Bahnschrift', sans-serif;}

        /* Conditions Table */
        .cond-table { background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05); border: 1px solid #f0f0f0; margin-bottom: 30px;}
        .t-row { display: grid; grid-template-columns: 1fr 1.2fr 0.8fr; }
        .t-head { background: var(--primary); color: white; font-size: 11px; font-weight: bold; text-align: center; padding: 10px 5px; border-right: 1px solid rgba(255,255,255,0.2);}
        .t-head:last-child { border-right: none;}
        .t-data { padding: 15px 10px; font-size: 11px; text-align: center; color: #555; font-weight: 500; border-right: 1px solid #eee; display: flex; align-items: center; justify-content: center;}
        .t-data:last-child { border-right: none; color: var(--primary); font-weight: bold; font-size: 13px;}

        /* Action Button */
        .btn-claim { width: 100%; border: none; padding: 15px; border-radius: 30px; font-size: 16px; font-weight: bold; transition: 0.3s; box-shadow: 0 4px 10px rgba(0,0,0,0.1); cursor: pointer;}
        
        .btn-disabled { background: #E0E0E0; color: #999; box-shadow: none; cursor: not-allowed;}
        .btn-active { background: linear-gradient(90deg, #FF7B7B, #F3595B); color: white; box-shadow: 0 4px 15px rgba(243, 89, 91, 0.4);}
        .btn-active:active { transform: scale(0.97); }

        /* Toast */
        .toast { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(0,0,0,0.8); color: white; padding: 12px 24px; border-radius: 8px; font-size: 14px; z-index: 2000; display: none; text-align: center; font-weight: bold;}
    </style>
</head>
<body>

    <div class="header">
        <a href="activity.php" class="back-btn">❮</a>
        <div class="title">Activity details</div>
    </div>

    <div class="gift-banner">
        <div class="banner-title">First gift</div>
        <div class="banner-desc">There are two types of new member gift package rewards::</div>
        <ul class="banner-list">
            <li>Bonus for first deposit negative profit</li>
            <li>Play games and get bonuses only for new members</li>
        </ul>
        <div class="btn-act-details">Activity details</div>
        
        <img src="https://91appt.com/assets/png/giftRedeem-bb2f7a92.webp" alt="Gift" class="gift-img">
    </div>

    <div class="content-wrap">
        
        <div class="time-box">
            <div class="time-top">Event start time</div>
            <div class="time-bot">2025-01-01 00:00:00</div>
        </div>

        <div class="cond-table">
            <div class="t-row">
                <div class="t-head">Conditions of participation</div>
                <div class="t-head">Get Compensation Bonus</div>
                <div class="t-head">Bonus limit</div>
            </div>
            <div class="t-row">
                <div class="t-data">First deposit for new users</div>
                <div class="t-data">Total <span style="color:var(--primary); margin:0 3px;">30%</span> compensation from First Deposit Amount</div>
                <div class="t-data bahnschrift">₹150.00</div>
            </div>
        </div>

        <?php if ($btnStatus === 2): ?>
            <button class="btn-claim btn-disabled" disabled>Application successful</button>
            <div style="text-align:center; font-size:11px; color:#999; margin-top:10px;">You have already claimed this reward.</div>
        
        <?php elseif ($btnStatus === 1): ?>
            <button class="btn-claim btn-active" onclick="claimBonus()">Claim ₹<?= $bonusAmount ?> Bonus</button>
            <div style="text-align:center; font-size:11px; color:#f3595b; margin-top:10px; font-weight:bold;">Your 1st Deposit is Approved! You are eligible.</div>
            
        <?php else: ?>
            <button class="btn-claim btn-disabled" disabled>Not Eligible Yet</button>
            <div style="text-align:center; font-size:11px; color:#999; margin-top:10px;">You need to complete your first recharge to claim this gift.</div>
        <?php endif; ?>

    </div>

    <div id="toast" class="toast"></div>

    <script>
        function showToast(msg, reload = false) {
            const toast = document.getElementById('toast');
            toast.innerText = msg;
            toast.style.display = 'block';
            setTimeout(() => {
                toast.style.display = 'none';
                if(reload) window.location.reload();
            }, 2000);
        }

        function claimBonus() {
            let formData = new FormData();
            formData.append('action', 'claim');

            fetch('firstgift.php', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if(data.success) {
                    showToast(data.msg, true);
                } else {
                    showToast(data.msg);
                }
            })
            .catch(err => {
                showToast("Network Error!");
            });
        }
    </script>
</body>
</html>