<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit; }
require_once __DIR__ . '/../config.php';

// Force Pakistan Timezone so the server stops using US time
date_default_timezone_set('Asia/Karachi'); 
$pdo->exec("SET time_zone = '+05:00';");

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

// Fetch withdrawal fee from settings
$fee_setting = $pdo->query("SELECT setting_value FROM admin_settings WHERE setting_key = 'withdrawal_fee_percent'")->fetchColumn();
$wd_fee_pct = $fee_setting !== false ? (float)$fee_setting : 10;
$wd_fee_multiplier = $wd_fee_pct / 100;

// Save withdrawal account
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'];

    if ($action === 'save_account') {
        $method = strtoupper(trim($_POST['method']??''));
        $name   = trim($_POST['account_name']??'');
        $number = trim($_POST['account_number']??'');
        $allowed = ['EASYPAISA','JAZZCASH'];
        
        if (!in_array($method,$allowed)||!$name||!$number) { echo json_encode(['ok'=>false,'msg'=>'Fill all fields']); exit; }
        
        // 1. Prevent modification if already bound
        $check_existing = $pdo->prepare("SELECT id FROM withdrawal_accounts WHERE user_id=? AND method=?");
        $check_existing->execute([$uid, $method]);
        if ($check_existing->fetch()) {
            echo json_encode(['ok'=>false,'msg'=>'Account already bound. Modification is not allowed.']); exit;
        }

        // 2. Prevent binding an account that another user already has
        $check_duplicate = $pdo->prepare("SELECT id FROM withdrawal_accounts WHERE account_number=?");
        $check_duplicate->execute([$number]);
        if ($check_duplicate->fetch()) {
            echo json_encode(['ok'=>false,'msg'=>'This account is already connected to another user.']); exit;
        }

        try {
            // Removed ON DUPLICATE KEY UPDATE to strictly enforce no-modifications
            $pdo->prepare("INSERT INTO withdrawal_accounts (user_id,method,account_name,account_number) VALUES(?,?,?,?)")
                ->execute([$uid,$method,$name,$number]);
            echo json_encode(['ok'=>true]);
        } catch(Exception $e){ echo json_encode(['ok'=>false,'msg'=>'DB error']); }
        exit;
    }

    if ($action === 'submit_withdrawal') {
        // 1. HARD ANTI-SPAM LOCK: Kills double-click duplicate bugs instantly
        if (isset($_SESSION['wd_lock']) && (time() - $_SESSION['wd_lock']) < 10) {
            echo json_encode(['ok'=>false,'msg'=>'Processing your previous request, please wait...']); 
            exit;
        }
        $_SESSION['wd_lock'] = time();

        $amount = (float)($_POST['amount']??0);
        $method = strtoupper(trim($_POST['method']??''));
        $allowed = ['EASYPAISA','JAZZCASH'];
        if (!in_array($method,$allowed)) { echo json_encode(['ok'=>false,'msg'=>'Invalid method']); exit; }
        if ($amount < 500) { echo json_encode(['ok'=>false,'msg'=>'Minimum withdrawal is Rs500']); exit; }

        $is_demo = $_SESSION['is_demo'] ?? 0;
        if (!$is_demo) {
            $user_demo_check = (int)$pdo->query("SELECT is_demo FROM users WHERE id = $uid")->fetchColumn();
            if ($user_demo_check) $is_demo = 1;
        }

        if ($is_demo) {
            // Get user account for method
            $acc = $pdo->prepare("SELECT * FROM withdrawal_accounts WHERE user_id=? AND method=?");
            $acc->execute([$uid,$method]); $acc=$acc->fetch();
            if (!$acc) { echo json_encode(['ok'=>false,'msg'=>'Please add a '.$method.' account first']); exit; }

            // Check balance
            $u2 = $pdo->prepare("SELECT balance FROM users WHERE id=?"); $u2->execute([$uid]); $u2=$u2->fetch();
            if ((float)$u2['balance'] < $amount) { echo json_encode(['ok'=>false,'msg'=>'Insufficient balance']); exit; }

            $now_pkt = date('Y-m-d H:i:s');
            $payout_order_id = "DEMO_WD_" . time() . "_" . $uid . "_" . rand(1000, 9999);
            try {
                $pdo->beginTransaction();
                // Deduct balance
                $pdo->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$amount,$uid]);
                // Insert withdrawal record as approved/sent directly
                $pdo->prepare("INSERT INTO withdrawals (user_id,amount,method,account_name,account_number,status,payout_order_id,payout_status,created_at,updated_at) VALUES(?,?,?,?,?,'approved',?,'sent',?,?)")
                    ->execute([$uid, $amount, $method, $acc['account_name'], $acc['account_number'], $payout_order_id, $now_pkt, $now_pkt]);
                $pdo->commit();
                echo json_encode(['ok'=>true,'msg'=>'Withdrawal completed successfully!']);
            } catch(Exception $e){
                if ($pdo->inTransaction()) $pdo->rollBack();
                echo json_encode(['ok'=>false,'msg'=>'DB error saving withdrawal']);
            }
            exit;
        }


       // ============================================
        // DEPOSIT REQUIREMENTS CHECK
        // ============================================
        
        // HARD LOCK FOR USER 147: Must have at least 5000 in NEW deposits
        if ($uid === 147) {
            // Set the exact time you want to start counting from (YYYY-MM-DD HH:MM:SS)
            $penalty_start_date = '2026-05-25 13:40:00'; 
            
            // Only sum deposits that happened AFTER the penalty start date
            $new_dep_147 = (float)$pdo->query("SELECT SUM(amount) FROM deposits WHERE user_id=147 AND status IN ('approved', 'completed', 'success', '1') AND created_at >= '$penalty_start_date'")->fetchColumn();
            
            if ($new_dep_147 < 5000) {
                // Calculate how much fresh balance they still owe
                $shortfall = 5000 - $new_dep_147;
                echo json_encode([
                    'ok' => false, 
                    'msg' => 'Account Restriction: You must make a new deposit of Rs' . number_format($shortfall, 2) . ' to unlock withdrawals.'
                ]); 
                exit;
            }
        }

        // HARD LOCK FOR USER 631: Must have at least 2000 in NEW deposits
        if ($uid === 631) {
            // Set the exact time you want to start counting from (YYYY-MM-DD HH:MM:SS)
            $penalty_start_date_631 = '2026-05-31 13:40:00'; 
            
            // Only sum deposits that happened AFTER the penalty start date
            $new_dep_631 = (float)$pdo->query("SELECT SUM(amount) FROM deposits WHERE user_id=631 AND status IN ('approved', 'completed', 'success', '1') AND created_at >= '$penalty_start_date_631'")->fetchColumn();
            
            if ($new_dep_631 < 2000) {
                // Calculate how much fresh balance they still owe
                $shortfall_631 = 2000 - $new_dep_631;
                echo json_encode([
                    'ok' => false, 
                    'msg' => 'Account Restriction: You must make a new deposit of Rs' . number_format($shortfall_631, 2) . ' to unlock withdrawals.'
                ]); 
                exit;
            }
        }

        // Check if user has ANY deposit (Normal Users)
        $dep_total = (int)$pdo->query("SELECT COUNT(*) FROM deposits WHERE user_id=$uid AND status IN ('approved', 'completed', 'success', '1')")->fetchColumn();
        if ($dep_total === 0) {
            echo json_encode(['ok'=>false,'msg'=>'You need to deposit first to be able to withdraw.']); exit;
        }

        // Check if user has a deposit in the last 3 days (Normal Users)
        $dep_recent = (int)$pdo->query("SELECT COUNT(*) FROM deposits WHERE user_id=$uid AND status IN ('approved', 'completed', 'success', '1') AND created_at >= DATE_SUB(NOW(), INTERVAL 3 DAY)")->fetchColumn();
        if ($dep_recent === 0) {
            echo json_encode(['ok'=>false,'msg'=>'You need to have a deposit from last 3 days to be able to withdraw.']); exit;
        }

        // Get user account for method
        $acc = $pdo->prepare("SELECT * FROM withdrawal_accounts WHERE user_id=? AND method=?");
        $acc->execute([$uid,$method]); $acc=$acc->fetch();
        if (!$acc) { echo json_encode(['ok'=>false,'msg'=>'Please add a '.$method.' account first']); exit; }

        // Check balance & wager
        $u2 = $pdo->prepare("SELECT balance,wager FROM users WHERE id=?"); $u2->execute([$uid]); $u2=$u2->fetch();
        if ((float)$u2['wager'] > 0) { echo json_encode(['ok'=>false,'msg'=>'Please complete your wager requirement first']); exit; }
        if ((float)$u2['balance'] < $amount) { echo json_encode(['ok'=>false,'msg'=>'Insufficient balance']); exit; }

        // Check daily withdrawal limit (2 per day), EXCLUDING failed/rejected withdrawals
        $today_count = (int)$pdo->query("SELECT COUNT(*) FROM withdrawals WHERE user_id=$uid AND DATE(created_at)=CURDATE() AND status NOT IN ('rejected', 'failed')")->fetchColumn();
        if ($today_count >= 2) { echo json_encode(['ok'=>false,'msg'=>'Daily withdrawal limit (2 requests) reached']); exit; }

        // ============================================
        // WITHDRAWAL FEE CALCULATION
        // ============================================
        $fee = $amount * $wd_fee_multiplier;
        $payout_amount = $amount - $fee;

        // ============================================
        // AUTO APPROVAL: PAYOUT API INTEGRATION
        // ============================================
        // Fetch payout gateway and credentials from admin settings
        $pay_settings = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('lg_app_id','lg_key','gopay_payout_api_key','gopay_payout_api_secret','payment_routing')")->fetchAll(PDO::FETCH_KEY_PAIR);
        $routing_json = json_decode($pay_settings['payment_routing'] ?? '{}', true);
        $payout_gateway = $routing_json['payout_gateway'] ?? 'lg_pay';

        // Exact PKT Time injection to fix the 5/9 timezone bug
        $now_pkt = date('Y-m-d H:i:s'); 
        $payout_order_id = "PO_" . time() . "_" . $uid . "_" . rand(1000, 9999);

        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
        $gateway_success = false;
        $gateway_error = '';

        if ($payout_gateway === 'go_pay') {
            // ============================================
            // GOPAY PAYOUT
            // ============================================
            $gp_api_key    = $pay_settings['gopay_payout_api_key'] ?? '';
            $gp_api_secret = $pay_settings['gopay_payout_api_secret'] ?? '';

            // Get GoPay method codes from routing config
            $gp_methods = $routing_json['gateways']['go_pay']['methods'] ?? [];
            $method_lower = strtolower($method);
            $gp_method_code = $gp_methods[$method_lower]['payout_code'] ?? $method_lower;

            $notify_url = "https://pakclub24.club/webhook/";

            $body = [
                'merchant_payout_id' => $payout_order_id,
                'amount'             => intval($payout_amount),
                'currency'           => 'PKR',
                'method'             => $gp_method_code,
                'account_number'     => $acc['account_number'],
                'account_name'       => $acc['account_name'],
                'notify_url'         => $notify_url
            ];

            $body_json = json_encode($body);
            $signature = hash_hmac('sha256', $body_json, $gp_api_secret);

            $ch = curl_init('https://api.gopayx.live/api/public/v1/payouts');
            curl_setopt_array($ch, [
                CURLOPT_POST           => true,
                CURLOPT_POSTFIELDS     => $body_json,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_HTTPHEADER     => [
                    'Content-Type: application/json',
                    'x-api-key: ' . $gp_api_key,
                    'x-signature: ' . $signature
                ]
            ]);
            $resp = curl_exec($ch);
            $err  = curl_error($ch);
            curl_close($ch);

            if ($err) {
                $gateway_error = 'Payment Gateway Connection Error';
            } else {
                $res = json_decode($resp, true);
                if (isset($res['code']) && $res['code'] === 0) {
                    $gateway_success = true;
                } else {
                    $gateway_error = 'Gateway Error: ' . ($res['msg'] ?? 'Unknown Error');
                }
            }
        } else {
            // ============================================
            // LG PAY PAYOUT (Default)
            // ============================================
            $app_id = $pay_settings['lg_app_id'] ?? 'PKR3245';
            $key    = $pay_settings['lg_key'] ?? 'LqpUftaBfNNyOh7YrMSXVlro7zIOj5um';

            // Method Configuration
            $method_lower = strtolower($method);
            if ($method_lower === 'easypaisa') {
                $trade_type = 'PKRPH-EASY';
                $addon1 = 'easypaisa';
            } else {
                $trade_type = 'PKR';
                $addon1 = 'jazzcash';
            }

            $notify_url = "{$protocol}://{$_SERVER['HTTP_HOST']}/lg_payout_callback.php";

            $params = [
                'app_id'      => $app_id,
                'currency'    => $trade_type,
                'trade_type'  => $trade_type,
                'order_sn'    => $payout_order_id,
                'money'       => intval($payout_amount * 100),
                'notify_url'  => $notify_url,
                'name'        => $acc['account_name'],
                'uid'         => $acc['account_number'],
                'card_number' => $acc['account_number'],
                'addon1'      => $addon1
            ];

            // Sign the request
            $params = array_filter($params, function($v) { return $v !== '' && $v !== null; });
            ksort($params);
            $str = urldecode(http_build_query($params)) . "&key=$key"; 
            $params['sign'] = strtoupper(md5($str));

            // cURL Request
            $ch = curl_init('https://www.lg-pay.com/api/deposit/create');
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => http_build_query($params),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT => 30
            ]);
            $resp = curl_exec($ch); 
            $err = curl_error($ch); 
            curl_close($ch);

            if ($err) {
                $gateway_error = 'Payment Gateway Connection Error';
            } else {
                $res = json_decode($resp, true);
                if (isset($res['status']) && $res['status'] == 1) {
                    $gateway_success = true;
                } else {
                    $gateway_error = 'Gateway Error: ' . ($res['msg'] ?? 'Unknown Error');
                }
            }
        }

        // ============================================
        // PROCESS RESULT (Shared for all gateways)
        // ============================================
        if ($gateway_success) {
            try {
                $pdo->beginTransaction();
                // Deduct the FULL requested amount from the user's balance
                $pdo->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$amount,$uid]);
                
                // FORCE THE CREATED_AT DATE TO PAKISTAN TIME SO IT NEVER SAYS 5/9 AGAIN
                // Storing the original requested amount so user history adds up correctly with their balance deduction
                $pdo->prepare("INSERT INTO withdrawals (user_id,amount,method,account_name,account_number,status,payout_order_id,payout_status,created_at,updated_at) VALUES(?,?,?,?,?,'approved',?,'processing',?,?)")
                    ->execute([$uid, $amount, $method, $acc['account_name'], $acc['account_number'], $payout_order_id, $now_pkt, $now_pkt]);
                
                $pdo->commit();
                echo json_encode(['ok'=>true,'msg'=>'Withdrawal auto-approved! Funds will arrive shortly.']);
            } catch(Exception $e){ 
                $pdo->rollBack(); 
                echo json_encode(['ok'=>false,'msg'=>'DB error saving withdrawal']); 
            }
        } else {
            // Do NOT deduct balance. Tell user the error directly.
            echo json_encode(['ok'=>false,'msg'=> $gateway_error]);
        }
        exit;
    }
}

