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

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

// =========================================================
// 1. TIMEZONE FIX: Force Pakistan Time so "Today" is accurate
// =========================================================
date_default_timezone_set('Asia/Karachi'); 
$pdo->exec("SET time_zone = '+05:00';");

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

// =========================================================
// AUTO-HEAL DATABASE SCHEMA (Runs silently to fix daily resets)
// =========================================================
try {
    $pdo->exec("ALTER TABLE users ADD COLUMN last_claim_date DATE DEFAULT NULL");
} catch (Exception $e) {
    // Column already exists, safe to ignore
}

// ---------------------------------------------------------
// AJAX CLAIM HANDLER
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'claim') {
    header('Content-Type: application/json');
    if (!isset($pdo) || !$user_number) {
        echo json_encode(['success' => false, 'message' => 'Not logged in or DB error']);
        exit;
    }
    
    $stmt = $pdo->prepare("SELECT unclaimed_earnings FROM users WHERE number = ?");
    $stmt->execute([$user_number]);
    $user = $stmt->fetch();
    
    if ($user && $user['unclaimed_earnings'] > 0) {
        $amount = $user['unclaimed_earnings'];
        try {
            $pdo->beginTransaction();
            
            // FIX: Removed total_commission math so it stops double-counting.
            // It now only updates balance, today_claimed, and resets unclaimed.
            $update = $pdo->prepare("UPDATE users SET balance = balance + ?, today_claimed = today_claimed + ?, unclaimed_earnings = 0, last_claim_date = CURDATE() WHERE number = ?");
            $update->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' => 'Claim failed, please try again.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'No earnings to claim']);
    }
    exit;
}
// ---------------------------------------------------------

// Initialize default variables
$my_refercode = "Error: Not Logged In";
$yesterday_comm = 0.00;
$today_claimed = 0.00;
$total_comm = 0.00;
$unclaimed_earnings = 0.00;

$dir_reg = 0; $dir_dep_users = 0; $dir_dep_amt = 0.00; $dir_first_dep = 0;
$team_reg = 0; $team_dep_users = 0; $team_dep_amt = 0.00; $team_first_dep = 0;
$today_refers = 0;

