<?php
// Production error handling
error_reporting(E_ALL);
ini_set('display_errors', 0);

session_start();
date_default_timezone_set('Asia/Karachi');
require_once __DIR__ . '/config.php';

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

$userId = (int)$_SESSION['user_id'];

// 1. User Details
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// 🛑 AUTO FIX LOGIC 🛑
// Agar Admin ne koi withdrawal approve kiya hai jo transactions mein pending hai, to use complete kar do
$conn->query("UPDATE transactions t
JOIN withdrawals w ON t.user_id = w.user_id AND t.quantity = w.quantity AND t.amount = w.amount
SET t.status = 'completed' 
WHERE t.user_id = $userId AND t.type = 'Sell Egg' AND t.status = 'pending' AND w.status = 'approved'");


// 2. Settings
$settings = [];
$resSet = $conn->query("SELECT setting_key, setting_value FROM site_settings");
if ($resSet) {
    while ($r = $resSet->fetch_assoc()) {
        $settings[$r['setting_key']] = $r['setting_value'];
    }
}
$waAdmin   = !empty($settings['admin_whatsapp']) ? $settings['admin_whatsapp'] : '923000000000';
$helpLine  = !empty($settings['helpline']) ? $settings['helpline'] : '923000000000';
$community = !empty($settings['community_link']) ? $settings['community_link'] : '#';
$ceoContact= !empty($settings['ceo_contact']) ? $settings['ceo_contact'] : '923000000000';

// 3. Stats
$stmtHens = $conn->prepare("SELECT COUNT(*) as total FROM user_hens WHERE user_id = ?");
$stmtHens->bind_param("i", $userId);
$stmtHens->execute();
$totalHens = $stmtHens->get_result()->fetch_assoc()['total'] ?? 0;

// Pending Buy Hens
$stmtPendingHens = $conn->prepare("SELECT SUM(quantity) as pendingHens FROM investments WHERE user_id = ? AND status = 'pending'");
$stmtPendingHens->bind_param("i", $userId);
$stmtPendingHens->execute();
$pendingHensCount = $stmtPendingHens->get_result()->fetch_assoc()['pendingHens'] ?? 0;

// Pending Sell Eggs
$stmtPendingEggs = $conn->prepare("SELECT SUM(quantity) as pendingEggs FROM transactions WHERE user_id = ? AND type LIKE '%Sell Egg%' AND status != 'completed' AND status != 'approved'");
$stmtPendingEggs->bind_param("i", $userId);
$stmtPendingEggs->execute();
$pendingEggsCount = $stmtPendingEggs->get_result()->fetch_assoc()['pendingEggs'] ?? 0;

$usernameVal = $user['username'];
$stmtTeam = $conn->prepare("SELECT COUNT(*) as totalTeam FROM users WHERE reference_id = ?");
$stmtTeam->bind_param("s", $usernameVal);
$stmtTeam->execute();
$totalTeam = $stmtTeam->get_result()->fetch_assoc()['totalTeam'] ?? 0;

$stats = [
    'pendingHens' => $pendingHensCount, 
    'pendingEggs' => $pendingEggsCount,
    'totalTeam' => $totalTeam
];

// 4. Recent Transactions
$stmtTx = $conn->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
$stmtTx->bind_param("i", $userId);
$stmtTx->execute();
$transactionsRes = $stmtTx->get_result();
$transactions = [];
while ($row = $transactionsRes->fetch_assoc()) {
    $transactions[] = $row;
}

// 5. Salary Tiers
$salaryTiers = [];
$resTiers = $conn->query("SELECT * FROM salary_tiers ORDER BY min_active_referrals ASC");
if ($resTiers) {
    while ($t = $resTiers->fetch_assoc()) {
        $salaryTiers[] = $t;
    }
}
$currentTier = null;
foreach ($salaryTiers as $tier) {
    if ($totalTeam >= $tier['min_active_referrals']) {
        $currentTier = $tier;
    }
}

// 🛑 NAYA FIX: AUTO SYNC TIMER LOGIC 🛑
// Agar profit_history mein naya profit aaya hai, toh next_profit_at ko khud update kar do
$syncStmt = $conn->prepare("
    UPDATE investments i
    SET i.next_profit_at = DATE_ADD(i.next_profit_at, INTERVAL 1 DAY)
    WHERE i.user_id = ? 
    AND i.status = 'approved'
    AND (SELECT COUNT(*) FROM profit_history ph WHERE ph.investment_id = i.id AND ph.created_at >= i.next_profit_at) > 0
");
$syncStmt->bind_param("i", $userId);
$syncStmt->execute();
// 🛑 FIX END 🛑

// 6. PER-PLAN TIMERS (DATABASE TIME LOGIC)
// Database ka current time utha rahe hain taake manual date change karne par bhi timer sahi chale
$dbTimeQuery = $conn->query("SELECT NOW() as db_now");
$dbNowString = $dbTimeQuery->fetch_assoc()['db_now'];
$dbTimeTs = strtotime($dbNowString); // Database ka waqt timestamp mein

$plans = [];
$stmtPlans = $conn->prepare("SELECT id, quantity, amount, created_at, next_profit_at FROM investments WHERE user_id = ? AND status = 'approved' ORDER BY id ASC");
$stmtPlans->bind_param("i", $userId);
$stmtPlans->execute();
$plansRes = $stmtPlans->get_result();

while ($p = $plansRes->fetch_assoc()) {
    if (empty($p['next_profit_at'])) {
        $p['next_profit_at'] = date('Y-m-d H:i:s', strtotime($p['created_at']) + 86400);
    }
    
    // next_profit_at ko timestamp mein badla
    $nextTs = strtotime($p['next_profit_at']);
    
    // Farq nikaala (Database ke waqt aur next_profit_at ke waqt ka)
    $remaining = max(0, $nextTs - $dbTimeTs);
    
    $p['remaining'] = $remaining;
    $p['hours']   = floor($remaining / 3600);
    $p['minutes'] = floor(($remaining % 3600) / 60);
    $p['seconds'] = $remaining % 60;
    $plans[] = $p;
}

$hasActivePlan = !empty($plans);
$nextPlan = null;

if ($hasActivePlan) {
    $nextPlan = $plans[0];
    foreach ($plans as $p) {
        if ($p['remaining'] < $nextPlan['remaining']) {
            $nextPlan = $p;
        }
    }
}
$timeRemaining = $nextPlan['remaining'] ?? 0;

// Images Cache Bust
function getImgUrl($filename) {
    $path = __DIR__ . '/' . $filename;
    return $filename . '?v=' . (file_exists($path) ? filemtime($path) : time());
}
$bgURL = getImgUrl('bg.png'); $henURL = getImgUrl('hen.png'); $eggURL = getImgUrl('egg.png');
$depositURL = getImgUrl('deposit.png'); $withdrawURL = getImgUrl('withdraw.png');
$transactionURL = getImgUrl('transaction.png'); $downloadURL = getImgUrl('download.png');
$verifiedURL = getImgUrl('verified.png'); $teamURL = getImgUrl('team.png');
$profileURL = getImgUrl('profile.png');

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$referralLink = $protocol . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/register.php?reference=" . urlencode($user['username']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ALHAYAT POULTRY FARM — Dashboard</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@600;700;800&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-cream: #f6f0e4;
            --glass-bg: rgba(255, 252, 245, 0.85);
            --glass-strong: rgba(255, 253, 249, 0.95);
            --glass-border: rgba(197, 155, 72, 0.45);
            --gold-primary: #c59b48;
            --gold-rich: #a67c2e;
            --bronze-grad: linear-gradient(135deg, #dfbe7a 0%, #b9893c 100%);
            --pearl-grad: linear-gradient(135deg, #ffffff 0%, #efe6d5 100%);
            --text-dark: #2c2419;
            --text-muted: #6e614f;
            --shadow-soft: 0 10px 30px rgba(92, 70, 32, 0.10);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Plus Jakarta Sans', sans-serif; }
        html, body { min-height: 100%; width: 100%; }
        
        /* Background */
        .fixed-bg {
            position: fixed; inset: 0; width: 100vw; height: 100vh;
            background-color: var(--bg-cream);
            background-image: url('<?php echo $bgURL; ?>');
            background-size: cover; background-position: center; background-repeat: no-repeat; z-index: -999;
        }
        .fixed-bg::after {
            content: ''; position: absolute; inset: 0; background: rgba(246, 240, 228, 0.2);
        }

        body { color: var(--text-dark); display: flex; justify-content: center; padding: 16px 14px 36px 14px; }
        .dashboard-container { width: 100%; max-width: 480px; display: flex; flex-direction: column; gap: 16px; z-index: 1; }
        
        /* FIXED HEADER */
        .header-fixed-wrap {
            position: fixed; top: 0; left: 0; width: 100%; z-index: 1000;
            display: flex; justify-content: center; padding: 10px 14px;
            background: rgba(255, 253, 249, 0.85); 
            backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
            border-bottom: 1px solid rgba(197, 155, 72, 0.2);
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        }
        
        .header { width: 100%; max-width: 480px; display: flex; justify-content: space-between; align-items: center; }
        .brand-title { font-family: 'Cinzel', serif; font-weight: 800; letter-spacing: 1px; font-size: 1.05rem; color: var(--text-dark); white-space: nowrap; }
        
        .icon-btn {
            background: var(--glass-strong); border: 1px solid var(--glass-border);
            width: 40px; height: 40px; border-radius: 50%; cursor: pointer;
            color: var(--gold-rich); display: flex; align-items: center; justify-content: center;
            text-decoration: none; box-shadow: 0 4px 12px rgba(92, 70, 32, 0.08);
        }
        
        .content-wrapper { margin-top: 75px; display: flex; flex-direction: column; gap: 16px; width: 100%; }

        .glass-card {
            background: var(--glass-bg); border: 1px solid var(--glass-border);
            border-radius: 24px; padding: 18px 16px; box-shadow: var(--shadow-soft);
        }
        
        /* Profile */
        .profile-hero { position: relative; margin-top: 26px; padding-top: 44px; text-align: center; }
        .avatar-ring {
            position: absolute; top: -32px; left: 50%; transform: translateX(-50%);
            width: 68px; height: 68px; border-radius: 50%; padding: 3px; background: var(--bronze-grad);
        }
        .avatar {
            width: 100%; height: 100%; border-radius: 50%; background: #2b2318; color: #f8e5b8;
            display: flex; align-items: center; justify-content: center;
            font-family: 'Cinzel', serif; font-size: 1.55rem; font-weight: 700; border: 2px solid #fffdf9;
        }
        .profile-hero h4 { font-size: 0.76rem; color: var(--text-muted); font-weight: 600; }
        .profile-hero h2 { font-size: 1.35rem; font-weight: 800; margin: 2px 0 6px 0; }
        .badge {
            display: inline-flex; align-items: center; gap: 5px; background: linear-gradient(135deg, #f5e6c4, #e7cfa0);
            color: #5c4318; border: 1px solid rgba(185, 137, 60, 0.35); font-weight: 700;
            font-size: 0.74rem; padding: 4px 13px; border-radius: 999px;
        }

        .section-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 14px; }
        .section-header h3 { font-size: 1.02rem; font-weight: 800; }
        .sub-text { font-size: 0.72rem; color: var(--text-muted); font-weight: 600; }

        .overview-grid { display: grid; grid-template-columns: 110px 1fr; gap: 12px; align-items: center; }
        
        /* Golden Egg */
        .golden-egg-wrap {
            width: 95px; height: 120px; margin: 0 auto; border-radius: 50% 50% 48% 48% / 60% 60% 40% 40%;
            background: radial-gradient(circle at 32% 28%, #fff6d6 0%, #e7c272 35%, #b88433 78%, #8f621c 100%);
            box-shadow: 0 14px 26px rgba(166, 124, 46, 0.34), inset 0 -8px 16px rgba(92, 60, 12, 0.35), inset 0 6px 12px rgba(255, 255, 255, 0.65);
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            text-align: center; animation: floatEgg 3.8s ease-in-out infinite;
        }
        @keyframes floatEgg { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-4px); } }
        .golden-egg-wrap h3 { font-size: 1.25rem; font-weight: 800; color: #fffdf8; text-shadow: 0 2px 6px rgba(74, 48, 10, 0.55); }
        .golden-egg-wrap p { font-size: 0.65rem; font-weight: 700; color: #fff7e2; text-shadow: 0 1px 3px rgba(74, 48, 10, 0.5); }

        /* 3D TIMER */
        .timer-3d-card {
            position: relative; background: linear-gradient(145deg, #1f2a24 0%, #2e3d33 55%, #1a241f 100%);
            border: 1px solid rgba(223, 190, 122, 0.45); border-radius: 18px;
            padding: 12px 8px 10px 8px; text-align: center;
            box-shadow: 0 12px 28px rgba(20, 30, 24, 0.45), inset 0 2px 4px rgba(255, 255, 255, 0.08), inset 0 -6px 14px rgba(0, 0, 0, 0.35);
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            min-height: 100px; overflow: hidden; transform: perspective(800px) rotateX(2deg);
        }
        .timer-3d-card::before {
            content: ''; position: absolute; inset: -50%; background: radial-gradient(circle, rgba(223,190,122,0.14) 0%, transparent 65%);
            animation: timerGlow 4s ease-in-out infinite;
        }
        @keyframes timerGlow { 0%, 100% { opacity: 0.5; } 50% { opacity: 1; } }
        .timer-label { font-size: 0.55rem; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; color: #e8d3a0; margin-bottom: 8px; z-index: 2; }
        
        .timer-ring-wrap { display: flex; gap: 4px; z-index: 2; align-items: center; justify-content: center; width: 100%; }
        .time-block {
            background: linear-gradient(180deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.03) 100%);
            border: 1px solid rgba(223, 190, 122, 0.35); border-radius: 10px; 
            padding: 6px 4px; width: 42px;
            display: flex; flex-direction: column; align-items: center;
            box-shadow: 0 4px 10px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.18), inset 0 -3px 6px rgba(0,0,0,0.35);
        }
        .time-block .num { font-size: 1rem; font-weight: 800; color: #f7e7b6; text-shadow: 0 0 10px rgba(247, 231, 182, 0.45); }
        .time-block .unit { font-size: 0.45rem; font-weight: 700; color: #a8b8a4; text-transform: uppercase; margin-top: 2px; }
        .time-divider { font-size: 0.9rem; font-weight: 800; color: #dfbe7a; animation: blinkDiv 1s step-start infinite; padding-bottom: 10px; }
        @keyframes blinkDiv { 50% { opacity: 0.25; } }
        .timer-ready { font-size: 0.85rem; font-weight: 800; color: #7cf2a0; animation: readyPulse 1.2s infinite; }
        @keyframes readyPulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.06); } }

        /* ACTIVE PLANS */
        .plan-timer-list { display: flex; flex-direction: column; gap: 8px; max-height: 140px; overflow-y: auto; padding-right: 4px; }
        .plan-timer-list::-webkit-scrollbar { width: 4px; }
        .plan-timer-list::-webkit-scrollbar-thumb { background: #c59b48; border-radius: 4px; }
        
        .plan-timer-item {
            background: linear-gradient(145deg, rgba(31,42,36,0.96) 0%, rgba(26,36,31,0.98) 100%);
            border: 1px solid rgba(223, 190, 122, 0.35); border-radius: 12px; padding: 10px 12px;
            display: flex; justify-content: space-between; align-items: center; flex-shrink: 0;
        }
        .plan-timer-info h5 { font-size: 0.75rem; color: #f7e7b6; margin-bottom: 2px; }
        .plan-timer-info p { font-size: 0.6rem; color: #a8b8a4; }
        .plan-timer-count { font-size: 0.8rem; font-weight: 800; color: #f7d38a; }
        .plan-timer-count.ready { color: #7cf2a0; animation: readyPulse 1.2s infinite; }

        /* Buy/Sell */
        .buy-sell-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 16px; }
        .capsule-btn {
            border-radius: 20px; padding: 8px 12px 8px 18px; 
            text-decoration: none; display: flex; align-items: center; justify-content: space-between; 
            font-weight: 800; font-size: 1rem;
            box-shadow: 0 6px 14px rgba(92, 70, 32, 0.15); transition: transform 0.2s;
        }
        .capsule-btn:active { transform: scale(0.96); }
        .capsule-gold { background: var(--bronze-grad); color: #261b0b; border: 1px solid rgba(255, 245, 220, 0.6); }
        .capsule-pearl { background: var(--pearl-grad); color: var(--text-dark); border: 1px solid rgba(197, 155, 72, 0.45); }
        .capsule-btn img { width: 50px; height: 50px; object-fit: cover; border-radius: 12px; box-shadow: 0 2px 6px rgba(0,0,0,0.1); }

        /* Referral & Support */
        .referral-input { display: flex; gap: 8px; }
        .referral-input input { flex: 1; padding: 10px 14px; border-radius: 999px; border: 1px solid var(--glass-border); background: rgba(255,255,255,0.75); font-size: 0.8rem; outline: none; }
        .btn-copy { background: var(--bronze-grad); color: #261b0b; border: none; border-radius: 999px; padding: 10px 16px; font-weight: 700; }
        
        .support-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; text-align: center; }
        .support-item { text-decoration: none; display: flex; flex-direction: column; align-items: center; }
        .support-icon { width: 46px; height: 46px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-bottom: 6px; color: #fff; font-size: 1.1rem; }
        .bg-green { background: #2fb364; } .bg-purple { background: #9c59d1; } .bg-blue { background: #4389e8; } .bg-orange { background: #e8843c; }
        .support-item span { font-size: 0.67rem; font-weight: 700; color: var(--text-dark); }

        /* Quick Actions (Purana 3x3 Grid) */
        .quick-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
        .quick-item { 
            background: rgba(255,255,255,0.85); border: 1px solid rgba(197, 155, 72, 0.42); 
            border-radius: 16px; padding: 12px 6px; display: flex; flex-direction: column; 
            align-items: center; text-decoration: none; box-shadow: 0 4px 10px rgba(0,0,0,0.05); transition: transform 0.2s;
        }
        .quick-item:active { transform: scale(0.95); }
        .quick-icon-wrap { width: 60px; height: 60px; border-radius: 14px; margin-bottom: 8px; overflow: hidden; box-shadow: 0 4px 8px rgba(0,0,0,0.15); }
        .quick-icon-wrap img { width: 100%; height: 100%; object-fit: cover; }
        .quick-item span { font-size: 0.76rem; font-weight: 700; color: var(--text-dark); text-align: center; line-height: 1.2; }

        /* ================= NAYA PROFIT BUTTONS SECTION ================= */
        .profit-buttons-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            margin-top: 5px;
        }
        .profit-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            background: var(--bronze-grad);
            border: 1px solid rgba(255, 255, 255, 0.4);
            border-radius: 16px;
            padding: 15px;
            text-decoration: none;
            box-shadow: 0 6px 15px rgba(185, 137, 60, 0.25);
            transition: transform 0.2s;
        }
        .profit-btn:active { transform: scale(0.96); }
        .profit-btn i { font-size: 1.5rem; color: #fff; text-shadow: 0 2px 4px rgba(0,0,0,0.3); }
        .profit-btn span { font-size: 0.9rem; font-weight: 800; color: #261b0b; }

        /* ================= STATS ================= */
        .stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
        
        .stat-card { 
            background: rgba(255, 253, 249, 0.65); 
            border: 1px solid var(--glass-border); 
            border-radius: 20px; 
            padding: 15px 10px; 
            text-align: center; 
            box-shadow: 0 4px 10px rgba(0,0,0,0.03);
            backdrop-filter: blur(5px);
        }
        
        .stat-ring { 
            width: 55px; height: 55px; border-radius: 50%; margin: 0 auto 8px; 
            display: flex; align-items: center; justify-content: center; font-size: 1.15rem; 
            background: #fffdf9; box-shadow: inset 0 2px 4px rgba(0,0,0,0.05); 
        }
        .ring-gold { border: 3px solid #c59b48; color: #a67c2e; } 
        .ring-amber { border: 3px solid #dfbe7a; color: #b9893c; }
        .ring-terracotta { border: 3px solid #c97a63; color: #a8563e; }
        .ring-purple { border: 3px solid #a882c9; color: #7e57a3; }
        
        .stat-card h4 { font-size: 1.05rem; font-weight: 800; color: var(--text-dark); } 
        .stat-card p { font-size: 0.7rem; color: var(--text-muted); font-weight: 700; margin-top: 2px; }
    </style>
</head>
<body>

<div class="fixed-bg"></div>

<!-- FIXED HEADER -->
<div class="header-fixed-wrap">
    <div class="header">
        <a href="logout.php" class="icon-btn"><i class="fa-solid fa-arrow-right-from-bracket"></i></a>
        <div class="brand-wrap">
            <div class="brand-title">ALHAYAT POULTRY FARM</div>
        </div>
        <a href="profile.php" class="icon-btn"><i class="fa-regular fa-user"></i></a>
    </div>
</div>

<div class="dashboard-container">
    
    <div class="content-wrapper">
        <!-- Profile -->
        <div class="glass-card profile-hero">
            <div class="avatar-ring"><div class="avatar"><?php echo strtoupper(substr($user['username'], 0, 1)); ?></div></div>
            <h4>Welcome Back,</h4>
            <h2><?php echo htmlspecialchars($user['username']); ?></h2>
            <div class="badge"><i class="fa-solid fa-crown"></i> <?php echo htmlspecialchars($user['reference_id']); ?></div>
        </div>

        <!-- Overview -->
        <div class="glass-card">
            <div class="section-header"><h3>Account Overview</h3></div>
            <div class="overview-grid">
                <div class="golden-egg-wrap">
                    <h3><?php echo number_format($user['total_eggs']); ?></h3>
                    <p>Total Eggs</p>
                </div>
                <?php if ($hasActivePlan): ?>
                    <div class="timer-3d-card">
                        <div class="timer-label"><i class="fa-solid fa-stopwatch"></i> Next Profit In</div>
                        <div class="timer-ring-wrap" id="countdown">
                            <div class="time-block"><span class="num" id="th"><?= sprintf("%02d", $nextPlan['hours']) ?></span><span class="unit">Hrs</span></div>
                            <span class="time-divider">:</span>
                            <div class="time-block"><span class="num" id="tm"><?= sprintf("%02d", $nextPlan['minutes']) ?></span><span class="unit">Min</span></div>
                            <span class="time-divider">:</span>
                            <div class="time-block"><span class="num" id="ts"><?= sprintf("%02d", $nextPlan['seconds']) ?></span><span class="unit">Sec</span></div>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="timer-3d-card" style="background:#96493e;">
                        <div class="timer-label">No Active Plan</div>
                        <a href="investments.php" style="color:#fff; font-size:0.8rem; text-decoration:none; font-weight:bold; margin-top:5px;">Buy Hen</a>
                    </div>
                <?php endif; ?>
            </div>
            <div class="buy-sell-grid">
                <a href="investments.php" class="capsule-btn capsule-gold"><span>Buy Hen</span><img src="<?php echo $henURL; ?>" alt="Hen"></a>
                <a href="sell-egg.php" class="capsule-btn capsule-pearl"><span>Sell Egg</span><img src="<?php echo $eggURL; ?>" alt="Egg"></a>
            </div>
        </div>

        <!-- Active Plans -->
        <?php if ($hasActivePlan): ?>
        <div class="glass-card">
            <div class="section-header"><h3>Your Active Plans</h3><span class="sub-text">Alag Alag Timers</span></div>
            <div class="plan-timer-list">
                <?php foreach ($plans as $idx => $p): ?>
                    <div class="plan-timer-item">
                        <div class="plan-timer-info">
                            <h5>Plan #<?= $idx + 1 ?> — <?= (int)$p['quantity'] ?> Hens</h5>
                            <p>Bought: <?= date('d-m-Y h:i A', strtotime($p['created_at'])) ?></p>
                        </div>
                        <div class="plan-timer-count <?= $p['remaining'] <= 0 ? 'ready' : '' ?>" data-remaining="<?= $p['remaining'] ?>">
                            <?= $p['remaining'] <= 0 ? '✓ Ready' : sprintf("%02d:%02d:%02d", $p['hours'], $p['minutes'], $p['seconds']) ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Referral -->
        <div class="glass-card">
            <div class="section-header"><h3>Referral Link</h3></div>
            <div class="referral-input">
                <input type="text" value="<?php echo htmlspecialchars($referralLink); ?>" readonly id="refLink">
                <button type="button" class="btn-copy" onclick="copyLink()">Copy</button>
            </div>
        </div>

        <!-- Support -->
        <div class="glass-card">
            <div class="section-header"><h3>Support Center</h3></div>
            <div class="support-grid">
                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $waAdmin); ?>" target="_blank" class="support-item">
                    <div class="support-icon bg-green"><i class="fa-brands fa-whatsapp"></i></div>
                    <span>WhatsApp</span>
                </a>
                <a href="https://whatsapp.com/channel/your-channel-link" target="_blank" class="support-item">
                    <div class="support-icon bg-purple"><i class="fa-brands fa-whatsapp"></i></div>
                    <span>Channel</span>
                </a>
                <a href="<?php echo htmlspecialchars($community); ?>" target="_blank" class="support-item">
                    <div class="support-icon bg-blue"><i class="fa-solid fa-users-viewfinder"></i></div>
                    <span>Community</span>
                </a>
                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $ceoContact); ?>" target="_blank" class="support-item">
                    <div class="support-icon bg-orange"><i class="fa-solid fa-user-tie"></i></div>
                    <span>CEO</span>
                </a>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="glass-card">
            <div class="section-header"><h3>Quick Actions</h3></div>
            <div class="quick-grid">
                <a href="egg-sold-history.php" class="quick-item"><div class="quick-icon-wrap"><img src="<?php echo $depositURL; ?>"></div><span>Egg Sold</span></a>
                <a href="purchase-history.php" class="quick-item"><div class="quick-icon-wrap"><img src="<?php echo $withdrawURL; ?>"></div><span>Purchase</span></a>
                <a href="transactions.php" class="quick-item"><div class="quick-icon-wrap"><img src="<?php echo $transactionURL; ?>"></div><span>Transactions</span></a>
                
                <a href="app-download.php" class="quick-item"><div class="quick-icon-wrap"><img src="<?php echo $downloadURL; ?>"></div><span>App</span></a>
                <a href="fbr.php" class="quick-item"><div class="quick-icon-wrap"><img src="<?php echo $verifiedURL; ?>"></div><span>Verified</span></a>
                <a href="my-team.php" class="quick-item"><div class="quick-icon-wrap"><img src="<?php echo $teamURL; ?>"></div><span>My Team</span></a>
                
                <a href="profile.php" class="quick-item" style="grid-column: span 3; flex-direction: row; gap:10px; padding:10px 15px;">
                    <div class="quick-icon-wrap" style="margin:0; width:50px; height:50px;"><img src="<?php echo $profileURL; ?>"></div>
                    <span style="font-size:0.85rem;">Profile Settings</span>
                </a>
            </div>
        </div>

        <!-- NAYA SECTION: Profit Buttons (Quick Actions se alag) -->
        <div class="glass-card">
            <div class="section-header"><h3>Profit History</h3></div>
            <div class="profit-buttons-grid">
                <a href="profit-history.php" class="profit-btn">
                    <i class="fa-solid fa-chart-line"></i>
                    <span>Daily Profit</span>
                </a>
                <a href="profit-history.php" class="profit-btn">
                    <i class="fa-solid fa-sack-dollar"></i>
                    <span>Total Profit</span>
                </a>
            </div>
        </div>

        <!-- Stats -->
        <div class="glass-card">
            <div class="section-header"><h3>Your Statistics</h3></div>
            <div class="stats-grid">
                <!-- Total Hens -->
                <div class="stat-card">
                    <div class="stat-ring ring-gold"><i class="fa-solid fa-kiwi-bird"></i></div>
                    <h4><?= number_format($totalHens); ?></h4>
                    <p>Total Hens</p>
                </div>
                
                <!-- Pending Buy Hens -->
                <div class="stat-card">
                    <div class="stat-ring ring-amber"><i class="fa-solid fa-hourglass-half"></i></div>
                    <h4><?= number_format($stats['pendingHens']); ?></h4>
                    <p>Pending Buy Hens</p>
                </div>
                
                <!-- Pending Sell Egg -->
                <div class="stat-card">
                    <div class="stat-ring ring-terracotta"><i class="fa-solid fa-egg"></i></div>
                    <h4><?= number_format($stats['pendingEggs']); ?></h4>
                    <p>Pending Sell Egg</p>
                </div>
                
                <!-- My Team -->
                <div class="stat-card">
                    <div class="stat-ring ring-purple"><i class="fa-solid fa-users-gear"></i></div>
                    <h4><?= number_format($stats['totalTeam']); ?></h4>
                    <p>My Team</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function copyLink() {
        var copyText = document.getElementById("refLink");
        copyText.select();
        document.execCommand("copy");
        alert("Referral link copied!");
    }

    <?php if ($hasActivePlan): ?>
    // Main Timer
    let timeLeft = <?= (int)$timeRemaining ?>;
    const th = document.getElementById('th');
    const tm = document.getElementById('tm');
    const ts = document.getElementById('ts');
    const countdownWrap = document.getElementById('countdown');

    function updateMainTimer() {
        if (timeLeft <= 0) {
            countdownWrap.innerHTML = '<div class="timer-ready">✨ Ready ✨</div>';
            return;
        }
        let h = Math.floor(timeLeft / 3600); if (h >= 24) h = 23;
        let m = Math.floor((timeLeft % 3600) / 60);
        let s = timeLeft % 60;
        th.textContent = String(h).padStart(2, '0');
        tm.textContent = String(m).padStart(2, '0');
        ts.textContent = String(s).padStart(2, '0');
        timeLeft--;
    }
    updateMainTimer();
    setInterval(updateMainTimer, 1000);

    // Per Plan Timers
    const planTimers = document.querySelectorAll('.plan-timer-count[data-remaining]');
    planTimers.forEach(function(el) {
        let rem = parseInt(el.getAttribute('data-remaining'), 10) || 0;
        function tick() {
            if (rem <= 0) {
                el.textContent = '✓ Ready';
                el.classList.add('ready');
                return;
            }
            let h = Math.floor(rem / 3600);
            let m = Math.floor((rem % 3600) / 60);
            let s = rem % 60;
            el.textContent = String(h).padStart(2,'0') + ':' + String(m).padStart(2,'0') + ':' + String(s).padStart(2,'0');
            rem--;
        }
        tick();
        setInterval(tick, 1000);
    });
    <?php endif; ?>
</script>

</body>
</html>