// ============================================
// DUPLICATE ACCOUNT CLEANUP ON PAGE LOAD
// ============================================
// Automatically remove wallets from this user if someone else already has them connected
$check_accs = $pdo->prepare("SELECT id, account_number FROM withdrawal_accounts WHERE user_id=?");
$check_accs->execute([$uid]);
foreach($check_accs->fetchAll() as $ca) {
    $has_dup = $pdo->prepare("SELECT id FROM withdrawal_accounts WHERE account_number=? AND user_id != ? LIMIT 1");
    $has_dup->execute([$ca['account_number'], $uid]);
    if ($has_dup->fetchColumn()) {
        $pdo->prepare("DELETE FROM withdrawal_accounts WHERE id=?")->execute([$ca['id']]);
    }
}

// Load data
$u = $pdo->prepare("SELECT balance,wager,is_demo FROM users WHERE id=?"); $u->execute([$uid]); $u=$u->fetch();
$balance      = (float)$u['balance'];
$is_demo      = (int)($u['is_demo'] ?? 0);
$wager        = $is_demo ? 0.0 : (float)$u['wager'];
$withdrawable = $is_demo ? max(0,$balance) : (($wager <= 0) ? max(0,$balance) : 0);

// User's saved accounts (Fetched AFTER the duplicate cleanup process)
$accs = $pdo->prepare("SELECT * FROM withdrawal_accounts WHERE user_id=?"); $accs->execute([$uid]); $accs=$accs->fetchAll();
$accs_by_method = [];
foreach($accs as $a) $accs_by_method[$a['method']] = $a;

