<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
require_once 'db.php';
require_once 'email_helper.php';

$user_id      = $_SESSION['user_id'];
$min_withdraw = 60;
$withdraw_fee = 8;

// ── Time helpers (Lusaka = Africa/Lusaka = CAT = UTC+2) ──────────────────────
function getLusakaTime(): array {
    $dt = new DateTime('now', new DateTimeZone('Africa/Lusaka'));
    return [
        'hour'    => (int)$dt->format('H'),
        'minute'  => (int)$dt->format('i'),
        'weekday' => (int)$dt->format('N'), // 1=Mon … 7=Sun
        'display' => $dt->format('D, d M Y H:i'),
    ];
}
function isWithinBusinessHours(): bool {
    $t = getLusakaTime();
    // Mon–Sun, 08:00–17:00
    $afterOpen   = ($t['hour'] >= 8);
    $beforeClose = ($t['hour'] < 17) || ($t['hour'] === 17 && $t['minute'] === 0);
    return $afterOpen && $beforeClose;
}

// ── Balance ───────────────────────────────────────────────────────────────────
$stmt1 = mysqli_prepare($conn, "SELECT SUM(amount) as total FROM deposits WHERE user_id=? AND status='processed'");
mysqli_stmt_bind_param($stmt1, "i", $user_id);
mysqli_stmt_execute($stmt1);
$total_deposits = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt1))['total'] ?? 0;
mysqli_stmt_close($stmt1);

$stmt2 = mysqli_prepare($conn, "SELECT SUM(amount) as total FROM withdrawals WHERE user_id=? AND status='processed'");
mysqli_stmt_bind_param($stmt2, "i", $user_id);
mysqli_stmt_execute($stmt2);
$total_withdrawals = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt2))['total'] ?? 0;
mysqli_stmt_close($stmt2);

$stmt3 = mysqli_prepare($conn, "SELECT SUM(amount) as total FROM profits WHERE user_id=?");
mysqli_stmt_bind_param($stmt3, "i", $user_id);
mysqli_stmt_execute($stmt3);
$total_profits = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt3))['total'] ?? 0;
mysqli_stmt_close($stmt3);

$available_balance = $total_deposits + $total_profits - $total_withdrawals;

// ── PRG: read flash messages set by previous POST ────────────────────────────
$success = $_SESSION['withdraw_success'] ?? null;
$error   = $_SESSION['withdraw_error']   ?? null;
unset($_SESSION['withdraw_success'], $_SESSION['withdraw_error']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // --- Business-hours check -------------------------------------------
    if (!isWithinBusinessHours()) {
        $lt = getLusakaTime();
        $_SESSION['withdraw_error'] = "Withdrawals are only processed between 08:00 and 17:00 Lusaka time (Monday–Sunday). Current Lusaka time: {$lt['display']}.";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }

    $amount     = floatval($_POST['amount']);
    $fee_amount = ($amount * $withdraw_fee) / 100;
    $net_amount = $amount - $fee_amount;

    if ($amount <= 0) {
        $_SESSION['withdraw_error'] = "Please enter a valid amount!";
    } elseif ($amount < $min_withdraw) {
        $_SESSION['withdraw_error'] = "Minimum withdrawal amount is ZMW " . number_format($min_withdraw, 2);
    } elseif ($amount > $available_balance) {
        $_SESSION['withdraw_error'] = "Insufficient balance! Available: ZMW " . number_format($available_balance, 2);
    } else {
        $sql  = "INSERT INTO withdrawals (user_id, amount, status, created_at) VALUES (?, ?, 'processing', NOW())";
        $stmt = mysqli_prepare($conn, $sql);

        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "id", $user_id, $amount);

            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['withdraw_success'] = "Withdrawal request submitted! You will receive ZMW " . number_format($net_amount, 2) . " after the " . $withdraw_fee . "% fee. Processing within 1 minute.";

                // Email notification
                $eq = mysqli_prepare($conn, "SELECT email FROM users WHERE id=?");
                mysqli_stmt_bind_param($eq, "i", $user_id);
                mysqli_stmt_execute($eq);
                $udat = mysqli_fetch_assoc(mysqli_stmt_get_result($eq));
                mysqli_stmt_close($eq);
                if (!empty($udat['email'])) {
                    sendWithdrawalNotification($udat['email'], $amount, 'processing');
                }

            } else {
                $_SESSION['withdraw_error'] = "Failed to submit withdrawal request: " . mysqli_error($conn);
            }
            mysqli_stmt_close($stmt);
        } else {
            $_SESSION['withdraw_error'] = "Database error: " . mysqli_error($conn);
        }
    }

    // PRG – redirect back to GET so refresh won't re-submit
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// ── History ───────────────────────────────────────────────────────────────────
$history_result = null;
$stmt = mysqli_prepare($conn, "SELECT * FROM withdrawals WHERE user_id=? ORDER BY created_at DESC LIMIT 10");
if ($stmt) {
    mysqli_stmt_bind_param($stmt, "i", $user_id);
    mysqli_stmt_execute($stmt);
    $history_result = mysqli_stmt_get_result($stmt);
}

