<?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 TABLES & INSERT DEFAULT DATA
// ==================================================
try {
    // Tiers Table
    $pdo->exec("CREATE TABLE IF NOT EXISTS `invitation_tiers` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `level` int(11) NOT NULL,
        `invitees_needed` int(11) NOT NULL,
        `recharge_needed` decimal(10,2) NOT NULL,
        `bonus_amount` decimal(10,2) NOT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // Check if tiers exist, if not insert default data from screenshot
    $checkTiers = $pdo->query("SELECT COUNT(*) FROM invitation_tiers")->fetchColumn();
    if ($checkTiers == 0) {
        $pdo->exec("INSERT INTO `invitation_tiers` (`level`, `invitees_needed`, `recharge_needed`, `bonus_amount`) VALUES
            (1, 1, 300.00, 55.00),
            (2, 3, 300.00, 155.00),
            (3, 10, 500.00, 555.00),
            (4, 30, 800.00, 1555.00),
            (5, 50, 1200.00, 2775.00),
            (6, 75, 1200.00, 4165.00),
            (7, 100, 1200.00, 5555.00)
        ");
    }

    // Records Table (Who invited whom)
    $pdo->exec("CREATE TABLE IF NOT EXISTS `invitation_records` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `referrer_id` int(11) NOT NULL,
        `referred_uid` varchar(20) NOT NULL,
        `referred_username` varchar(50) NOT NULL,
        `registered_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `total_deposit` decimal(10,2) DEFAULT '0.00',
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // Claims Table (Track which bonuses are claimed)
    $pdo->exec("CREATE TABLE IF NOT EXISTS `invitation_claims` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `user_id` int(11) NOT NULL,
        `tier_id` int(11) NOT NULL,
        `claimed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

} catch (Exception $e) {}


// ==================================================
// 2. FETCH USER DATA & PROGRESS
// ==================================================
$tiersStmt = $pdo->query("SELECT * FROM invitation_tiers ORDER BY level ASC");
$tiers = $tiersStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch total valid invitees for this user (Dummy query structure, modify as per your actual referral logic)
$inviteesStmt = $pdo->prepare("SELECT * FROM invitation_records WHERE referrer_id = ? ORDER BY registered_at DESC");
$inviteesStmt->execute([$userId]);
$inviteRecords = $inviteesStmt->fetchAll(PDO::FETCH_ASSOC);

// Get claimed tiers
$claimsStmt = $pdo->prepare("SELECT tier_id FROM invitation_claims WHERE user_id = ?");
$claimsStmt->execute([$userId]);
$claimedTiers = $claimsStmt->fetchAll(PDO::FETCH_COLUMN);

// Calculate how many invites meet the recharge criteria for each tier dynamically
// (In a real scenario, you loop through $inviteRecords and check if `total_deposit` >= `recharge_needed`)


// ==================================================
// 3. HANDLE CLAIM REQUEST
// ==================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'claim') {
    header('Content-Type: application/json');
    $tierId = (int)$_POST['tier_id'];
    
    // Safety check and process claim...
    // (Add logic to verify if user actually has enough invites before granting)
    echo json_encode(['success' => false, 'msg' => 'Validation pending. Ensure you have enough valid invites.']);
    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>Invitation Bonus - 91CLUB</title>
    <style>
        /* ORIGINAL FONT */
        @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;         
            --primary-grad: linear-gradient(135deg, #FF9800 0%, #FF5722 100%);
            --text-dark: #333333;
            --text-muted: #888888;
        }

        * { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, 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: var(--text-dark); max-width: 480px; margin: 0 auto; min-height: 100vh; overflow-x: hidden; padding-bottom: 20px;}

        /* 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;}
        .back-btn { position: absolute; left: 15px; font-size: 20px; color: #666; cursor: pointer; text-decoration: none; padding: 10px;}
        .title { font-size: 16px; font-weight: bold; color: #333; }

        /* VIEW SWITCHER */
        .page-view { padding-top: 50px; display: none; }
        .page-view.active { display: block; animation: fadeIn 0.3s ease; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

        /* =========================================
           1. MAIN PAGE (BONUS TIERS)
           ========================================= */
        .inv-banner { background: var(--primary-grad); color: white; padding: 25px 20px 60px; position: relative; overflow: hidden; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px;}
        .inv-banner h1 { font-size: 20px; font-weight: 900; margin-bottom: 8px; position: relative; z-index: 2;}
        .inv-banner p { font-size: 11px; line-height: 1.4; font-weight: 500; position: relative; z-index: 2; width: 70%; opacity: 0.9;}
        .inv-banner .date { font-size: 11px; margin-top: 10px; font-weight: bold;}
        .banner-img { position: absolute; right: -20px; top: 10px; width: 140px; z-index: 1;}

        .top-actions { display: flex; gap: 15px; padding: 0 15px; margin-top: -30px; position: relative; z-index: 10;}
        .action-card { flex: 1; background: #fff; border-radius: 12px; padding: 15px 10px; display: flex; flex-direction: column; align-items: center; gap: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); cursor: pointer;}
        .action-card img { width: 35px; height: 35px; }
        .action-card span { font-size: 11px; font-weight: bold; color: #666; text-align: center;}

        .tier-list { padding: 20px 15px; display: flex; flex-direction: column; gap: 15px;}
        .tier-card { background: #fff; border-radius: 12px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.03);}
        
        .tier-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed #eee; padding-bottom: 12px; margin-bottom: 12px;}
        .tier-title-wrap { display: flex; align-items: center; gap: 8px; }
        .tier-badge { background: #E0F2E9; color: #4CAF50; font-size: 12px; font-weight: bold; padding: 3px 10px; border-radius: 15px; display: flex; align-items: center; gap: 5px;}
        .tier-badge.unfinished { background: #f0f0f0; color: #999; }
        .tier-icon { width: 16px; height: 16px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; color: white; background: #4CAF50;}
        .tier-icon.unfinished { background: #ccc; }
        .tier-bonus-amt { color: #FF9800; font-size: 14px; font-weight: bold; }

        .tier-row { display: flex; justify-content: space-between; font-size: 12px; color: #666; margin-bottom: 8px;}
        .tier-row .val { font-weight: bold; color: #333;}
        
        .progress-row { display: flex; justify-content: space-around; text-align: center; margin: 15px 0;}
        .prog-item { display: flex; flex-direction: column; gap: 4px; }
        .prog-val { font-size: 14px; font-weight: bold; color: var(--primary);}
        .prog-lbl { font-size: 10px; color: #999;}

        .btn-receive { width: 100%; border: none; padding: 12px; border-radius: 25px; font-size: 14px; font-weight: bold; transition: 0.3s; cursor: pointer;}
        .btn-disabled { background: #E0E0E0; color: #aaa; box-shadow: none; cursor: not-allowed;}
        .btn-active { background: linear-gradient(90deg, #FF9800, #FF5722); color: white; box-shadow: 0 4px 10px rgba(255, 152, 0, 0.3);}

        /* =========================================
           2. RULE PAGE (TABLE)
           ========================================= */
        .rule-wrap { padding: 15px; }
        .rule-header-txt { font-size: 12px; color: #666; line-height: 1.5; margin-bottom: 15px; font-weight: 500;}
        .rule-header-txt span { color: var(--primary); font-weight: bold;}
        
        .rule-table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.03);}
        .rule-table th { background: var(--primary); color: white; padding: 12px; font-size: 12px; font-weight: bold; text-align: center;}
        .rule-table td { padding: 12px; font-size: 12px; text-align: center; border-bottom: 1px solid #f0f0f0; color: #555; font-weight: 500;}
        .rule-table tr:nth-child(even) { background: #fafafa; }
        .rule-table tr:last-child td { border-bottom: none;}

        /* =========================================
           3. RECORD PAGE
           ========================================= */
        .record-wrap { padding: 15px; }
        .record-card { background: #fff; border-radius: 10px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); margin-bottom: 10px;}
        .r-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px dashed #eee; padding-bottom: 10px;}
        .r-name { font-size: 13px; font-weight: bold; color: #333;}
        .r-uid { font-size: 12px; color: #5CA6FF; font-weight: bold;}
        .r-row { display: flex; justify-content: space-between; font-size: 11px; color: #888; margin-bottom: 5px;}
        .r-amt { color: #FF9800; font-weight: bold; font-size: 13px;}
        .no-more { text-align: center; font-size: 12px; color: #ccc; margin-top: 20px;}

    </style>
</head>
<body>

    <div class="header">
        <a href="javascript:void(0);" class="back-btn" onclick="goBack()">❮</a>
        <div class="title" id="headerTitle">Invitation bonus</div>
    </div>

    <div id="page-main" class="page-view active">
        <div class="inv-banner">
            <h1>Invite friends and deposit</h1>
            <p>Both parties can receive rewards<br>Invite friends to register and recharge to receive rewards</p>
            <div class="date">activity date<br>2000-01-01 - 2099-01-01</div>
            <img src="https://91appt.com/assets/png/invitationBonus-aa7acbd3.png" alt="Gifts" class="banner-img">
        </div>

        <div class="top-actions">
            <div class="action-card" onclick="switchPage('rule')">
                <img src="https://cdn-icons-png.flaticon.com/512/2921/2921222.png" alt="Rules">
                <span>Invitation reward rules</span>
            </div>
            <div class="action-card" onclick="switchPage('record')">
                <img src="https://cdn-icons-png.flaticon.com/512/10627/10627116.png" alt="Records">
                <span>Invitation record</span>
            </div>
        </div>

        <div class="tier-list">
            <?php foreach($tiers as $index => $t): 
                // Mock logic for display (In real app, calculate actual progress)
                $isClaimed = in_array($t['id'], $claimedTiers);
                $myInvites = count($inviteRecords); // Example
                
                // Styling based on status
                $statusClass = $isClaimed ? '' : 'unfinished';
                $iconHtml = $isClaimed ? '✓' : '✕';
                $btnClass = $isClaimed ? 'btn-disabled' : 'btn-disabled'; // Default disabled
                $btnText = $isClaimed ? 'Received' : 'Unfinished';
                
                // If eligible but not claimed (Mock logic)
                if (!$isClaimed && $myInvites >= $t['invitees_needed']) {
                    $btnClass = 'btn-active';
                    $btnText = 'Receive';
                }
            ?>
            <div class="tier-card">
                <div class="tier-header">
                    <div class="tier-title-wrap">
                        <div class="tier-badge <?= $statusClass ?>">
                            Bonus <?= $t['level'] ?> 
                            <div class="tier-icon <?= $statusClass ?>"><?= $iconHtml ?></div>
                        </div>
                    </div>
                    <div class="tier-bonus-amt bahnschrift">₹<?= number_format($t['bonus_amount'], 2) ?></div>
                </div>

                <div class="tier-row">
                    <span>Number of invitees</span>
                    <span class="val bahnschrift"><?= $t['invitees_needed'] ?></span>
                </div>
                <div class="tier-row">
                    <span>Recharge per people</span>
                    <span class="val bahnschrift" style="color: #f3595b;">₹<?= number_format($t['recharge_needed'], 2) ?></span>
                </div>

                <div class="progress-row">
                    <div class="prog-item">
                        <span class="prog-val bahnschrift"><?= min($myInvites, $t['invitees_needed']) ?> / <?= $t['invitees_needed'] ?></span>
                        <span class="prog-lbl">Number of invitees</span>
                    </div>
                    <div class="prog-item">
                        <span class="prog-val bahnschrift">0 / <?= $t['invitees_needed'] ?></span>
                        <span class="prog-lbl">Deposit number</span>
                    </div>
                </div>

                <button class="btn-receive <?= $btnClass ?>" disabled><?= $btnText ?></button>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div id="page-rule" class="page-view">
        <div class="rule-wrap">
            <div class="rule-header-txt">
                Invite friends and recharge to get additional platform rewards!<br>
                After being claimed, the rewards will be directly distributed to the wallet balance within <span>10 minutes</span>.
            </div>

            <table class="rule-table">
                <thead>
                    <tr>
                        <th>Invite account</th>
                        <th>Deposit amount</th>
                        <th>Bonus</th>
                    </tr>
                </thead>
                <tbody class="bahnschrift">
                    <?php foreach($tiers as $t): ?>
                    <tr>
                        <td><?= $t['invitees_needed'] ?>People</td>
                        <td>₹<?= number_format($t['recharge_needed'], 2) ?></td>
                        <td>₹<?= number_format($t['bonus_amount'], 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div id="page-record" class="page-view">
        <div class="record-wrap">
            
            <?php if(empty($inviteRecords)): ?>
                <div class="record-card">
                    <div class="r-top">
                        <span class="r-name">MemberNNGYPHAY</span>
                        <span class="r-uid bahnschrift">UID:14248673</span>
                    </div>
                    <div class="r-row">
                        <span>Registration time</span>
                        <span class="bahnschrift">2024-11-01 11:23:13</span>
                    </div>
                    <div class="r-row">
                        <span>Deposit amount</span>
                        <span class="r-amt bahnschrift">₹25,380.99</span>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach($inviteRecords as $rec): ?>
                <div class="record-card">
                    <div class="r-top">
                        <span class="r-name"><?= htmlspecialchars($rec['referred_username']) ?></span>
                        <span class="r-uid bahnschrift">UID:<?= $rec['referred_uid'] ?></span>
                    </div>
                    <div class="r-row">
                        <span>Registration time</span>
                        <span class="bahnschrift"><?= $rec['registered_at'] ?></span>
                    </div>
                    <div class="r-row">
                        <span>Deposit amount</span>
                        <span class="r-amt bahnschrift">₹<?= number_format($rec['total_deposit'], 2) ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>

            <div class="no-more">No more</div>
        </div>
    </div>

    <script>
        let currentView = 'main';

        function switchPage(page) {
            document.getElementById('page-main').classList.remove('active');
            document.getElementById('page-rule').classList.remove('active');
            document.getElementById('page-record').classList.remove('active');

            document.getElementById('page-' + page).classList.add('active');
            currentView = page;

            const titleEl = document.getElementById('headerTitle');
            if(page === 'main') {
                titleEl.innerText = 'Invitation bonus';
            } else if (page === 'rule') {
                titleEl.innerText = 'Invitation reward rules';
            } else if (page === 'record') {
                titleEl.innerText = 'Invitation record';
            }
            window.scrollTo(0,0);
        }

        function goBack() {
            if (currentView === 'main') {
                window.location.href = 'activity.php'; 
            } else {
                switchPage('main');
            }
        }
    </script>
</body>
</html>