// Withdrawal history
$wds = $pdo->query("SELECT * FROM withdrawals WHERE user_id=$uid ORDER BY id DESC LIMIT 150")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Withdraw - PakClub</title>

<link rel="icon" href="../favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../css/global.css">
<style>
/* --- Base Styles --- */
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #160e0a; color: #fff; font-family: 'Segoe UI', sans-serif; max-width: 414px; margin: 0 auto; min-height: 100vh; position: relative; }

/* --- Header Wrapper (Hidden but Included) --- */
.header-wrapper { display: none; }

/* --- Top App Bar --- */
.app-header { background: #1a0f0a; padding: 14px 16px; display: flex; align-items: center; justify-content: space-between; position: sticky; top: 0; z-index: 10; border-bottom: 1px solid #2c1a12; }
.app-header .title { font-size: 17px; font-weight: 700; flex: 1; text-align: center; }
.hbtn { color: #fff; font-size: 18px; text-decoration: none; width: 32px; display: flex; justify-content: center; cursor: pointer; transition: color 0.2s; }
.hbtn-group { display: flex; gap: 8px; color: #a6958a; }
.hbtn-group .hbtn { color: #a6958a; }

/* --- Balance Cards --- */
.balance-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; }
.bal-card { background: #2b221e; border: 1px solid #3c302a; border-radius: 12px; padding: 12px; }
.bal-label { font-size: 13px; color: #fff; font-weight: 600; margin-bottom: 12px; display: flex; align-items: center; gap: 6px; justify-content: center; }
.bal-label i { cursor: pointer; color: #a6958a; font-size: 12px; }
.bal-content { display: flex; align-items: center; justify-content: center; gap: 10px; }
.bal-icon { color: #5a4b43; font-size: 24px; }
.bal-val { font-size: 18px; font-weight: 800; color: #f59e0b; }
.bal-val-wd { color: #f59e0b; }

/* --- Main Withdraw Tab --- */
#wdTab { padding-bottom: 90px; }
.section { padding: 0 16px; margin-bottom: 20px; }

/* Input */
.amount-hint { font-size: 13px; color: #fff; margin-bottom: 12px; }
.amount-input-wrap { background: #1a0f0a; border: 1px solid #3c302a; border-radius: 8px; display: flex; align-items: center; padding: 0 14px; margin-bottom: 6px; transition: border-color .3s; }
.amount-input-wrap:focus-within { border-color: #d97706; }
.amount-prefix { font-size: 15px; font-weight: 700; color: #fff; margin-right: 12px; padding: 14px 0; border-right: 1px solid #3c302a; padding-right: 12px; }
.amount-input { flex: 1; background: transparent; border: none; color: #fff; font-size: 15px; font-weight: 600; outline: none; padding: 14px 0; }
.amount-input::placeholder { color: #5a4b43; font-weight: 500; }
.all-btn { background: none; border: none; color: #d97706; font-size: 15px; font-weight: 700; cursor: pointer; padding: 14px 0 14px 12px; border-left: 1px solid #3c302a; }

/* Fee Display */
.fee-breakdown { display: flex; justify-content: space-between; font-size: 13px; color: #a6958a; margin-bottom: 16px; padding: 0 4px; display: none; }
.fee-breakdown span strong { font-weight: 700; }

/* Account Display Area */
.account-area { margin-bottom: 20px; }
.btn-add-acc { background: #261710; color: #d97706; padding: 16px; border-radius: 8px; text-align: center; cursor: pointer; border: none; width: 100%; font-size: 14px; font-weight: 600; display: flex; justify-content: center; align-items: center; gap: 8px; }
.btn-add-acc:active { background: #3c2317; }
.btn-add-acc i { font-size: 16px; }

.saved-acc-card { background: #1a0f0a; border: 1px solid #3c302a; border-radius: 8px; padding: 14px 16px; display: none; align-items: center; justify-content: space-between; cursor: pointer; }
.saved-acc-left { display: flex; align-items: center; gap: 12px; }
.saved-acc-details { display: flex; flex-direction: column; align-items: center; gap: 4px; }
.saved-acc-logo { width: 32px; height: 32px; border-radius: 6px; object-fit: contain; }
.saved-acc-name { color: #fff; font-size: 11px; font-weight: 600; letter-spacing: 0.5px; }
.saved-acc-divider { width: 1px; height: 30px; background: #3c302a; margin: 0 4px; }
.saved-acc-num { color: #fff; font-size: 15px; font-weight: 600; }
.saved-acc-right { color: #ef4444; font-size: 16px; font-weight: bold; }

/* Payment Methods */
.section-label { font-size: 14px; font-weight: 700; color: #fff; margin-bottom: 12px; display: block; }
.section-label span { color: #ef4444; }
.method-grid { display: flex; gap: 12px; margin-bottom: 24px; }
.method-card { flex: 1; background: #1a0f0a; border: 1px solid #3c302a; border-radius: 8px; padding: 10px; display: flex; align-items: center; justify-content: center; gap: 8px; position: relative; cursor: pointer; transition: all 0.2s; }
.method-card.active { border: 1px solid #f59e0b; background: rgba(245, 158, 11, 0.1); }
.method-card.active::before { content: '\f164'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; top: -8px; left: -8px; background: #dc2626; color: #fff; border: 2px solid #160e0a; border-radius: 50%; width: 22px; height: 22px; font-size: 10px; display: flex; align-items: center; justify-content: center; }
.method-card.active::after { content: '\f00c'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; bottom: 0; right: 0; background: #f59e0b; color: #fff; font-size: 10px; padding: 2px 4px 1px 5px; border-top-left-radius: 8px; }
.method-icon { width: 28px; height: 28px; background: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; padding: 4px; }
.method-icon img { width: 100%; height: 100%; object-fit: contain; }
.method-name { font-size: 13px; font-weight: 600; color: #8b7a70; }
.method-card.active .method-name { color: #fff; }

/* Info Rows */
.info-list { display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px; border-top: 1px solid #2c1a12; padding-top: 20px; }
.info-item { background: #1a0f0a; border: 1px solid #2c1a12; padding: 14px 16px; border-radius: 8px; display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: #8b7a70; }
.info-item span:last-child { color: #fff; font-weight: 600; }

.text-box { margin-bottom: 20px; }
.text-title { font-size: 14px; font-weight: 700; color: #fff; margin-bottom: 8px; }
.text-para { font-size: 13px; color: #a6958a; line-height: 1.5; }
.text-para span { color: #f59e0b; }

/* Sticky Button */
.sticky-pay-wrapper { position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 414px; background: #160e0a; padding: 12px 16px; border-top: 1px solid #2c1a12; z-index: 100; }
.wd-btn { width: 100%; background: #4b3020; color: #8b7a70; border: none; border-radius: 30px; padding: 14px; font-size: 16px; font-weight: 700; cursor: not-allowed; transition: all .2s; }
.wd-btn.active { background: #5a4b43; color: #a6958a; } /* Mid state */
.wd-btn.ready { background: #d97706; color: #fff; cursor: pointer; }
.wd-btn.ready:active { transform: scale(0.98); background: #b45309; }

/* --- History Tab --- */
#historyTab { display: none; padding-bottom: 30px; }
.hist-nav { display: flex; border-bottom: 1px solid #2c1a12; margin-bottom: 16px; }
.hist-nav-item { flex: 1; text-align: center; padding: 14px 0; font-size: 14px; color: #8b7a70; cursor: pointer; border-bottom: 2px solid transparent; transition: 0.2s; }
.hist-nav-item.active { color: #d97706; border-bottom-color: #d97706; }

.hist-summary { display: flex; justify-content: space-between; padding: 0 16px 12px 16px; font-size: 14px; color: #fff; font-weight: 600; }
.hist-summary .total-val { color: #f59e0b; font-weight: 500; }

.hist-card { background: #26160d; border-radius: 10px; padding: 16px; margin: 0 16px 12px 16px; display: flex; flex-direction: column; gap: 12px; }
.hist-card-top { display: flex; justify-content: space-between; align-items: flex-start; }
.hist-left-group { display: flex; gap: 12px; align-items: flex-start; }
.hist-icon { width: 34px; height: 34px; background: #d97706; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 18px; flex-shrink: 0; }
.hist-details { display: flex; flex-direction: column; gap: 6px; }
.hist-date { color: #d97706; font-size: 13px; font-weight: 500; }
.hist-order { color: #d1d5db; font-size: 13px; display: flex; align-items: center; gap: 6px; }
.hist-order i { color: #8b7a70; cursor: pointer; font-size: 14px; }
.hist-method { color: #d1d5db; font-size: 13px; }

.hist-amounts { text-align: right; display: flex; flex-direction: column; gap: 4px; }
.hist-req { color: #8b7a70; font-size: 12px; text-decoration: line-through; }
.hist-bal { color: #22c55e; font-size: 14px; font-weight: 600; }
.hist-status { font-size: 13px; font-weight: 600; text-transform: capitalize; margin-top: 2px;}
.empty-msg { text-align: center; color: #8b7a70; font-size: 14px; padding: 40px 0; font-weight: 600; display: none; }
.no-more { text-align: center; color: #8b7a70; font-size: 14px; padding: 20px 0; display: none; }

/* Modal */
.modal-bg { position: fixed; inset: 0; background: rgba(0,0,0,.8); z-index: 999; display: none; align-items: center; justify-content: center; padding: 20px; }
.modal-bg.open { display: flex; }
.modal { background: #1a0f0a; border: 1px solid #3c302a; border-radius: 12px; width: 100%; max-width: 360px; overflow: hidden; }
.modal-head { padding: 16px 20px; text-align: center; border-bottom: 1px solid #2c1a12; position: relative; }
.modal-head h3 { font-size: 16px; font-weight: 700; color: #fff; }
.modal-close { position: absolute; right: 16px; top: 16px; background: none; border: none; color: #8b7a70; font-size: 20px; cursor: pointer; }
.modal-body { padding: 20px; }
.mfield { margin-bottom: 16px; }
.mfield label { display: block; font-size: 13px; color: #8b7a70; margin-bottom: 8px; font-weight: 600; }
.mfield input { width: 100%; background: #2b1a13; border: 1px solid #3c302a; border-radius: 8px; padding: 14px; color: #fff; font-size: 14px; outline: none; }
.mfield input:focus { border-color: #d97706; }
.save-btn { width: 100%; background: #d97706; color: #fff; border: none; border-radius: 8px; padding: 14px; font-size: 15px; font-weight: 700; cursor: pointer; margin-top: 8px; }

/* Toast */
.toast { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background: rgba(20,20,20,.95); border: 1px solid #3c302a; color: #fff; padding: 12px 24px; border-radius: 30px; font-size: 13px; font-weight: 600; display: none; z-index: 9999; white-space: nowrap; box-shadow: 0 4px 12px rgba(0,0,0,0.5); }

/* Hide arrows */
input[type=number]::-webkit-outer-spin-button, input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
input[type=number] { -moz-appearance: textfield; }
</style>
</head>
<body>

<div class="header-wrapper">
    <?php @require_once __DIR__ . '/../external/header.php'; ?>
</div>

<div class="app-header">
    <a href="javascript:void(0)" onclick="handleBack()" class="hbtn"><i class="fa-solid fa-angle-left"></i></a>
    <div class="title" id="pageTitle">Withdraw</div>
    <div class="hbtn-group">
        <a href="../support.php" class="hbtn"><i class="fa-solid fa-headset"></i></a>
        <a href="javascript:void(0)" class="hbtn" id="historyToggleBtn" onclick="toggleHistory()"><i class="fa-solid fa-file-invoice-dollar"></i></a>
    </div>
</div>

<div class="balance-row">
    <div class="bal-card">
        <div class="bal-label">Cash Balance <i class="fa-solid fa-rotate-right" onclick="refreshBal()"></i></div>
        <div class="bal-content">
            <i class="fa-solid fa-wallet bal-icon"></i>
            <div class="bal-val" id="balVal">Rs<?= number_format($balance,0) ?></div>
        </div>
    </div>
    <div class="bal-card">
        <div class="bal-label">Withdrawable</div>
        <div class="bal-content">
            <i class="fa-solid fa-money-bill-transfer bal-icon"></i>
            <div class="bal-val bal-val-wd" id="wdVal">Rs<?= number_format($withdrawable,0) ?></div>
        </div>
    </div>
</div>

<div id="wdTab">
    <div class="section">
        <div class="amount-hint">Withdraw amount: Min Rs500</div>
        <div class="amount-input-wrap">
            <span class="amount-prefix">Rs</span>
            <input type="number" class="amount-input" id="wdAmount" placeholder="500" min="500" oninput="checkForm()">
            <button class="all-btn" onclick="setAll()">All</button>
        </div>
        
        <div class="fee-breakdown" id="feeBreakdown">
            <span>Fee (<?= $wd_fee_pct ?>%): <strong id="feeValue" style="color: #ef4444;">Rs0.00</strong></span>
            <span>You will receive: <strong id="receiveValue" style="color: #22c55e;">Rs0.00</strong></span>
        </div>

        <div class="account-area">
            <button class="btn-add-acc" id="noAccState" onclick="openAccountModal()">
                <i class="fa-solid fa-circle-plus"></i> Add Withdrawal Account
            </button>
            
            <div class="saved-acc-card" id="hasAccState" onclick="toast('Account modification is not allowed', false)">
                <div class="saved-acc-left">
                    <div class="saved-acc-details">
                        <img src="" class="saved-acc-logo" id="displayAccLogo" alt="logo">
                        <div class="saved-acc-name" id="displayAccMethod">JAZZCASH</div>
                    </div>
                    <div class="saved-acc-divider"></div>
                    <div class="saved-acc-num" id="displayAccNum">033****817</div>
                </div>
                <div class="saved-acc-right"><i class="fa-solid fa-lock" style="color: #5a4b43; font-size: 14px;"></i></div>
            </div>
        </div>

        <label class="section-label">Payment methods <span>*</span></label>
        <div class="method-grid">
            <div class="method-card active" id="m-EASYPAISA" onclick="setMethod('EASYPAISA')">
                <div class="method-icon"><img src="https://vectorseek.com/wp-content/uploads/2023/12/EASYPAISA-New-Logo-Vector.svg--300x161.png" alt="EasyPaisa"></div>
                <div class="method-name">EASYPAISA</div>
            </div>
            <div class="method-card" id="m-JAZZCASH" onclick="setMethod('JAZZCASH')">
                <div class="method-icon"><img src="https://iconape.com/wp-content/png_logo_vector/jazz-cash-logo.png" alt="JazzCash"></div>
                <div class="method-name">JAZZCASH</div>
            </div>
        </div>

        <div class="info-list">
            <div class="info-item">
                <span>Withdrawal Fee:</span>
                <span style="color: #ef4444;"><?= $wd_fee_pct ?>%</span>
            </div>
            <div class="info-item">
                <span>Remaining Withdrawal Limit:</span>
                <span>Rs50,000.00</span>
            </div>
            <div class="info-item">
                <span>Withdrawal Daily Limit:</span>
                <span>2</span>
            </div>
            <div class="info-item">
                <span>Wager Required to Withdraw:</span>
                <span id="wagerInfo">Rs<?= number_format($wager,2) ?></span>
            </div>
        </div>

        <div class="text-box">
            <div class="text-title">Withdrawal Speed:</div>
            <div class="text-para">Under normal circumstances, the withdrawal amount will arrive in your account <span>instantly</span>. A <?= $wd_fee_pct ?>% fee is applied to all transactions.</div>
        </div>
    </div>

    <div class="sticky-pay-wrapper" id="stickyPay">
        <button type="button" class="wd-btn" id="wdBtn" onclick="submitWithdrawal()" disabled>Withdraw</button>
    </div>
</div>

<div id="historyTab">
    <div class="hist-nav">
        <div class="hist-nav-item active" id="filter-1d" onclick="filterHistory(1, this)">1 Day</div>
        <div class="hist-nav-item" onclick="filterHistory(7, this)">7 Days</div>
        <div class="hist-nav-item" onclick="filterHistory(30, this)">30 Days</div>
    </div>
    
    <div class="hist-summary">
        <div id="histDateRange">-- to --</div>
        <div>Total: <span class="total-val" id="histTotalVal">Rs0.00</span></div>
    </div>

    <div id="histList">
        <?php if($wds): foreach($wds as $w): 
            $st = strtolower($w['status'] ?? '');
            $pst = strtolower($w['payout_status'] ?? '');
            
            if ($pst === 'sent' || $st === 'completed') {
                $display_st = 'Completed';
                $status_color = '#22c55e'; // Green
                $data_status = 'completed';
            } elseif ($st === 'rejected' || $pst === 'failed') {
                $display_st = 'Failed';
                $status_color = '#ef4444'; // Red
                $data_status = 'failed';
            } else {
                $display_st = 'Processing';
                $status_color = '#f59e0b'; // Orange
                $data_status = 'processing';
            }

            $display_date = date('Y-m-d H:i:s', strtotime($w['created_at']));
            $oid = 'WD'.date('Ymd',strtotime($w['created_at'])).substr(md5($w['id']),0,12);
            $short_oid = strlen($oid) > 15 ? substr($oid, 0, 6) . '...' . substr($oid, -6) : $oid;
            $timestamp = strtotime($w['created_at']) * 1000;
            
            // Fee logic for history view
            $original_req = (float)$w['amount'];
            $fee_deducted = $original_req * $wd_fee_multiplier;
            $received_amount = $original_req - $fee_deducted;
        ?>
        <div class="hist-card" data-timestamp="<?= $timestamp ?>" data-amount="<?= $original_req ?>" data-status="<?= $data_status ?>">
            <div class="hist-card-top">
                <div class="hist-left-group">
                    <div class="hist-icon"><i class="fa-solid fa-clock-rotate-left" style="transform: scaleX(-1);"></i></div>
                    <div class="hist-details">
                        <div class="hist-date"><?= $display_date ?></div>
                        <div class="hist-order">Order ID: <?= $short_oid ?> <i class="fa-regular fa-copy" onclick="copyToClipboard('<?= htmlspecialchars($oid) ?>')"></i></div>
                        <div class="hist-method">Method: <?= $w['method'] ?></div>
                    </div>
                </div>
                <div class="hist-amounts">
                    <div class="hist-req">Req: Rs<?= number_format($original_req, 2) ?></div>
                    <div class="hist-bal">Received: Rs<?= number_format($received_amount, 2) ?></div>
                    <div class="hist-status" style="color: <?= $status_color ?>;"><?= $display_st ?></div>
                </div>
            </div>
            <?php if($w['reject_reason']): ?><div style="font-size:11px;color:#f87171;margin-top:6px;"><i class="fa-solid fa-circle-info"></i> <?= htmlspecialchars($w['reject_reason']) ?></div><?php endif; ?>
        </div>
        <?php endforeach; endif; ?>
        
        <div class="empty-msg" id="histEmpty">No withdrawal records found.</div>
        <div class="no-more" id="histNoMore">no more</div>
    </div>
</div>

<div class="modal-bg" id="accModal">
    <div class="modal">
        <div class="modal-head">
            <h3>Add Account</h3>
            <button class="modal-close" onclick="closeModal()"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="modal-body">
            <div class="mfield">
                <label>Account Name</label>
                <input type="text" id="accName" placeholder="e.g. Ali Raza">
            </div>
            <div class="mfield">
                <label>Account Number</label>
                <input type="text" id="accNum" placeholder="03XXXXXXXXX">
            </div>
            <button class="save-btn" onclick="saveAccount()">Save</button>
        </div>
    </div>
</div>

<div class="toast" id="toast"></div>

<script>
let selMethod = 'EASYPAISA';
let currentBalance = <?= $balance ?>;
let withdrawable = <?= $withdrawable ?>;
let wager = <?= $wager ?>;
const accs = <?= json_encode($accs_by_method) ?>;

// Logos
const logos = {
    'EASYPAISA': 'https://vectorseek.com/wp-content/uploads/2023/12/EASYPAISA-New-Logo-Vector.svg--300x161.png',
    'JAZZCASH': 'https://iconape.com/wp-content/png_logo_vector/jazz-cash-logo.png'
};

document.addEventListener("DOMContentLoaded", () => {
    setMethod('EASYPAISA');
    filterHistory(1, document.getElementById('filter-1d'));
    checkForm();
    
    // Check URL parameters to auto-open history on page reload
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('history') === '1') {
        toggleHistory();
        const cleanUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
        window.history.replaceState({path: cleanUrl}, '', cleanUrl);
    }
});

function maskNumber(num) {
    if(!num) return '';
    if(num.length > 6) return num.substring(0,3) + '****' + num.substring(num.length-3);
    return num;
}

function setMethod(m) {
    selMethod = m;
    document.querySelectorAll('.method-card').forEach(b => b.classList.remove('active'));
    document.getElementById('m-'+m).classList.add('active');
    
    // Update Account Area
    const acc = accs[selMethod];
    if (acc) {
        document.getElementById('noAccState').style.display = 'none';
        document.getElementById('hasAccState').style.display = 'flex';
        document.getElementById('displayAccNum').innerText = maskNumber(acc.account_number);
        document.getElementById('displayAccMethod').innerText = selMethod;
        document.getElementById('displayAccLogo').src = logos[selMethod];
    } else {
        document.getElementById('noAccState').style.display = 'flex';
        document.getElementById('hasAccState').style.display = 'none';
    }
    
    checkForm();
}

function setAll() {
    document.getElementById('wdAmount').value = withdrawable;
    checkForm();
}

function checkForm() {
    const amt = parseFloat(document.getElementById('wdAmount').value) || 0;
    const btn = document.getElementById('wdBtn');
    const feeBox = document.getElementById('feeBreakdown');
    
    // Live Fee Update
    if (amt > 0) {
        const feePct = <?= $wd_fee_pct ?> / 100;
        const fee = amt * feePct;
        const receive = amt - fee;
        document.getElementById('feeValue').innerText = 'Rs' + fee.toFixed(2);
        document.getElementById('receiveValue').innerText = 'Rs' + receive.toFixed(2);
        feeBox.style.display = 'flex';
    } else {
        feeBox.style.display = 'none';
    }
    
    // Check lock state
    if (btn.getAttribute('data-processing') === '1') return;

    if (amt >= 500 && amt <= withdrawable && wager <= 0 && accs[selMethod]) {
        btn.classList.add('ready');
        btn.classList.remove('active');
        btn.disabled = false;
    } else if (withdrawable > 0) {
        btn.classList.add('active');
        btn.classList.remove('ready');
        btn.disabled = true;
    } else {
        btn.classList.remove('ready', 'active');
        btn.disabled = true;
    }
}

function openAccountModal() {
    document.getElementById('accModal').classList.add('open');
    if (accs[selMethod]) {
        document.getElementById('accName').value = accs[selMethod].account_name;
        document.getElementById('accNum').value = accs[selMethod].account_number;
    } else {
        document.getElementById('accName').value = '';
        document.getElementById('accNum').value = '';
    }
}

function saveAccount() {
    const accName = document.getElementById('accName').value.trim();
    const accNum = document.getElementById('accNum').value.trim();
    const btn = document.querySelector('.save-btn');

    if (!accName || !accNum) {
        toast('Please fill all fields', false);
        return;
    }

    // Prevent double clicking
    btn.disabled = true;
    btn.innerText = 'Saving...';

    api({
        action: 'save_account',
        method: selMethod,
        account_name: accName,
        account_number: accNum
    }, r => {
        // Reset button
        btn.disabled = false;
        btn.innerText = 'Save';

        if (r.ok) {
            toast('Account saved successfully', true);
            
            // Update local object so we don't need to refresh the page
            accs[selMethod] = {
                account_name: accName,
                account_number: accNum,
                method: selMethod
            };
            
            closeModal();
            setMethod(selMethod); // This re-triggers the UI update to show the new account
        } else {
            toast(r.msg || 'Error saving account', false);
        }
    });
}
function closeModal() {
    document.getElementById('accModal').classList.remove('open');
}

function toast(m, ok=true) {
    const t = document.getElementById('toast');
    t.style.display = 'block';
    t.style.borderLeft = '4px solid ' + (ok ? '#22c55e' : '#ef4444');
    t.innerText = m;
    setTimeout(() => t.style.display = 'none', 3000);
}

function api(data, cb) {
    const fd = new FormData();
    for(const[k,v] of Object.entries(data)) fd.append(k,v);
    fetch('withdraw.php', {method:'POST', body:fd})
        .then(r => r.json())
        .then(cb)
        .catch(() => toast('Network error', false));
}

function refreshBal() {
    fetch('../balance.php').then(r=>r.json()).then(d => {
        if(d.ok) {
            currentBalance = d.balance;
            withdrawable = d.withdrawable;
            wager = d.wager;
            document.getElementById('balVal').innerText = 'Rs' + d.balance.toLocaleString();
            document.getElementById('wdVal').innerText = 'Rs' + d.withdrawable.toLocaleString();
            document.getElementById('wagerInfo').innerText = 'Rs' + d.wager.toFixed(2);
            document.getElementById('wdVal').style.color = d.withdrawable > 0 ? '#f59e0b' : '#8b7a70';
            toast('Balance refreshed');
            checkForm();
        }
    });
}

function submitWithdrawal() {
    const btn = document.getElementById('wdBtn');
    
    // Hard check to instantly prevent double tapping before API responds
    if (btn.disabled || btn.getAttribute('data-processing') === '1') return;

    const amt = parseFloat(document.getElementById('wdAmount').value);
    if (!amt || amt < 500) { toast('Minimum withdrawal is Rs500', false); return; }
    if (!accs[selMethod]) { toast('Please add account first', false); return; }
    
    // Lock Button completely
    btn.setAttribute('data-processing', '1');
    btn.disabled = true; 
    btn.classList.remove('ready');
    btn.innerText = 'Processing...';
    
    api({action:'submit_withdrawal', amount:amt, method:selMethod}, r => {
        toast(r.msg, r.ok);
        if(r.ok) {
            document.getElementById('wdAmount').value = '';
            setTimeout(() => {
                window.location.href = window.location.pathname + '?history=1';
            }, 1500);
        } else {
            // Unlock button only if there was an error
            btn.removeAttribute('data-processing');
            btn.innerText = 'Withdraw';
            checkForm();
        }
    });
}

// History Functions
function filterHistory(days, btnElement) {
    document.querySelectorAll('.hist-nav-item').forEach(el => el.classList.remove('active'));
    if(btnElement) btnElement.classList.add('active');
    
    const now = new Date();
    now.setHours(23, 59, 59, 999);
    
    const startDate = new Date();
    startDate.setDate(now.getDate() - (days - 1));
    startDate.setHours(0, 0, 0, 0);
    
    const pad = n => String(n).padStart(2, '0');
    const endYMD = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
    const startYMD = `${startDate.getFullYear()}-${pad(startDate.getMonth()+1)}-${pad(startDate.getDate())}`;
    
    let total = 0;
    let visibleCount = 0;
    
    document.querySelectorAll('.hist-card').forEach(card => {
        const cardTime = parseInt(card.getAttribute('data-timestamp'));
        if (cardTime >= startDate.getTime() && cardTime <= now.getTime()) {
            card.style.display = 'flex';
            visibleCount++;
            const status = card.getAttribute('data-status');
            if (status === 'completed') {
                total += parseFloat(card.getAttribute('data-amount'));
            }
        } else {
            card.style.display = 'none';
        }
    });
    
    document.getElementById('histDateRange').innerText = `${startYMD} to ${endYMD}`;
    document.getElementById('histTotalVal').innerText = 'Rs' + total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    
    if (visibleCount === 0) {
        document.getElementById('histEmpty').style.display = 'block';
        document.getElementById('histNoMore').style.display = 'none';
    } else {
        document.getElementById('histEmpty').style.display = 'none';
        document.getElementById('histNoMore').style.display = 'block';
    }
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => toast('Order ID copied!')).catch(() => toast('Failed to copy', false));
}

function toggleHistory() {
    const wdTab = document.getElementById('wdTab');
    const histTab = document.getElementById('historyTab');
    const title = document.getElementById('pageTitle');
    const stickyPay = document.getElementById('stickyPay');
    const histBtn = document.getElementById('historyToggleBtn');
    
    if (histTab.style.display === 'block') {
        histTab.style.display = 'none';
        wdTab.style.display = 'block';
        stickyPay.style.display = 'block';
        title.innerText = 'Withdraw';
        histBtn.style.color = '#a6958a';
    } else {
        histTab.style.display = 'block';
        wdTab.style.display = 'none';
        stickyPay.style.display = 'none';
        title.innerText = 'Withdrawal history';
        histBtn.style.color = '#fff';
    }
}

function handleBack() {
    const histTab = document.getElementById('historyTab');
    if (histTab.style.display === 'block') {
        toggleHistory();
    } else {
        window.location.href = '../index.php';
    }
}
</script>
</body>
</html>