$lt          = getLusakaTime();
$serviceOpen = isWithinBusinessHours();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Withdraw - MaxTrade</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        body{background:#000;color:#fff;font-family:Arial,sans-serif;padding-bottom:70px;font-size:13px}
        .header{background:#111;padding:15px;text-align:center;box-shadow:0 2px 10px rgba(0,0,0,.5);position:sticky;top:0;z-index:100}
        .header h1{color:#fff;font-size:22px}
        .back-btn{position:absolute;left:15px;top:50%;transform:translateY(-50%);color:#FFD700;text-decoration:none;font-size:22px}
        .container{padding:15px}
        .balance-card{background:linear-gradient(135deg,#1a3300,#2e5c00);border-radius:15px;padding:25px;margin-bottom:15px;text-align:center;box-shadow:0 4px 15px rgba(0,0,0,.5)}
        .balance-label{font-size:13px;color:#ccc;margin-bottom:8px}
        .balance-amount{font-size:38px;font-weight:bold;color:#fff}
        .info-banner{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:15px}
        .info-box{background:#111;border:1px solid #333;border-radius:8px;padding:10px 8px;text-align:center}
        .info-box.highlight{border-color:#FFD700}
        .info-box-icon{color:#FFD700;font-size:15px;margin-bottom:4px}
        .info-box-value{font-size:13px;font-weight:bold;color:#fff}
        .info-box-label{font-size:9px;color:#888;margin-top:2px}
        .fee-card{background:#111;border-radius:10px;padding:15px;margin-bottom:15px;border:1px solid #333}
        .fee-card h3{color:#FFD700;font-size:13px;margin-bottom:10px;display:flex;align-items:center;gap:6px}
        .fee-row{display:flex;justify-content:space-between;padding:6px 0;font-size:12px;border-bottom:1px solid #222}
        .fee-row:last-child{border-bottom:none;padding-top:8px}
        .fee-row span:first-child{color:#888}
        .fee-row span:last-child{color:#fff;font-weight:bold}
        .fee-row.net span:last-child{color:#4ade80;font-size:14px}
        .form-card{background:#111;border-radius:15px;padding:20px;margin-bottom:15px;box-shadow:0 4px 15px rgba(0,0,0,.5)}
        .form-card h3{color:#fff;margin-bottom:15px;font-size:14px}
        .form-group{margin-bottom:15px}
        label{display:block;margin-bottom:8px;color:#888;font-size:12px}
        input[type="number"]{width:100%;padding:12px;background:#000;border:1px solid #333;border-radius:5px;color:#fff;font-size:16px}
        input:focus{outline:none;border-color:#FFD700}
        .submit-btn{width:100%;padding:14px;background:#FFD700;color:#000;border:none;border-radius:10px;font-weight:bold;cursor:pointer;font-size:16px;margin-top:10px;display:flex;align-items:center;justify-content:center;gap:8px}
        .submit-btn:hover{background:#FFA500}
        .submit-btn:disabled{background:#555;color:#888;cursor:not-allowed}
        .message{padding:12px;margin-bottom:15px;border-radius:8px;text-align:center;font-size:12px;display:flex;align-items:center;gap:8px}
        .success{background:#1a4d1a;border:1px solid #2d7a2d;color:#4ade80}
        .error{background:#4d1a1a;border:1px solid #7a2d2d;color:#f87171}
        .history-card{background:#111;border-radius:15px;padding:20px;box-shadow:0 4px 15px rgba(0,0,0,.5)}
        .history-card h3{color:#FFD700;margin-bottom:15px;font-size:14px;display:flex;align-items:center;gap:8px}
        .history-item{background:#000;padding:12px;border-radius:8px;margin-bottom:10px;border-left:3px solid #333}
        .history-item.processing{border-left-color:#FFA500}
        .history-item.processed{border-left-color:#4ade80}
        .history-item.rejected{border-left-color:#f87171}
        .history-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:5px}
        .history-amount{font-size:16px;font-weight:bold;color:#FFD700}
        .history-fee{font-size:10px;color:#888;margin-top:2px}
        .history-date{color:#888;font-size:11px;margin-top:4px}
        .status{display:inline-block;padding:3px 10px;border-radius:4px;font-size:10px;font-weight:bold}
        .status-processing{background:#FFA500;color:#000}
        .status-processed{background:#4ade80;color:#000}
        .status-rejected{background:#f87171;color:#fff}
        .no-history{text-align:center;padding:20px;color:#888}
        .note{background:#000;border:1px solid #333;padding:10px 12px;border-radius:5px;margin-top:12px;font-size:11px;color:#888;line-height:1.6}
        .note i{color:#FFD700;margin-right:4px}
        .note strong{color:#FFD700}
        /* hours / closed */
        .closed-banner{background:rgba(248,65,65,0.1);border:1px solid rgba(248,65,65,0.35);border-radius:10px;padding:12px 14px;margin-bottom:15px;display:flex;align-items:center;gap:10px;font-size:12px;color:#f87171}
        .closed-banner i{font-size:20px;flex-shrink:0}
        .closed-banner strong{color:#ff4141}
        .hours-box{background:#111;border:1px solid #333;border-radius:10px;padding:10px 14px;margin-bottom:15px;display:flex;align-items:center;justify-content:space-between;font-size:11px}
        .h-label{color:#555}
        .h-time{font-weight:800;color:#fff}
        .h-tz{font-size:9px;color:#444}
        .status-dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:5px}
        .dot-open{background:#4ade80;box-shadow:0 0 5px #4ade80}
        .dot-closed{background:#f87171;box-shadow:0 0 5px #f87171}
        .form-disabled{opacity:0.4;pointer-events:none}
    </style>
</head>
<body>
    <div class="header">
        <a href="home.php" class="back-btn"><i class="fas fa-arrow-left"></i></a>
        <h1>Withdraw Funds</h1>
    </div>

    <div class="container">

        <?php if ($success): ?>
            <div class="message success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="message error"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <?php if (!$serviceOpen): ?>
        <div class="closed-banner">
            <i class="fas fa-clock"></i>
            <div>
                <strong>Service Closed</strong><br>
                Withdrawals are processed <strong>08:00 – 17:00</strong> Lusaka time, Monday to Sunday.<br>
                Current Lusaka time: <strong><?php echo $lt['display']; ?></strong>
            </div>
        </div>
        <?php endif; ?>

        <!-- Hours status bar -->
        <div class="hours-box">
            <div>
                <div class="h-label">Withdrawal Hours</div>
                <div class="h-time">08:00 – 17:00 <span class="h-tz">Lusaka time (Mon–Sun)</span></div>
            </div>
            <div style="text-align:right;">
                <div>
                    <span class="status-dot <?php echo $serviceOpen ? 'dot-open' : 'dot-closed'; ?>"></span>
                    <span style="font-size:11px;font-weight:700;color:<?php echo $serviceOpen ? '#4ade80' : '#f87171'; ?>">
                        <?php echo $serviceOpen ? 'OPEN' : 'CLOSED'; ?>
                    </span>
                </div>
                <div class="h-tz" style="margin-top:2px;">Now: <?php echo $lt['display']; ?></div>
            </div>
        </div>

        <div class="balance-card">
            <div class="balance-label">Available Balance</div>
            <div class="balance-amount">ZMW <?php echo number_format($available_balance, 2); ?></div>
        </div>

        <div class="info-banner">
            <div class="info-box highlight">
                <div class="info-box-icon"><i class="fas fa-arrow-up"></i></div>
                <div class="info-box-value">ZMW 60</div>
                <div class="info-box-label">Min Withdraw</div>
            </div>
            <div class="info-box">
                <div class="info-box-icon"><i class="fas fa-percentage"></i></div>
                <div class="info-box-value">8%</div>
                <div class="info-box-label">Service Fee</div>
            </div>
            <div class="info-box">
                <div class="info-box-icon"><i class="fas fa-bolt"></i></div>
                <div class="info-box-value">~1 Min</div>
                <div class="info-box-label">Processing</div>
            </div>
        </div>

        <div class="fee-card">
            <h3><i class="fas fa-calculator"></i> Fee Calculator</h3>
            <div class="fee-row">
                <span>You Request</span>
                <span id="calc-requested">ZMW 0.00</span>
            </div>
            <div class="fee-row">
                <span>Service Fee (8%)</span>
                <span id="calc-fee" style="color:#f87171;">- ZMW 0.00</span>
            </div>
            <div class="fee-row net">
                <span>You Receive</span>
                <span id="calc-net">ZMW 0.00</span>
            </div>
        </div>

        <div class="form-card <?php echo !$serviceOpen ? 'form-disabled' : ''; ?>">
            <h3><i class="fas fa-money-bill-wave"></i> Request Withdrawal</h3>
            <form method="POST" id="withdrawForm" onsubmit="return handleSubmit(this)">
                <div class="form-group">
                    <label><i class="fas fa-coins"></i> Amount (ZMW) — Minimum ZMW 60</label>
                    <input type="number" name="amount" id="withdrawAmount"
                           step="0.01" min="60"
                           max="<?php echo $available_balance; ?>"
                           placeholder="Enter withdrawal amount"
                           oninput="updateCalculator(this.value)"
                           <?php echo !$serviceOpen ? 'disabled' : ''; ?>
                           required>
                </div>
                <div class="note">
                    <i class="fas fa-info-circle"></i>
                    An <strong>8% service fee</strong> will be deducted.
                    Minimum withdrawal is <strong>ZMW 60</strong>.
                    Processing within <strong>1 minute</strong>.
                    Service hours: <strong>08:00 – 17:00 Lusaka time</strong>, Mon – Sun.
                </div>
                <button type="submit" id="submitBtn" class="submit-btn" <?php echo !$serviceOpen ? 'disabled' : ''; ?>>
                    <i class="fas fa-paper-plane"></i>
                    <?php echo $serviceOpen ? 'Confirm Withdrawal' : 'Service Currently Closed'; ?>
                </button>
            </form>
        </div>

        <div class="history-card">
            <h3><i class="fas fa-history"></i> Withdrawal History</h3>
            <?php if ($history_result && mysqli_num_rows($history_result) > 0): ?>
                <?php while ($row = mysqli_fetch_assoc($history_result)):
                    $row_fee = ($row['amount'] * 8) / 100;
                    $row_net = $row['amount'] - $row_fee;
                ?>
                <div class="history-item <?php echo htmlspecialchars($row['status']); ?>">
                    <div class="history-header">
                        <div>
                            <div class="history-amount">ZMW <?php echo number_format($row['amount'], 2); ?></div>
                            <div class="history-fee">
                                Fee: ZMW <?php echo number_format($row_fee, 2); ?> &nbsp;|&nbsp;
                                You receive: <span style="color:#4ade80;">ZMW <?php echo number_format($row_net, 2); ?></span>
                            </div>
                        </div>
                        <span class="status status-<?php echo htmlspecialchars($row['status']); ?>">
                            <?php echo strtoupper(htmlspecialchars($row['status'])); ?>
                        </span>
                    </div>
                    <div class="history-date">
                        <i class="fas fa-clock"></i> <?php echo date('M d, Y h:i A', strtotime($row['created_at'])); ?>
                    </div>
                </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="no-history">
                    <i class="fas fa-inbox" style="font-size:40px;opacity:0.3;display:block;margin-bottom:10px;"></i>
                    No withdrawal history yet
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        var submitting = false;

        function handleSubmit(form) {
            if (submitting) return false; // block double-submit
            submitting = true;
            var btn = document.getElementById('submitBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing…';
            return true;
        }

        function updateCalculator(value) {
            const amount = parseFloat(value) || 0;
            const fee    = amount * 0.08;
            const net    = amount - fee;
            document.getElementById('calc-requested').textContent = 'ZMW ' + amount.toFixed(2);
            document.getElementById('calc-fee').textContent       = '- ZMW ' + fee.toFixed(2);
            document.getElementById('calc-net').textContent       = 'ZMW ' + net.toFixed(2);
        }

        setTimeout(function() {
            document.querySelectorAll('.message').forEach(function(m) {
                m.style.transition = 'opacity .5s'; m.style.opacity = '0';
                setTimeout(function() { m.remove(); }, 500);
            });
        }, 6000);
    </script>
    <?php include 'bottom-nav.php'; ?>
</body>
</html>
<?php if (isset($stmt)) mysqli_stmt_close($stmt); mysqli_close($conn); ?>