<?php
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 1); 
require_once 'element/connection.php';
session_regenerate_id(true);

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

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

$my_id = intval($_SESSION['user_id']); // Ensure integer

// Generate CSRF token
if (empty($_SESSION['csrf_token_withdraw'])) {
    $_SESSION['csrf_token_withdraw'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token_withdraw'];

// Fetch user details with prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->bind_param("i", $my_id);
$stmt->execute();
$user_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user_data) {
    session_destroy();
    header("Location: ../login.php");
    exit();
}

// Profile completion check – now required for withdrawal
$profile_complete = true;
$missing_fields = [];

if (empty($user_data['panno'])) {
    $profile_complete = false;
    $missing_fields[] = 'PAN Card';
}
if (empty($user_data['aadharno'])) {
    $profile_complete = false;
    $missing_fields[] = 'Aadhaar Card';
}

// Bank details check
$stmt = $conn->prepare("SELECT * FROM bank_details WHERE user_id = ?");
$stmt->bind_param("i", $my_id);
$stmt->execute();
$bank_details = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$bank_details || empty($bank_details['account_number'])) {
    $profile_complete = false;
    $missing_fields[] = 'Bank Details';
}

// Fetch counts and wallet
$stmt = $conn->prepare("SELECT left_count, right_count, wallet FROM users WHERE user_id = ?");
$stmt->bind_param("i", $my_id);
$stmt->execute();
$counts = $stmt->get_result()->fetch_assoc();
$stmt->close();

$withdrawal_amount = floatval($counts['wallet']);
$tds_percentage = 5;
$admin_percentage = 10;
$tds_amount = $withdrawal_amount * $tds_percentage / 100;
$admin_amount = $withdrawal_amount * $admin_percentage / 100;
$net_amount = $withdrawal_amount - $tds_amount - $admin_amount;

// Withdrawal time check (optional, just for info)
$current_hour = (int)date('H');
$withdrawal_time_active = ($current_hour >= 6 && $current_hour < 18);

// Fetch withdrawal history (limited to 10)
$stmt = $conn->prepare("SELECT * FROM witdrawl WHERE user_id = ? ORDER BY request_date DESC LIMIT 10");
$stmt->bind_param("i", $my_id);
$stmt->execute();
$withdrawals_result = $stmt->get_result();
$stmt->close();

// Session messages
$success_message = $_SESSION['withdraw_success'] ?? '';
$error_message = $_SESSION['withdraw_error'] ?? '';
unset($_SESSION['withdraw_success'], $_SESSION['withdraw_error']);

// Rank definitions
$ranks = [
    1 => ['name' => 'STARTER', 'members' => 4, 'income' => 1000, 'rewards' => 'N/A'],
    2 => ['name' => 'BRONZE', 'members' => 16, 'income' => 1600, 'rewards' => 'IBR 2000/- Grocery Item per month (T/C)'],
    3 => ['name' => 'SILVER', 'members' => 64, 'income' => 6500, 'rewards' => 'Accidental Policy 5 Lac - 10 Lacs'],
    4 => ['name' => 'GOLD', 'members' => 256, 'income' => 28000, 'rewards' => 'INR 100000/- For Kanyadan Donation'],
    5 => ['name' => 'PLATINUM', 'members' => 1024, 'income' => 130000, 'rewards' => 'Start-up Business Training'],
    6 => ['name' => 'DIAMOND', 'members' => 4069, 'income' => 540000, 'rewards' => 'Shimla Tour'],
    7 => ['name' => 'BLACK DIAMOND', 'members' => 16384, 'income' => 2250000, 'rewards' => 'Foreign Tour + Car']
];

$total_team = $user_data['left_count'] + $user_data['right_count'];
$current_rank = 'STARTER';
$next_rank = '';
$members_needed = 0;

foreach ($ranks as $level => $rank) {
    if ($total_team >= $rank['members']) {
        $current_rank = $rank['name'];
    } else {
        $next_rank = $rank['name'];
        $members_needed = $rank['members'] - $total_team;
        break;
    }
}

