<?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';");
// Check if user is logged in
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    header('Location: /login.php');
    exit;
}
$user_id = (int)$_SESSION['user_id'];
// =========================================================
// 2. AUTO-HEAL DATABASE SCHEMA (Runs silently on first view)
// =========================================================
try {
    $pdo->exec("ALTER TABLE users ADD COLUMN last_checkin_date DATE DEFAULT NULL");
} catch (Exception $e) {
    // Column already exists, safe to ignore
}
try {
    $pdo->exec("ALTER TABLE users ADD COLUMN checkin_streak INT DEFAULT 0");
} catch (Exception $e) {
    // Column already exists, safe to ignore
}
// =========================================================
// 3. REWARDS CONFIGURATION
// =========================================================
$rewards = [
    1 => 5.00,
    2 => 8.00,
    3 => 15.00,
    4 => 20.00,
    5 => 26.00,
    6 => 30.00,
    7 => 50.00
];
try {
    $r_stmt = $pdo->query("SELECT setting_value FROM admin_settings WHERE setting_key = 'daily_rewards'");
    if ($r_stmt) {
        $rewards_json = $r_stmt->fetchColumn();
        if ($rewards_json) {
            $parsed_rewards = json_decode($rewards_json, true);
            if (is_array($parsed_rewards) && count($parsed_rewards) == 7) {
                // Map array [day1_val, day2_val, ...] to 1-indexed array
                $rewards = [
                    1 => (float)$parsed_rewards[0],
                    2 => (float)$parsed_rewards[1],
                    3 => (float)$parsed_rewards[2],
                    4 => (float)$parsed_rewards[3],
                    5 => (float)$parsed_rewards[4],
                    6 => (float)$parsed_rewards[5],
                    7 => (float)$parsed_rewards[6]
                ];
            }
        }
    }
} catch (Exception $e) {}
// =========================================================
// 4. AJAX CHECK-IN CLAIM HANDLER (POST)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'checkin') {
    header('Content-Type: application/json');
    
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));
    
    try {
        $pdo->beginTransaction();
        
        // Fetch and lock the user row to prevent race conditions / double claiming
        $stmt = $pdo->prepare("SELECT last_checkin_date, checkin_streak, balance, wager FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'User not found.']);
            exit;
        }
        
        $last_checkin = $user['last_checkin_date'];
        $streak = (int)$user['checkin_streak'];
        
        // Validation: Already checked in today
        if ($last_checkin === $today) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Already checked in today!']);
            exit;
        }
        
        // Calculate the streak day to claim today
        if ($last_checkin === $yesterday) {
            $new_streak = $streak + 1;
            if ($new_streak > 7) {
                $new_streak = 1;
            }
        } else {
            // Missed a day or first check-in ever, resets to Day 1
            $new_streak = 1;
        }
        
        $reward_amount = $rewards[$new_streak];
        
        // Update user row: credit balance, increment wager requirement (1x wager), save streak & check-in date
        $update = $pdo->prepare("UPDATE users SET balance = balance + ?, wager = wager + ?, last_checkin_date = ?, checkin_streak = ? WHERE id = ?");
        $update->execute([$reward_amount, $reward_amount, $today, $new_streak, $user_id]);
        
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Successfully checked in!',
            'reward' => $reward_amount,
            'streak' => $new_streak,
            'new_balance' => number_format($user['balance'] + $reward_amount, 2)
        ]);
        
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['success' => false, 'message' => 'Check-in failed. Please try again later.']);
    }
    exit;
}
// =========================================================
// 5. GET REQUEST: EVALUATE STATUS & STREAK
// =========================================================
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
try {
    $stmt = $pdo->prepare("SELECT last_checkin_date, checkin_streak, balance FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user) {
        $last_checkin = $user['last_checkin_date'];
        $streak = (int)$user['checkin_streak'];
        $balance = $user['balance'];
    } else {
        $last_checkin = null;
        $streak = 0;
        $balance = 0.00;
    }
} catch (Exception $e) {
    $last_checkin = null;
    $streak = 0;
    $balance = 0.00;
}
// Determine active state
$checked_in_today = ($last_checkin === $today);
if ($checked_in_today) {
    // Already checked in today.
    $current_streak_day = $streak; 
} else {
    // Not checked in today. Evaluate next step:
    if ($last_checkin === $yesterday) {
        // Checked in yesterday, so next day is streak + 1
        $current_streak_day = $streak + 1;
        if ($current_streak_day > 7) {
            $current_streak_day = 1;
        }
    } else {
        // Missed a day or first time, resets to Day 1
        $current_streak_day = 1;
    }
}
?>
<!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>Daily Check-In - PAKclub</title>
    <!-- Premium Google Fonts: Outfit and Inter -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;700;900&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            box-sizing: border-box;
            font-family: 'Outfit', 'Inter', sans-serif;
            margin: 0;
            padding: 0;
        }
        /* Hide scrollbars for maximum premium experience */
        html, body, .app-container {
            -ms-overflow-style: none;  /* IE and Edge */
            scrollbar-width: none;  /* Firefox */
        }
        html::-webkit-scrollbar, body::-webkit-scrollbar, .app-container::-webkit-scrollbar {
            display: none; /* Chrome, Safari, Opera */
        }
        body {
            background: #000000 !important; /* Don't force any color outside the wrapper */
            color: #ffffff;
            min-height: 100vh;
            display: flex;
            justify-content: center;
        }
        .app-container {
            width: 100%;
            max-width: 420px;
            background: linear-gradient(to bottom, #43210d, #140904); /* Apply gradient inside wrapper only */
            min-height: 100vh;
            position: relative;
            padding-bottom: 120px;
            box-shadow: 0 0 30px rgba(0,0,0,0.8);
            display: flex;
            flex-direction: column;
            border-left: 1px solid rgba(196, 148, 58, 0.1);
            border-right: 1px solid rgba(196, 148, 58, 0.1);
        }
        
        /* Top Navigation Header */
        .top-nav {
            background-color: #1c100a;
            border-bottom: 1px solid #2e1c12;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px 20px;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .back-btn {
            color: #ffffff;
            font-size: 20px;
            text-decoration: none;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .back-btn:active {
            transform: scale(0.9);
        }
        .nav-title {
            font-size: 18px;
            font-weight: 700;
            color: #ffffff;
            letter-spacing: 0.5px;
        }
        .balance-badge {
            background: rgba(196, 148, 58, 0.12);
            border: 1px solid rgba(196, 148, 58, 0.35);
            border-radius: 20px;
            padding: 5px 12px;
            font-size: 12px;
            font-weight: 700;
            color: #d4a84a;
            letter-spacing: 0.3px;
        }
        /* Hero Banner Section */
        .hero-section {
            position: relative;
            padding: 35px 20px 25px 20px;
            text-align: center;
            background: linear-gradient(180deg, #1c100a 0%, #140904 100%);
            border-bottom: 1px solid rgba(255, 255, 255, 0.03);
            overflow: hidden;
        }
        .hero-section::before {
            content: '';
            position: absolute;
            top: -50px; left: 50%; transform: translateX(-50%);
            width: 140%; height: 160px;
            background: radial-gradient(ellipse at center, rgba(196, 148, 58, 0.18) 0%, transparent 65%);
            z-index: 1;
            pointer-events: none;
        }
        .chest-icon {
            font-size: 60px;
            color: #ffd54f;
            margin-bottom: 15px;
            filter: drop-shadow(0 0 20px rgba(255, 213, 79, 0.5));
            animation: floatChest 3s ease-in-out infinite;
            position: relative;
            z-index: 2;
        }
        @keyframes floatChest {
            0%, 100% { transform: translateY(0) rotate(0); }
            50% { transform: translateY(-8px) rotate(2deg); }
        }
        .hero-title {
            font-size: 24px;
            font-weight: 900;
            margin-bottom: 6px;
            color: #ffffff;
            letter-spacing: 0.3px;
            text-shadow: 0 2px 10px rgba(0,0,0,0.5);
            position: relative;
            z-index: 2;
        }
        .hero-subtitle {
            font-size: 13px;
            color: #a0938a;
            line-height: 1.5;
            margin-bottom: 5px;
            position: relative;
            z-index: 2;
        }
        .streak-container {
            font-size: 13px;
            color: #ffffff;
            margin-top: 8px;
            background: rgba(196, 148, 58, 0.08);
            border: 1px solid rgba(196, 148, 58, 0.2);
            padding: 4px 14px;
            border-radius: 30px;
            display: inline-block;
            position: relative;
            z-index: 2;
        }
        .rules-badge {
            display: inline-block;
            background: rgba(255, 255, 255, 0.03);
            border: 1px dashed rgba(196, 148, 58, 0.25);
            padding: 6px 14px;
            border-radius: 8px;
            font-size: 11px;
            color: #c4a46a;
            margin-top: 15px;
            font-weight: 500;
            letter-spacing: 0.2px;
            position: relative;
            z-index: 2;
        }
        /* Grid for Check-in Cards */
        .cards-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 14px;
            padding: 22px;
        }
        /* Premium Card Styling */
        .checkin-card {
            background: linear-gradient(145deg, #241b16 0%, #1a120e 100%);
            border: 1px solid rgba(196, 148, 58, 0.15);
            border-radius: 16px;
            padding: 18px 10px;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
            transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
        }
        .card-day {
            font-size: 11px;
            font-weight: 700;
            color: #8a7a70;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 0.8px;
        }
        
        .card-coin {
            font-size: 24px;
            color: #c4943a;
            margin-bottom: 10px;
            transition: transform 0.3s;
        }
        .card-amount {
            font-size: 15px;
            font-weight: 800;
            color: #ffffff;
            letter-spacing: -0.2px;
        }
        /* CARD STATE: CLAIMED */
        .checkin-card.claimed {
            background: linear-gradient(145deg, #121c14 0%, #0d140f 100%);
            border-color: rgba(76, 175, 80, 0.25);
            box-shadow: none;
            opacity: 0.8;
        }
        .checkin-card.claimed .card-day {
            color: #81c784;
        }
        .checkin-card.claimed .card-coin {
            color: #81c784;
            transform: scale(0.9);
        }
        .checkin-card.claimed .card-amount {
            color: #81c784;
            text-decoration: line-through;
            opacity: 0.7;
        }
        .checkin-card.claimed::before {
            content: "\f058"; /* fa-circle-check */
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            position: absolute;
            top: 6px;
            right: 6px;
            font-size: 12px;
            color: #81c784;
        }
        /* CARD STATE: ACTIVE (TODAY) */
        .checkin-card.active {
            border: 1px solid rgba(255, 215, 0, 0.6);
            background: linear-gradient(145deg, #3d2510 0%, #201309 100%);
            box-shadow: 0 0 20px rgba(242, 109, 15, 0.35);
            transform: scale(1.05);
            z-index: 2;
        }
        .checkin-card.active .card-day {
            color: #ffb74d;
        }
        .checkin-card.active .card-coin {
            color: #ffd54f;
            transform: scale(1.15);
            animation: bounceCoin 2.5s infinite;
        }
        .checkin-card.active .card-amount {
            color: #ffd54f;
            font-weight: 900;
            text-shadow: 0 0 10px rgba(255, 213, 79, 0.4);
        }
        @keyframes bounceCoin {
            0%, 100% { transform: scale(1.15) translateY(0); }
            50% { transform: scale(1.15) translateY(-4px); }
        }
        /* CARD STATE: LOCKED */
        .checkin-card.locked {
            opacity: 0.6;
            filter: brightness(0.75);
            box-shadow: none;
        }
        /* Day 7 Highlight Card (Full Width) */
        .day7-card {
            grid-column: 1 / span 3;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            padding: 20px 25px;
            background: linear-gradient(135deg, #c4943a 0%, #3d2510 50%, #1a0d04 100%);
            border: 1px solid rgba(255, 215, 0, 0.45);
            box-shadow: 0 8px 25px rgba(196, 148, 58, 0.15);
        }
        .day7-card .card-coin {
            font-size: 40px;
            color: #ffd54f;
            filter: drop-shadow(0 0 12px rgba(255, 213, 79, 0.7));
            margin-bottom: 0;
            animation: floatBigCoin 3s ease-in-out infinite;
        }
        @keyframes floatBigCoin {
            0%, 100% { transform: translateY(0) scale(1.05); }
            50% { transform: translateY(-4px) scale(1.1); }
        }
        .day7-card .card-text-group {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: 4px;
        }
        .day7-card .card-day {
            font-size: 12px;
            color: #ffd54f;
            margin-bottom: 0;
            letter-spacing: 1px;
            font-weight: 800;
        }
        .day7-card .card-amount {
            font-size: 22px;
            color: #ffffff;
            font-weight: 900;
            text-shadow: 0 2px 8px rgba(0,0,0,0.5);
        }
        .day7-card.claimed {
            background: linear-gradient(145deg, #121c14 0%, #0d140f 100%);
            border-color: rgba(76, 175, 80, 0.25);
            box-shadow: none;
        }
        .day7-card.claimed .card-day {
            color: #81c784;
        }
        .day7-card.claimed .card-coin {
            color: #81c784;
            filter: none;
            animation: none;
        }
        .day7-card.claimed .card-amount {
            color: #81c784;
            text-decoration: line-through;
            opacity: 0.7;
        }
        .day7-card.claimed::before {
            font-size: 18px;
            top: 14px;
            right: 18px;
        }
        .day7-card.active {
            border: 2px solid #ffd54f;
            box-shadow: 0 0 28px rgba(255, 213, 79, 0.5);
        }
        /* Action Claim Button */
        .btn-container {
            padding: 0 22px 20px 22px;
            margin-top: 10px;
        }
        .claim-btn {
            width: 100%;
            background: linear-gradient(to bottom, #d4952a, #c47a1a);
            color: #ffffff;
            padding: 15px;
            border: 2px solid #ffea00;
            border-radius: 30px;
            font-size: 17px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            box-shadow: 0 5px 0 #7a3a14, 0 8px 15px rgba(242, 109, 15, 0.3);
            transition: all 0.1s ease;
            outline: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            cursor: pointer;
        }
        .claim-btn:active {
            transform: translateY(5px);
            box-shadow: 0 0 0 #7a3a14, 0 2px 4px rgba(0,0,0,0.6);
        }
        .claim-btn:disabled {
            background: #33241d !important;
            color: #92837b !important;
            border: 1px solid #4a3429 !important;
            box-shadow: none !important;
            cursor: not-allowed;
            transform: none !important;
        }
        /* Glass Toast Notification */
        .custom-toast {
            visibility: hidden;
            min-width: auto;
            background: rgba(20, 20, 20, 0.8); 
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px); 
            color: #fff;
            text-align: center;
            border-radius: 50px; 
            padding: 10px 24px;
            position: fixed;
            z-index: 9999;
            left: 50%;
            bottom: 50px; 
            transform: translateX(-50%);
            font-size: 13px;
            font-weight: 500;
            opacity: 0;
            transition: opacity 0.3s, bottom 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            border: 1px solid rgba(255, 255, 255, 0.15); 
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
            white-space: nowrap;
        }
        .custom-toast.show {
            visibility: visible;
            opacity: 1;
            bottom: 100px; 
        }
        /* ── Premium Claim Success Modal ── */
        .claim-modal-overlay {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.85);
            backdrop-filter: blur(6px);
            -webkit-backdrop-filter: blur(6px);
            z-index: 3000;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 24px;
        }
        .claim-modal-overlay.show {
            display: flex;
        }
        .claim-modal {
            background: linear-gradient(145deg, #3d2510 0%, #1a0d04 100%);
            border-radius: 24px;
            padding: 40px 24px 30px;
            width: 100%;
            max-width: 320px;
            text-align: center;
            border: 1px solid rgba(196, 148, 58, 0.45);
            box-shadow: 0 15px 45px rgba(0,0,0,0.9), inset 0 1px 0 rgba(196, 148, 58, 0.2);
            position: relative;
            animation: modalPopIn 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        }
        .claim-modal::before {
            content: '';
            position: absolute;
            top: -60px; left: 50%; transform: translateX(-50%);
            width: 130%; height: 120px;
            background: radial-gradient(ellipse at center, rgba(196, 148, 58, 0.3) 0%, transparent 60%);
            z-index: -1;
            pointer-events: none;
        }
        .claim-modal::after {
            content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 4px;
            background: linear-gradient(90deg, transparent, #c4943a, #f2a832, #c4943a, transparent);
            opacity: 0.8;
            border-bottom-left-radius: 24px;
            border-bottom-right-radius: 24px;
        }
        @keyframes modalPopIn {
            0% { transform: scale(0.85); opacity: 0; }
            100% { transform: scale(1); opacity: 1; }
        }
        .modal-icon {
            font-size: 60px;
            color: #ffd54f;
            margin-bottom: 20px;
            filter: drop-shadow(0 0 18px rgba(255, 213, 79, 0.7));
            animation: modalIconFloat 2s ease-in-out infinite;
        }
        @keyframes modalIconFloat {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
        }
        .modal-title {
            font-size: 22px;
            font-weight: 900;
            color: #ffffff;
            margin-bottom: 6px;
            letter-spacing: 0.3px;
        }
        .modal-subtitle {
            font-size: 13px;
            color: #a0938a;
            margin-bottom: 25px;
        }
        .modal-reward {
            font-size: 32px;
            font-weight: 900;
            color: #ffd54f;
            margin-bottom: 30px;
            text-shadow: 0 0 15px rgba(255, 213, 79, 0.4);
            letter-spacing: -0.5px;
        }
        .modal-btn {
            background: linear-gradient(to bottom, #d4952a, #c47a1a);
            color: #fff;
            border: 1px solid #ffea00;
            border-radius: 25px;
            padding: 12px 0;
            font-weight: 800;
            font-size: 14px;
            cursor: pointer;
            width: 100%;
            box-shadow: 0 4px 0 #7a3a14, 0 6px 12px rgba(242, 109, 15, 0.25);
            transition: all 0.1s ease;
            text-transform: uppercase;
        }
        .modal-btn:active {
            transform: translateY(4px);
            box-shadow: none;
        }
    </style>
</head>
<body>
<!-- Included header but don't show it -->
<div style="display: none !important; visibility: hidden !important;">
    <?php include 'external/header.php'; ?>
</div>
<div class="app-container">
    
    <!-- Top Nav -->
    <div class="top-nav">
        <!-- Back button triggers JS history back for smooth navigation -->
        <a onclick="goBack()" class="back-btn"><i class="fa-solid fa-chevron-left"></i></a>
        <div class="nav-title">Daily Check-In</div>
        <div class="balance-badge" id="displayBalance">Rs<?php echo number_format($balance, 2); ?></div>
    </div>
    <!-- Hero Banner -->
    <div class="hero-section">
        <i class="fa-solid fa-wallet chest-icon" style="color: #ffd54f;"></i>
        <h2 class="hero-title">Daily Rewards</h2>
        <p class="hero-subtitle">Log in every day to claim progressively higher cash bonuses!</p>
        
        <div class="streak-container">
            Consecutive progress: <strong style="color:#ffd54f;" id="streakCounter"><?php echo $streak; ?> Days</strong>
        </div>
        <br>
        <div>
            <span class="rules-badge"><i class="fa-solid fa-circle-info"></i> 1x Wager Requirement Applied | Reset if day is missed</span>
        </div>
    </div>
    <!-- 7 Day Cards Container -->
    <div class="cards-grid">
        <?php
        // Loop through Days 1 to 6
        for ($d = 1; $d <= 6; $d++):
            $d_status = 'locked';
            if ($checked_in_today) {
                if ($d <= $current_streak_day) {
                    $d_status = 'claimed';
                }
            } else {
                if ($d < $current_streak_day) {
                    $d_status = 'claimed';
                } elseif ($d == $current_streak_day) {
                    $d_status = 'active';
                }
            }
        ?>
            <div class="checkin-card <?php echo $d_status; ?>" id="card-day-<?php echo $d; ?>">
                <span class="card-day">Day <?php echo $d; ?></span>
                <i class="fa-solid fa-coins card-coin"></i>
                <span class="card-amount">Rs<?php echo (int)$rewards[$d]; ?></span>
            </div>
        <?php endfor; ?>
        <!-- Day 7 Highlight Card -->
        <?php
        $d = 7;
        $d_status = 'locked';
        if ($checked_in_today) {
            if ($d <= $current_streak_day) {
                $d_status = 'claimed';
            }
        } else {
            if ($d < $current_streak_day) {
                $d_status = 'claimed';
            } elseif ($d == $current_streak_day) {
                $d_status = 'active';
            }
        }
        ?>
        <div class="checkin-card day7-card <?php echo $d_status; ?>" id="card-day-7">
            <div class="card-text-group">
                <span class="card-day">Day 7 (Grand Prize)</span>
                <span class="card-amount">Rs<?php echo (int)$rewards[7]; ?></span>
            </div>
            <i class="fa-solid fa-gift card-coin"></i>
        </div>
    </div>
    <!-- Action Button -->
    <div class="btn-container">
        <button class="claim-btn" id="claimBtn" onclick="performCheckin()" <?php echo $checked_in_today ? 'disabled' : ''; ?>>
            <i class="fa-solid fa-circle-check"></i>
            <span id="btnText"><?php echo $checked_in_today ? 'Checked In Today' : 'Claim Daily Reward'; ?></span>
        </button>
    </div>
    <!-- Footer menu overlay -->
    <?php include 'external/footer.php'; ?>
</div>
<!-- Claim Success Modal Popup -->
<div class="claim-modal-overlay" id="claimModalOverlay">
    <div class="claim-modal">
        <i class="fa-solid fa-gift modal-icon"></i>
        <h3 class="modal-title">Congratulations!</h3>
        <p class="modal-subtitle" id="modalSubtitle">You successfully checked in today.</p>
        <div class="modal-reward" id="modalRewardText">+Rs0.00</div>
        <button class="modal-btn" onclick="closeSuccessModal()">Fantastic</button>
    </div>
</div>
<!-- Glass Toast Notification -->
<div id="customToast" class="custom-toast"></div>
<script>
    // Smooth Back Navigation Handler
    function goBack() {
        if (document.referrer && document.referrer.indexOf(window.location.host) !== -1) {
            window.history.back();
        } else {
            window.location.href = 'me.php';
        }
    }
    // Glassy iPhone Toast
    function showToast(message) {
        if (!message) return;
        var toast = document.getElementById("customToast");
        if(window.toastTimeout) {
            clearTimeout(window.toastTimeout);
            toast.className = "custom-toast"; 
        }
        toast.innerText = message;
        void toast.offsetWidth; // Force reflow
        toast.className = "custom-toast show";
        window.toastTimeout = setTimeout(function(){ 
            toast.className = toast.className.replace("show", ""); 
        }, 1500); 
    }
    // Modal success close
    function closeSuccessModal() {
        document.getElementById('claimModalOverlay').classList.remove('show');
    }
    // AJAX Check-in processing
    function performCheckin() {
        const claimBtn = document.getElementById('claimBtn');
        const btnText = document.getElementById('btnText');
        
        claimBtn.disabled = true;
        btnText.innerText = 'Processing...';
        let formData = new FormData();
        formData.append('action', 'checkin');
        fetch('checkin.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                // Update header wallet balance & streak display
                document.getElementById('displayBalance').innerText = 'Rs' + data.new_balance;
                document.getElementById('streakCounter').innerText = data.streak + ' Days';
                
                // Disable button
                claimBtn.disabled = true;
                btnText.innerText = 'Checked In Today';
                // Refresh UI Card statuses dynamically (no page reload)
                const currentDay = data.streak;
                for (let d = 1; d <= 7; d++) {
                    const card = document.getElementById('card-day-' + d);
                    if (card) {
                        card.className = card.className.replace(/\b(claimed|active|locked)\b/g, '');
                        if (d <= currentDay) {
                            card.classList.add('claimed');
                        } else {
                            card.classList.add('locked');
                        }
                    }
                }
                // Show custom elegant modal popup instead of standard toast
                document.getElementById('modalSubtitle').innerText = 'You successfully checked in for Day ' + data.streak + '.';
                document.getElementById('modalRewardText').innerText = '+Rs' + data.reward.toFixed(2);
                document.getElementById('claimModalOverlay').classList.add('show');
            } else {
                showToast(data.message);
                claimBtn.disabled = false;
                btnText.innerText = 'Claim Daily Reward';
            }
        })
        .catch(err => {
            showToast('Network error, please try again.');
            claimBtn.disabled = false;
            btnText.innerText = 'Claim Daily Reward';
        });
    }
</script>
</body>
</html>