// Check if the PDO connection exists
if (!isset($pdo)) {
    $my_refercode = "Error: Database connection failed";
} elseif ($user_number) {
    // 1. Get Current User Info
    $stmt = $pdo->prepare("SELECT id, refercode, yesterday_commission, today_claimed, total_commission, unclaimed_earnings, last_claim_date FROM users WHERE number = ?");
    
    if ($stmt) {
        $stmt->execute([$user_number]);
        if ($user = $stmt->fetch()) {
            $my_refercode = !empty($user['refercode']) ? $user['refercode'] : "Error: Code not generated";
            
            $uid = $user['id'];
            $total_comm = $user['total_commission'];
            $unclaimed_earnings = $user['unclaimed_earnings'];
            
            // Calculate Today's Earned dynamically
            $stmt_today_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) FROM referral_commissions WHERE user_id = ? AND DATE(created_at) = CURDATE()");
            if ($stmt_today_earn) {
                $stmt_today_earn->execute([$uid]);
                $today_earned = (float)$stmt_today_earn->fetchColumn();
            } else {
                $today_earned = 0.00;
            }
            
            // Calculate Yesterday's Earned dynamically
            $stmt_yest_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) FROM referral_commissions WHERE user_id = ? AND DATE(created_at) = CURDATE() - INTERVAL 1 DAY");
            if ($stmt_yest_earn) {
                $stmt_yest_earn->execute([$uid]);
                $yesterday_comm = (float)$stmt_yest_earn->fetchColumn();
            } else {
                $yesterday_comm = 0.00;
            }

        } else {
            $my_refercode = "Error: User not found in database";
        }
    }

    if (strpos($my_refercode, 'Error') === false) {
        // Direct Invitees Stats (Level 1)
        $stmt_dir = $pdo->prepare("
            SELECT 
                COUNT(id) as registered_count,
                SUM(CASE WHEN total_deposits > 0 THEN 1 ELSE 0 END) as deposit_users,
                SUM(total_deposits) as deposit_amount
            FROM users WHERE referedby = ?
        ");
        if ($stmt_dir) {
            $stmt_dir->execute([$my_refercode]);
            if ($row = $stmt_dir->fetch()) {
                $dir_reg = $row['registered_count'] ?? 0;
                $dir_dep_users = $row['deposit_users'] ?? 0;
                $dir_dep_amt = $row['deposit_amount'] ?? 0.00;
                $dir_first_dep = $dir_dep_users; 
            }
        }

        // Team Invitees Stats (Level 2 + Level 3)
        $stmt_team = $pdo->prepare("
            SELECT 
                COUNT(id) as registered_count,
                SUM(CASE WHEN total_deposits > 0 THEN 1 ELSE 0 END) as deposit_users,
                SUM(total_deposits) as deposit_amount
            FROM users 
            WHERE referedby IN (SELECT refercode FROM users WHERE referedby = ?) 
               OR referedby IN (SELECT refercode FROM users WHERE referedby IN (SELECT refercode FROM users WHERE referedby = ?))
        ");
        if ($stmt_team) {
            $stmt_team->execute([$my_refercode, $my_refercode]);
            if ($row = $stmt_team->fetch()) {
                $team_reg = $row['registered_count'] ?? 0;
                $team_dep_users = $row['deposit_users'] ?? 0;
                $team_dep_amt = $row['deposit_amount'] ?? 0.00;
                $team_first_dep = $team_dep_users;
            }
        }

        // Today's New Invitees (Fixed by Timezone)
        $stmt_today = $pdo->prepare("SELECT COUNT(id) as today_count FROM users WHERE referedby = ? AND DATE(created_at) = CURDATE()");
        if ($stmt_today) {
            $stmt_today->execute([$my_refercode]);
            if ($row = $stmt_today->fetch()) {
                $today_refers = $row['today_count'] ?? 0;
            }
        }
    }
}
?>
<!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>Earn</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        /* earn.php specific overrides */
        :root {
            --tab-active: #e37a4e;      /* Light soft orange */
            --tab-inactive: #d16b40;    /* Slightly darker soft orange */
        }

        /* ========================================================
           HEADER
           ======================================================== */
        .earn-header {
            text-align: center;
            padding: 15px;
            font-size: 18px;
            font-weight: 700;
            background-color: var(--bg-card);
            position: sticky;
            top: 0;
            z-index: 10;
        }

        /* ========================================================
           COMMISSION CARD (HERO)
           ======================================================== */
        .commission-wrapper {
            padding: 0 15px;
            margin-top: 15px; 
            margin-bottom: 20px;
        }

        .commission-card {
            position: relative;
            background-color: var(--bg-card);
            border-radius: 8px;
            padding: 25px 20px 20px 20px;
            text-align: center;
            overflow: hidden;
            box-shadow: none;
            border: 1px solid var(--border-color);
        }

        .commission-card::before {
            content: "♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦ ♠ ♥ ♣ ♦";
            position: absolute;
            top: -20px; left: -20px; right: -20px; bottom: -20px;
            color: rgba(255, 255, 255, 0.03);
            font-size: 32px;
            line-height: 50px;
            letter-spacing: 25px;
            text-align: justify;
            z-index: 1;
            pointer-events: none;
            word-wrap: break-word;
        }

        .commission-card > * {
            position: relative;
            z-index: 2;
        }

        .commission-card .title {
            color: var(--text-main);
            font-size: 14px;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .commission-card .amount {
            color: var(--primary-orange);
            font-size: 34px;
            font-weight: 800;
            margin-bottom: 20px;
        }

        .dashed-divider {
            height: 1px;
            border-top: 1px dashed rgba(255, 255, 255, 0.1);
            margin: 0 -5px; 
        }

        .unclaimed-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 15px;
            text-align: left;
        }

        .unclaimed-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .unclaimed-lbl { 
            font-size: 12px; 
            color: var(--text-muted); 
        }

        .unclaimed-val { 
            font-size: 16px; 
            font-weight: 700; 
            color: var(--success-green); 
        }

        .btn-claim {
            background-color: var(--success-green);
            color: #ffffff;
            border: none;
            padding: 8px 24px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.1s;
        }

        .btn-claim:active { transform: scale(0.95); }
        .btn-claim:disabled {
            background-color: #33241d; 
            color: #92837b;
            cursor: not-allowed;
            transform: none;
        }

        /* ========================================================
           SLIDER CONTAINERS & TABS
           ======================================================== */
        .slider-container {
            padding: 0 15px;
            margin-bottom: 15px;
            width: 100%;
            overflow: hidden;
        }

        .slider-wrapper {
            display: flex;
            overflow-x: auto;
            scroll-snap-type: x mandatory;
            scrollbar-width: none; 
            -ms-overflow-style: none; 
            background-color: var(--bg-card);
            border-radius: 8px;
            width: 100%;
            cursor: grab; 
            border: 1px solid var(--border-color);
        }

        .slider-wrapper:active { cursor: grabbing; }
        .slider-wrapper::-webkit-scrollbar { display: none; }

        .slide {
            flex: 0 0 100%;
            width: 100%;
            scroll-snap-align: start;
            padding: 0; 
            box-sizing: border-box;
        }

        /* Slide 1 - Tabs Format */
        .stats-tabs {
            display: flex;
            width: 100%;
        }

        .tab {
            flex: 1;
            text-align: center;
            padding: 14px 0;
            font-size: 14px;
            font-weight: 600;
            color: var(--text-main);
        }

        .tab.active { background-color: var(--tab-active); }
        .tab.inactive { background-color: var(--tab-inactive); }

        .tab:first-child {
            border-right: 2px solid #000000; 
        }

        .stats-content { 
            padding: 20px 15px; 
            pointer-events: none; 
        }
        
        .stats-data-panel {
            display: flex;
            flex-direction: row;
        }

        .stats-col {
            flex: 1;
            text-align: center;
            display: flex;
            flex-direction: column;
            gap: 16px; 
        }

        .stat-item {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .stat-val { font-size: 15px; font-weight: 700; color: var(--text-main); }
        .stat-val.green { color: var(--success-green); }
        .stat-val.orange { color: var(--primary-orange); }
        .stat-label { font-size: 12px; color: var(--text-muted); font-weight: 400; }

        /* Slide 2 - Overview Format */
        .slide-overview { padding: 20px 15px; pointer-events: none; }
        
        .pills-row {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
        }

        .pill {
            flex: 1;
            background-color: var(--bg-dark);
            border: 1px solid var(--border-color);
            border-radius: 15px;
            padding: 10px 0;
            text-align: center;
        }

        .pill .val { color: var(--primary-orange); font-weight: 700; font-size: 14px; margin-bottom: 4px;}
        .pill .lbl { color: var(--text-muted); font-size: 11px; text-transform: capitalize; }

        .counts-row {
            display: flex;
            text-align: center;
        }

        .counts-col { flex: 1; }
        .counts-col .val { color: var(--text-main); font-size: 16px; font-weight: 700; margin-bottom: 4px; }
        .counts-col .lbl { color: var(--text-muted); font-size: 13px; }

        .slide-divider {
            height: 1px;
            background-color: rgba(255,255,255,0.05);
            margin: 0 -15px 25px -15px;
        }

        /* ========================================================
           CAROUSEL DOTS
           ======================================================== */
        .carousel-dots {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 6px;
            margin-bottom: 20px;
        }

        .dot {
            height: 4px;
            border-radius: 2px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .dot.active { width: 14px; background-color: var(--primary-orange); }
        .dot.inactive { width: 6px; background-color: var(--border-color); }

        /* ========================================================
           INVITE BUTTON
           ======================================================== */
        .btn-wrapper {
            padding: 0 15px;
            margin-bottom: 20px;
        }

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

        .btn-invite:active { transform: translateY(4px); box-shadow: none; }

        /* ========================================================
           MENU LIST 
           ======================================================== */
        .menu-wrapper {
            padding: 0 15px;
            margin-bottom: 20px;
        }

        .menu-list {
            background-color: var(--bg-card);
            border-radius: 8px;
            border: 1px solid var(--border-color);
            overflow: hidden;
        }

        .menu-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 15px;
            border-bottom: 1px solid rgba(255,255,255,0.03);
            text-decoration: none;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .menu-item:last-child { border-bottom: none; }
        .menu-item:active { background-color: var(--bg-dark); }

        .menu-left { display: flex; align-items: center; gap: 14px; }

        .menu-icon {
            width: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: var(--primary-orange); 
        }

        .menu-text {
            color: var(--text-main);
            font-size: 14px;
            font-weight: 500;
        }

        .menu-right {
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--text-muted);
            font-size: 14px;
        }

        .invite-code-text {
            color: var(--text-main);
            font-weight: 500;
            font-size: 13px;
        }
        
        .invite-error {
            color: #ff6b6b !important;
            font-size: 11px !important;
        }

        .copy-icon { font-size: 16px; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease; }
        .arrow-icon { font-size: 14px; color: var(--border-color); }

        /* ========================================================
           MODALS (Popups)
           ======================================================== */
        .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-card);
            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 5px 25px rgba(0,0,0,0.6);
            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
           ======================================================== */
        #toast-container {
            position: fixed;
            bottom: 90px;
            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>

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

    <div id="toast-container"></div>

    <div class="modal-overlay" id="modalOverlay" onclick="closeAllModals()"></div>

    <div class="modal" id="rulesModal">
        <div class="modal-header">
            <h3>Invitation Rules</h3>
            <i class="fa-solid fa-times close-btn" onclick="closeAllModals()"></i>
        </div>
        <div class="modal-body">
            <p style="margin-bottom: 8px;"><strong>Level 1 (Direct Invite):</strong><br>
    First deposit: <strong style="color: var(--primary-orange);">15%</strong> | Other deposits: <strong style="color: var(--primary-orange);">6%</strong>
</p>
<p style="margin-bottom: 8px;"><strong>Level 2:</strong><br>
    First deposit: <strong style="color: var(--primary-orange);">6%</strong> | Other deposits: <strong style="color: var(--primary-orange);">3%</strong>
</p>
<p style="margin-bottom: 12px;"><strong>Level 3:</strong><br>
    First deposit: <strong style="color: var(--primary-orange);">2%</strong> | Other deposits: <strong style="color: var(--primary-orange);">2%</strong>
</p>
            <p style="font-size: 12px; color: var(--text-muted); border-top: 1px dashed rgba(255,255,255,0.1); padding-top: 10px;">
                <em>What are levels?</em> If you invite someone directly, they are Level 1. If your Level 1 friend invites someone, that person is your Level 2. If the Level 2 person invites someone, they are Level 3.
            </p>
        </div>
    </div>

    <div class="modal" id="inviteesModal">
        <div class="modal-header">
            <h3>New Invitees</h3>
            <i class="fa-solid fa-times close-btn" onclick="closeAllModals()"></i>
        </div>
        <div class="modal-body" style="text-align: center;">
            <div style="font-size: 40px; color: var(--primary-orange); font-weight: 800; margin-bottom: 5px;">
                <?php echo $today_refers; ?>
            </div>
            <div style="color: var(--text-muted);">Users registered today</div>
        </div>
    </div>

    <div class="earn-header">
        Earn
    </div>

    <div class="commission-wrapper">
        <div class="commission-card">
            <div class="title">Today's Earned</div>
            <div class="amount">Rs<?php echo number_format($today_earned ?? 0.00, 2); ?></div>
            
            <div class="dashed-divider"></div>
            
            <div class="unclaimed-section">
                <div class="unclaimed-info">
                    <span class="unclaimed-lbl">Unclaimed Earnings</span>
                    <span class="unclaimed-val" id="ui-unclaimed">Rs<?php echo number_format($unclaimed_earnings, 2); ?></span>
                </div>
                <button class="btn-claim" id="btn-claim" onclick="claimEarnings()" <?php echo $unclaimed_earnings > 0 ? '' : 'disabled'; ?>>
                    Claim
                </button>
            </div>
        </div>
    </div>

    <div class="slider-container">
        <div class="slider-wrapper" id="scroll-wrapper">
            
            <div class="slide" id="slide1">
                <div class="stats-tabs">
                    <div class="tab active">Direct Invitees</div>
                    <div class="tab inactive">Team Invitees</div>
                </div>
                
                <div class="stats-content">
                    <div class="stats-data-panel">
                        <div class="stats-col">
                            <div class="stat-item">
                                <div class="stat-val"><?php echo $dir_reg; ?></div>
                                <div class="stat-label">Registered Users</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-val green"><?php echo $dir_dep_users; ?></div>
                                <div class="stat-label">Deposit Users</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-val orange">Rs<?php echo number_format($dir_dep_amt, 2); ?></div>
                                <div class="stat-label">Deposit Amount</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-val"><?php echo $dir_first_dep; ?></div>
                                <div class="stat-label">First Deposit Users</div>
                            </div>
                        </div>
                        
                        <div class="stats-col">
                            <div class="stat-item">
                                <div class="stat-val"><?php echo $team_reg; ?></div>
                                <div class="stat-label">Registered Users</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-val green"><?php echo $team_dep_users; ?></div>
                                <div class="stat-label">Deposit Users</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-val orange">Rs<?php echo number_format($team_dep_amt, 2); ?></div>
                                <div class="stat-label">Deposit Amount</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-val"><?php echo $team_first_dep; ?></div>
                                <div class="stat-label">First Deposit Users</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="slide" id="slide2">
                <div class="slide-overview">
                    <div class="pills-row">
                        <div class="pill">
                            <div class="val">Rs<?php echo number_format($today_earned ?? 0.00, 2); ?></div>
                            <div class="lbl">Today's Earned</div>
                        </div>
                        <div class="pill">
                            <div class="val">Rs<?php echo number_format($yesterday_comm, 2); ?></div>
                            <div class="lbl">Yesterday's</div>
                        </div>
                        <div class="pill">
                            <div class="val">Rs<?php echo number_format($total_comm, 2); ?></div>
                            <div class="lbl">Total Comm.</div>
                        </div>
                    </div>
                    
                    <div class="slide-divider"></div>

                    <div class="counts-row">
                        <div class="counts-col">
                            <div class="val"><?php echo $dir_reg; ?></div>
                            <div class="lbl">Direct Invitees</div>
                            <div style="font-size: 10px; color: var(--text-muted); margin-top: 2px;">(Level 1)</div>
                        </div>
                        <div class="counts-col">
                            <div class="val"><?php echo $team_reg; ?></div>
                            <div class="lbl">Team Invitees</div>
                            <div style="font-size: 10px; color: var(--text-muted); margin-top: 2px;">(Level 2 - 3)</div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <div class="carousel-dots">
        <div class="dot active" onclick="scrollToSlide(0)"></div>
        <div class="dot inactive" onclick="scrollToSlide(1)"></div>
    </div>

    <div class="btn-wrapper">
        <button class="btn-invite" onclick="window.location.href='share.php'">Invite Friends To Get Money</button>
    </div>

    <div class="menu-wrapper">
        <div class="menu-list">
            
            <div class="menu-item">
                <div class="menu-left">
                    <div class="menu-icon"><i class="fa-solid fa-envelope-open-text"></i></div>
                    <div class="menu-text">Invite code</div>
                </div>
                <div class="menu-right">
                    <span class="invite-code-text <?php echo strpos($my_refercode, 'Error') !== false ? 'invite-error' : ''; ?>" id="invite-code">
                        <?php echo htmlspecialchars($my_refercode); ?>
                    </span>
                    <?php if(strpos($my_refercode, 'Error') === false): ?>
                        <i class="fa-regular fa-copy copy-icon" id="copy-btn-icon" onclick="copyCode(this)"></i>
                    <?php endif; ?>
                </div>
            </div>
            
            <a onclick="openModal('inviteesModal'); return false;" class="menu-item">
                <div class="menu-left">
                    <div class="menu-icon"><i class="fa-solid fa-clipboard-list"></i></div>
                    <div class="menu-text">New Invitees</div>
                </div>
                <div class="menu-right"><i class="fa-solid fa-angle-right arrow-icon"></i></div>
            </a>
            
            <a onclick="openModal('rulesModal'); return false;" class="menu-item">
                <div class="menu-left">
                    <div class="menu-icon"><i class="fa-solid fa-bookmark"></i></div>
                    <div class="menu-text">Invitation Rules</div>
                </div>
                <div class="menu-right"><i class="fa-solid fa-angle-right arrow-icon"></i></div>
            </a>
            
            <a href="gift.php" class="menu-item">
                <div class="menu-left">
                    <div class="menu-icon"><i class="fa-solid fa-qrcode"></i></div>
                    <div class="menu-text">Gift code</div>
                </div>
                <div class="menu-right"><i class="fa-solid fa-angle-right arrow-icon"></i></div>
            </a>

            <a href="checkin.php" class="menu-item">
                <div class="menu-left">
                    <div class="menu-icon"><i class="fa-solid fa-calendar-check"></i></div>
                    <div class="menu-text">Daily Check-In</div>
                </div>
                <div class="menu-right"><i class="fa-solid fa-angle-right arrow-icon"></i></div>
            </a>

            <a href="support.php" class="menu-item">
                <div class="menu-left">
                    <div class="menu-icon"><i class="fa-solid fa-headset"></i></div>
                    <div class="menu-text">Support</div>
                </div>
                <div class="menu-right"><i class="fa-solid fa-angle-right arrow-icon"></i></div>
            </a>

        </div>
    </div>

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

    <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';
        }

        // iPhone Style Toast Function
        function showToast(message) {
            const container = document.getElementById('toast-container');
            
            // Prevent Stacking
            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);
        }

        // Copy Invite Code functionality
        function copyCode(element) {
            var text = document.getElementById("invite-code").innerText.trim();
            if(text && !text.includes("Error")) {
                navigator.clipboard.writeText(text).then(function() {
                    const originalClasses = element.className;
                    element.className = "fa-solid fa-check copy-icon";
                    element.style.color = "#32c149";
                    
                    setTimeout(() => {
                        element.className = originalClasses;
                        element.style.color = ""; 
                    }, 2000);

                }, function(err) {
                    showToast("Failed to copy code");
                });
            }
        }

        // Claim Earnings AJAX
        function claimEarnings() {
            const btn = document.getElementById('btn-claim');
            btn.disabled = true;
            btn.innerText = "Claiming...";
            
            const formData = new FormData();
            formData.append('action', 'claim');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if(data.success) {
                    showToast(data.message);
                    document.getElementById('ui-unclaimed').innerText = 'Rs0.00';
                    btn.innerText = "Claimed";
                    setTimeout(() => location.reload(), 2000); 
                } else {
                    showToast(data.message);
                    btn.disabled = false;
                    btn.innerText = "Claim";
                }
            })
            .catch(err => {
                showToast('Network error occurred');
                btn.disabled = false;
                btn.innerText = "Claim";
            });
        }

        // Horizontal Scroll Slider Logic
        const scrollWrapper = document.getElementById('scroll-wrapper');
        const dots = document.querySelectorAll('.carousel-dots .dot');
        
        let isDown = false;
        let startX;
        let scrollLeft;

        scrollWrapper.addEventListener('mousedown', (e) => {
            isDown = true;
            startX = e.pageX - scrollWrapper.offsetLeft;
            scrollLeft = scrollWrapper.scrollLeft;
            scrollWrapper.style.scrollSnapType = 'none'; 
        });

        scrollWrapper.addEventListener('mouseleave', () => {
            if(!isDown) return;
            isDown = false;
            scrollWrapper.style.scrollSnapType = 'x mandatory';
        });

        scrollWrapper.addEventListener('mouseup', () => {
            isDown = false;
            scrollWrapper.style.scrollSnapType = 'x mandatory'; 
            scrollWrapper.scrollBy({left: 1, behavior: 'auto'});
            scrollWrapper.scrollBy({left: -1, behavior: 'auto'});
        });

        scrollWrapper.addEventListener('mousemove', (e) => {
            if (!isDown) return;
            e.preventDefault();
            const x = e.pageX - scrollWrapper.offsetLeft;
            const walk = (x - startX) * 1.5; 
            scrollWrapper.scrollLeft = scrollLeft - walk;
        });

        scrollWrapper.addEventListener('scroll', () => {
            let index = Math.round(scrollWrapper.scrollLeft / scrollWrapper.clientWidth);
            dots.forEach((dot, i) => {
                dot.className = i === index ? 'dot active' : 'dot inactive';
            });
        });

        function scrollToSlide(index) {
            const slideWidth = scrollWrapper.clientWidth;
            scrollWrapper.scrollTo({ left: index * slideWidth, behavior: 'smooth' });
        }
    </script>
</body>
</html>