// Determine if user can withdraw
$can_withdraw = $profile_complete; // True only if all required fields are present
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Secure Withdrawal">
    <meta name="keywords" content="withdrawal, funds">
    <title><?php echo htmlspecialchars($user_data['name']); ?> || Withdraw</title>
    <link href="../img/logo/logo22222.png" rel="icon">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --warning-gradient: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%);
            --danger-gradient: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            --primary-color: #667eea;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
        }

        /* Alert Messages */
        .alert-success-custom {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #1e293b;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            animation: slideIn 0.5s ease;
        }

        .alert-error-custom {
            background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            color: #1e293b;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            animation: slideIn 0.5s ease;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            border: 1px solid rgba(102, 126, 234, 0.1);
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.15);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
            font-size: 24px;
            color: white;
        }

        .stat-icon.wallet { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .stat-icon.left { background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%); }
        .stat-icon.right { background: linear-gradient(135deg, #10b981 0%, #34d399 100%); }
        .stat-icon.rank { background: linear-gradient(135deg, #ec4899 0%, #f43f5e 100%); }

        .stat-value {
            font-size: 2rem;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* Rank Card */
        .rank-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 24px;
            padding: 25px;
            color: white;
            margin-bottom: 30px;
            position: relative;
            overflow: hidden;
        }

        .rank-card::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 300px;
            height: 300px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .rank-card::after {
            content: '';
            position: absolute;
            bottom: -30%;
            left: -5%;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .current-rank {
            font-size: 1.1rem;
            opacity: 0.9;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }

        .rank-name {
            font-size: 2.5rem;
            font-weight: 800;
            margin-bottom: 15px;
            position: relative;
            z-index: 1;
        }

        .rank-progress {
            background: rgba(255, 255, 255, 0.2);
            border-radius: 30px;
            height: 10px;
            margin: 20px 0;
            position: relative;
            z-index: 1;
        }

        .rank-progress-bar {
            background: white;
            height: 10px;
            border-radius: 30px;
            width: 0%;
            box-shadow: 0 0 10px rgba(255,255,255,0.5);
        }

        .rank-next {
            position: relative;
            z-index: 1;
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 15px;
            padding: 10px 15px;
            background: rgba(255,255,255,0.1);
            border-radius: 12px;
        }

        /* Alert Box */
        .alert-box {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            animation: slideIn 0.5s ease;
        }

        .alert-title {
            font-weight: 700;
            color: #856404;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .missing-list {
            list-style: none;
            padding: 0;
            margin: 10px 0 0;
        }

        .missing-list li {
            padding: 5px 0;
            color: #856404;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* New strict error box */
        .alert-blocked {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            color: #721c24;
        }
        .alert-blocked .alert-title {
            color: #721c24;
        }

        /* Withdrawal Card */
        .withdrawal-card {
            background: white;
            border-radius: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 30px;
            transition: all 0.3s ease;
        }

        .withdrawal-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 30px 60px rgba(102, 126, 234, 0.15);
        }

        .card-header-modern {
            background: var(--primary-gradient);
            color: white;
            padding: 25px 30px;
        }

        .card-header-modern h3 {
            margin: 0;
            font-weight: 700;
            font-size: 1.5rem;
        }

        .card-header-modern p {
            margin: 5px 0 0;
            opacity: 0.9;
        }

        .card-body-modern {
            padding: 30px;
        }

        /* Amount Display */
        .amount-display {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 25px;
            text-align: center;
            border: 1px solid rgba(102, 126, 234, 0.1);
        }

        .amount-label {
            color: #64748b;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 10px;
        }

        .amount-value {
            font-size: 3.5rem;
            font-weight: 800;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            line-height: 1.2;
        }

        .amount-breakdown {
            display: flex;
            justify-content: center;
            gap: 30px;
            margin-top: 15px;
            color: #64748b;
            font-size: 0.95rem;
            flex-wrap: wrap;
        }

        .amount-note {
            margin-top: 15px;
            padding: 10px;
            background: rgba(102, 126, 234, 0.1);
            border-radius: 12px;
            color: #667eea;
            font-size: 0.9rem;
        }

        /* Info Grid */
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }

        .info-item {
            background: #f8fafc;
            border-radius: 16px;
            padding: 15px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .info-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.1);
        }

        .info-item i {
            font-size: 24px;
            color: #667eea;
            margin-bottom: 10px;
        }

        .info-item .label {
            color: #64748b;
            font-size: 0.85rem;
            margin-bottom: 5px;
        }

        .info-item .value {
            font-weight: 700;
            color: #1e293b;
            font-size: 1.1rem;
        }

        /* Form Elements */
        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 8px;
            display: block;
        }

        .form-label i {
            color: #667eea;
            margin-right: 8px;
        }

        .input-group-modern {
            position: relative;
            display: flex;
            align-items: center;
        }

        .input-icon {
            position: absolute;
            left: 15px;
            color: #94a3b8;
            font-size: 1.1rem;
        }

        .form-control-modern {
            width: 100%;
            padding: 14px 20px 14px 45px;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control-modern:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            outline: none;
        }

        .form-control-modern:read-only {
            background: #f8fafc;
            cursor: not-allowed;
        }

        /* Submit Button */
        .btn-withdraw {
            width: 100%;
            padding: 16px;
            border: none;
            border-radius: 16px;
            background: var(--primary-gradient);
            color: white;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 20px;
        }

        .btn-withdraw:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 15px 30px rgba(102, 126, 234, 0.4);
        }

        .btn-withdraw:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            background: #94a3b8;
            box-shadow: none;
        }

        /* Time Status */
        .time-status {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 50px;
            font-weight: 600;
            margin-bottom: 20px;
            animation: slideIn 0.5s ease;
        }

        .time-active {
            background: #dcfce7;
            color: #166534;
            border: 1px solid #bbf7d0;
        }

        .time-inactive {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffe69c;
        }

        /* Rank Table */
        .rank-table-container {
            overflow-x: auto;
            margin: 20px 0;
        }

        .rank-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }

        .rank-table th {
            background: #f8fafc;
            padding: 15px;
            font-weight: 700;
            color: #1e293b;
            border-radius: 12px;
        }

        .rank-table td {
            background: white;
            padding: 15px;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.03);
            transition: all 0.3s ease;
        }

        .rank-table td:hover {
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
        }

        .rank-table .current-rank-row {
            background: rgba(102, 126, 234, 0.1);
            border-left: 4px solid #667eea;
            font-weight: 600;
        }

        /* Rules List */
        .rules-list {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }

        .rule-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px;
            background: #f8fafc;
            border-radius: 16px;
            transition: all 0.3s ease;
        }

        .rule-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.1);
        }

        .rule-icon {
            width: 40px;
            height: 40px;
            border-radius: 12px;
            background: rgba(102, 126, 234, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #667eea;
            font-size: 20px;
        }

        .rule-text {
            flex: 1;
        }

        .rule-text strong {
            display: block;
            color: #1e293b;
            margin-bottom: 3px;
        }

        .rule-text small {
            color: #64748b;
        }

        /* Withdrawal Table */
        .table-container {
            overflow-x: auto;
        }

        .withdrawal-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }

        .withdrawal-table th {
            padding: 15px;
            background: #f8fafc;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
            border-radius: 12px;
        }

        .withdrawal-table td {
            padding: 15px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.03);
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-approved {
            background: #d4edda;
            color: #155724;
        }

        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        /* Animations */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-slide {
            animation: slideIn 0.5s ease forwards;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .amount-value {
                font-size: 2.5rem;
            }
            
            .amount-breakdown {
                flex-direction: column;
                gap: 10px;
            }
            
            .rank-name {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>

<?php include 'element/header.php'; ?>
<?php include 'element/sidebar.php'; ?>

<main id="main" class="main">
    <div class="pagetitle">
        <h1>Withdraw Funds</h1>
        <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li><li class="breadcrumb-item active">Withdraw</li></ol></nav>
    </div>

    <?php if ($success_message): ?>
        <div class="alert-success-custom animate-slide"><i class="fas fa-check-circle fa-2x"></i><div><h5 class="mb-1">Success!</h5><p class="mb-0"><?php echo htmlspecialchars($success_message); ?></p></div><button class="btn-close ms-auto" onclick="this.parentElement.remove()"></button></div>
    <?php endif; ?>
    <?php if ($error_message): ?>
        <div class="alert-error-custom animate-slide"><i class="fas fa-exclamation-circle fa-2x"></i><div><h5 class="mb-1">Error!</h5><p class="mb-0"><?php echo htmlspecialchars($error_message); ?></p></div><button class="btn-close ms-auto" onclick="this.parentElement.remove()"></button></div>
    <?php endif; ?>

    <div class="rank-card animate-slide">
        <div class="current-rank">Your Current Rank</div>
        <div class="rank-name"><?php echo htmlspecialchars($current_rank); ?></div>
        <?php
        $next_rank_members = 0;
        foreach ($ranks as $rank) {
            if ($rank['name'] == $current_rank) { $next_rank_members = $rank['members']; break; }
        }
        $progress = ($next_rank_members > 0) ? min(($total_team / $next_rank_members) * 100, 100) : 100;
        ?>
        <div class="rank-progress"><div class="rank-progress-bar" style="width: <?php echo $progress; ?>%"></div></div>
        <?php if ($next_rank): ?>
            <div class="rank-next"><i class="fas fa-arrow-up"></i><span>Need <?php echo $members_needed; ?> more members to reach <strong><?php echo htmlspecialchars($next_rank); ?></strong></span></div>
        <?php else: ?>
            <div class="rank-next"><i class="fas fa-crown"></i><span>Congratulations! You've reached the highest rank!</span></div>
        <?php endif; ?>
    </div>

    <div class="stats-grid">
        <div class="stat-card animate-slide" style="animation-delay: 0.1s;"><div class="stat-icon wallet"><i class="fas fa-wallet"></i></div><div class="stat-value">₹<?php echo number_format($counts['wallet'], 2); ?></div><div class="stat-label">Wallet Balance</div></div>
        <div class="stat-card animate-slide" style="animation-delay: 0.2s;"><div class="stat-icon left"><i class="fas fa-arrow-left"></i></div><div class="stat-value"><?php echo intval($counts['left_count']); ?></div><div class="stat-label">Left Count</div></div>
        <div class="stat-card animate-slide" style="animation-delay: 0.3s;"><div class="stat-icon right"><i class="fas fa-arrow-right"></i></div><div class="stat-value"><?php echo intval($counts['right_count']); ?></div><div class="stat-label">Right Count</div></div>
        <div class="stat-card animate-slide" style="animation-delay: 0.4s;"><div class="stat-icon rank"><i class="fas fa-users"></i></div><div class="stat-value"><?php echo $total_team; ?></div><div class="stat-label">Team Members</div></div>
    </div>

    <div class="time-status <?php echo $withdrawal_time_active ? 'time-active' : 'time-inactive'; ?> animate-slide">
        <i class="fas fa-clock"></i><span><?php echo $withdrawal_time_active ? '⏰ Recommended Time: 6 AM - 6 PM (Current time is within recommended window)' : '⏰ Recommended Time: 6 AM - 6 PM (Withdrawals outside this time may take longer to process)'; ?></span>
    </div>

    <!-- If profile incomplete, show blocking error instead of the old warning -->
    <?php if (!$profile_complete): ?>
        <div class="alert-box alert-blocked animate-slide">
            <div class="alert-title"><i class="fas fa-exclamation-triangle fa-lg"></i><span>Withdrawal Blocked – Incomplete KYC</span></div>
            <p>You cannot request a withdrawal until you complete the following:</p>
            <ul class="missing-list">
                <?php foreach ($missing_fields as $field): ?>
                <li><i class="fas fa-times-circle"></i> <?php echo htmlspecialchars($field); ?></li>
                <?php endforeach; ?>
            </ul>
            <a href="profile.php" class="btn btn-danger mt-3"><i class="fas fa-edit me-2"></i>Update Profile Now</a>
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-xl-5 col-lg-5 col-md-12 col-12">
            <div class="withdrawal-card animate-slide">
                <div class="card-header-modern"><h3><i class="fas fa-money-bill-wave me-2"></i>Request Withdrawal</h3><p>Enter the amount you wish to withdraw</p></div>
                <div class="card-body-modern">
                    <div class="amount-display">
                        <div class="amount-label">Available for Withdrawal</div>
                        <div class="amount-value">₹<?php echo number_format($withdrawal_amount, 2); ?></div>
                        <div class="amount-breakdown"><span><i class="fas fa-wallet"></i> Balance: ₹<?php echo number_format($withdrawal_amount, 2); ?></span><span><i class="fas fa-percent"></i> TDS (5%): -₹<?php echo number_format($tds_amount, 2); ?></span><span><i class="fas fa-file-invoice"></i> Admin (10%): -₹<?php echo number_format($admin_amount, 2); ?></span></div>
                        <div class="amount-note"><i class="fas fa-info-circle me-2"></i>Amount will be deducted only after approval</div>
                    </div>
                    <div class="info-grid">
                        <div class="info-item"><i class="fas fa-calendar-alt"></i><div class="label">Payout Dates</div><div class="value">1st & 15th</div></div>
                        <div class="info-item"><i class="fas fa-clock"></i><div class="label">Processing</div><div class="value">24-48 Hours</div></div>
                        <div class="info-item"><i class="fas fa-headset"></i><div class="label">Support</div><div class="value">24x7 Available</div></div>
                    </div>
                    <form method="POST" action="element/process_withdrawal.php" id="withdrawForm">
                        <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                        <input type="hidden" name="withdrawl_request" value="1">
                        <input type="hidden" name="user_id" value="<?php echo $my_id; ?>">
                        <div class="form-group">
                            <label>Amount (₹)</label>
                            <input type="number" name="amount" class="form-control" required min="100" step="100" id="amount"
                                <?php echo !$can_withdraw ? 'readonly' : ''; ?>>
                        </div>
                        <button type="submit" class="btn-withdraw" id="submitBtn" <?php echo !$can_withdraw ? 'disabled' : ''; ?>>
                            <span>Submit Withdrawal Request</span>
                        </button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-xl-7 col-lg-7 col-md-12 col-12">
            <!-- Rank Achievement Table -->
            <div class="withdrawal-card animate-slide" style="animation-delay: 0.2s;">
                <div class="card-header-modern" style="background: linear-gradient(135deg, #ec4899 0%, #f43f5e 100%);"><h3><i class="fas fa-crown me-2"></i>Achieve Multiple Ranks</h3><p>Grow Step by Step • Multiple Growth Opportunities • Based On Autopool System</p></div>
                <div class="card-body-modern">
                    <div class="text-center mb-4"><h5 class="fw-bold">MORE EFFORT = MORE MONEY</h5><h6 class="text-muted">HIGHER RANK = HIGHER INCOME</h6></div>
                    <div class="rank-table-container">
                        <table class="rank-table">
                            <thead><tr><th>LEVEL</th><th>MEMBERS</th><th>RANK</th><th>INCOME</th><th>REWARDS</th></tr></thead>
                            <tbody>
                                <?php foreach ($ranks as $level => $rank): ?>
                                <tr class="<?php echo ($rank['name'] == $current_rank) ? 'current-rank-row' : ''; ?>">
                                    <td><strong><?php echo $level; ?></strong></td>
                                    <td><?php echo number_format($rank['members']); ?></td>
                                    <td><?php echo htmlspecialchars($rank['name']); ?></td>
                                    <td>₹<?php echo number_format($rank['income']); ?></td>
                                    <td><small><?php echo htmlspecialchars($rank['rewards']); ?></small></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="text-center mt-4 p-3 bg-light rounded-3"><p class="text-muted mb-0"><i class="fas fa-gift me-2 text-warning"></i>Special Rewards: IBR 2000/- Grocery per month | GOA Tour | Accidental Policy 5-10 Lacs | Kanyadan Donation ₹100000 | Business Training | Shimla Tour | Foreign Tour + Car</p></div>
                </div>
            </div>
            <!-- System Rules -->
            <div class="withdrawal-card animate-slide" style="animation-delay: 0.3s;">
                <div class="card-header-modern" style="background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);"><h3><i class="fas fa-rules me-2"></i>System Rules & Guidelines</h3></div>
                <div class="card-body-modern">
                    <div class="rules-list">
                        <div class="rule-item"><div class="rule-icon"><i class="fas fa-id-card"></i></div><div class="rule-text"><strong>KYC Requirements</strong><small>One PAN, One Aadhaar, One Bank Account</small></div></div>
                        <div class="rule-item"><div class="rule-icon"><i class="fas fa-calendar-check"></i></div><div class="rule-text"><strong>Payout Schedule</strong><small>1st and 15th of every month</small></div></div>
                        <div class="rule-item"><div class="rule-icon"><i class="fas fa-percent"></i></div><div class="rule-text"><strong>Deductions</strong><small>Admin Charge: 10% | TDS: 5%</small></div></div>
                        <div class="rule-item"><div class="rule-icon"><i class="fas fa-clock"></i></div><div class="rule-text"><strong>Withdrawal Window</strong><small>6:00 AM to 6:00 PM Daily</small></div></div>
                        <div class="rule-item"><div class="rule-icon"><i class="fas fa-phone-alt"></i></div><div class="rule-text"><strong>Customer Support</strong><small>24x7 Support System Available</small></div></div>
                        <div class="rule-item"><div class="rule-icon"><i class="fas fa-shopping-cart"></i></div><div class="rule-text"><strong>One Time Purchase</strong><small>No Withdrawal Conditions</small></div></div>
                    </div>
                    <div class="alert-box mt-4" style="background: #e3f2fd; border-left-color: #2196f3;"><div class="alert-title" style="color: #0d47a1;"><i class="fas fa-user-check"></i><span>Minimum Age Requirement</span></div><p class="mb-0">All members must be 18+ years to participate in the program.</p></div>
                </div>
            </div>
            <!-- Withdrawal History -->
            <div class="withdrawal-card animate-slide" style="animation-delay: 0.4s;">
                <div class="card-header-modern" style="background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);"><h3><i class="fas fa-history me-2"></i>Withdrawal History</h3></div>
                <div class="card-body-modern">
                    <div class="table-container">
                        <table class="withdrawal-table">
                            <thead><tr><th>Date</th><th>Amount</th><th>Status</th></tr></thead>
                            <tbody>
                                <?php if ($withdrawals_result->num_rows > 0): while ($withdrawal = $withdrawals_result->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo date('d M Y', strtotime($withdrawal['request_date'])); ?></td>
                                    <td><strong>₹<?php echo number_format(floatval($withdrawal['amt']), 2); ?></strong></td>
                                    <td><?php
                                        $status = intval($withdrawal['status'] ?? 0);
                                        if ($status == 0) echo '<span class="status-badge status-pending"><i class="fas fa-clock"></i> Pending</span>';
                                        elseif ($status == 1) echo '<span class="status-badge status-approved"><i class="fas fa-check-circle"></i> Approved</span>';
                                        else echo '<span class="status-badge status-rejected"><i class="fas fa-times-circle"></i> Rejected</span>';
                                    ?></td>
                                </tr>
                                <?php endwhile; else: ?>
                                <tr><td colspan="3" class="text-center py-5"><i class="fas fa-receipt fa-4x text-muted mb-3"></i><h5 class="text-muted">No withdrawal history found</h5><p class="text-muted">Your withdrawal requests will appear here</p></td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<footer class="footer"><div class="copyright">&copy; Copyright <strong>Healthy Life Mission</strong>. All Rights Reserved</div></footer>
<a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
<script src="assets/js/main.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script>
document.getElementById('withdrawForm').addEventListener('submit', function(e) {
    // If profile incomplete, form should be disabled anyway, but double-check
    <?php if (!$can_withdraw): ?>
        e.preventDefault();
        return;
    <?php endif; ?>

    const amount = parseFloat(document.getElementById('amount').value);
    const maxAmount = <?php echo $withdrawal_amount; ?>;
    if (isNaN(amount) || amount < 100) { e.preventDefault(); alert('Please enter a valid amount (minimum ₹100)'); return; }
    if (amount > maxAmount) { e.preventDefault(); alert('You cannot withdraw more than your available balance of ₹' + maxAmount.toLocaleString('en-IN')); return; }
    <?php if (!$withdrawal_time_active): ?>
        if (!confirm('Note: You are withdrawing outside recommended hours (6 AM - 6 PM). Processing may take longer. Do you still want to proceed?')) { e.preventDefault(); return; }
    <?php endif; ?>
    if (!confirm('Are you sure you want to withdraw ₹' + amount.toLocaleString('en-IN') + '? This amount will be deducted from your wallet after approval.')) { e.preventDefault(); }
    else { document.getElementById('submitBtn').innerHTML = '<span class="spinner-border spinner-border-sm"></span> Processing...'; document.getElementById('submitBtn').disabled = true; }
});
$(document).ready(function() { if ($('.withdrawal-table tbody tr').length > 1) { $('.withdrawal-table').DataTable({ pageLength:5, order:[[0,'desc']], language:{search:"<i class='fas fa-search'></i>",searchPlaceholder:"Search...",lengthMenu:"Show _MENU_ entries",info:"Showing _START_ to _END_ of _TOTAL_ entries",infoEmpty:"No entries found",infoFiltered:"(filtered from _MAX_ total entries)"} }); } });
</script>
</body>
</html>