<?php
include('header.php');
$page_title  = WEB_NAME . " | Withdrawal History";
$page_title2 = "Withdrawal History";
$current_page = 'withdrawal-history';

// Auto-sync pending withdrawals with Paystack
$paystack_secret = trim($site_data['paystack_secret_key'] ?? '');
if (!empty($paystack_secret)) {
    try {
        $pending = $pdo->prepare("SELECT id, transaction_ref FROM transactions WHERE user_id = :uid AND payment_gateway = 'paystack_transfer' AND status = 'pending'");
        $pending->execute(['uid' => $user['id']]);
        $pending_txns = $pending->fetchAll(PDO::FETCH_ASSOC);

        foreach ($pending_txns as $ptxn) {
            $ch = curl_init('https://api.paystack.co/transfer/verify/' . urlencode($ptxn['transaction_ref']));
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $paystack_secret],
                CURLOPT_TIMEOUT        => 5,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => 0,
            ]);
            $resp = curl_exec($ch);
            curl_close($ch);
            $res = json_decode($resp, true);
            if ($res && $res['status'] === true && !empty($res['data']['status'])) {
                $ps = strtolower($res['data']['status']);
                if ($ps === 'success') {
                    $pdo->prepare("UPDATE transactions SET status = 'successful' WHERE id = :id")->execute(['id' => $ptxn['id']]);
                } elseif ($ps === 'failed' || $ps === 'reversed') {
                    $pdo->prepare("UPDATE transactions SET status = 'failed' WHERE id = :id")->execute(['id' => $ptxn['id']]);
                    // Refund
                    $t = $pdo->prepare("SELECT amount, metadata FROM transactions WHERE id = :id");
                    $t->execute(['id' => $ptxn['id']]);
                    $tr = $t->fetch(PDO::FETCH_ASSOC);
                    if ($tr) {
                        $meta = json_decode($tr['metadata'] ?? '{}', true);
                        $refund = (float)$tr['amount'] + floatval($meta['fee'] ?? 0);
                        $pdo->prepare("UPDATE users SET main_balance = main_balance + :amt WHERE id = :uid")->execute(['amt' => $refund, 'uid' => $user['id']]);
                    }
                }
            }
        }
    } catch (Exception $e) {}
}

try {
    $stmt = $pdo->prepare(
        "SELECT * FROM transactions WHERE user_id = :uid AND (transaction_type = 'withdrawal' OR payment_gateway = 'paystack_transfer') ORDER BY created_at DESC"
    );
    $stmt->execute(['uid' => $user['id']]);
    $withdrawals = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $withdrawals = []; }

$total_withdrawn = 0;
$pending_count = 0;
$successful_count = 0;
foreach ($withdrawals as $w) {
    if ($w['status'] === 'successful') { $total_withdrawn += (float)$w['amount']; $successful_count++; }
    if ($w['status'] === 'pending') $pending_count++;
}
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}
.wh-hero{background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 40%,#4D148C 80%,#4D148C 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:14px}
.wh-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:14px;padding:14px;transition:border-color .2s;margin-bottom:8px}
.wh-card:hover{border-color:rgba(77,20,140,.2)}
.stat-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:12px;padding:12px;display:flex;align-items:center;gap:10px}
</style>

<div class="max-w-4xl mx-auto">

<!-- Hero -->
<div class="wh-hero anim anim-1">
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:14px;">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;margin-bottom:4px;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-money-bill-transfer text-emerald-300 text-base"></i>Withdrawal History
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem;">Track all your bank withdrawals.</p>
        </div>
        <a href="withdraw" style="background:white;color:#4D148C;font-weight:700;font-size:.78rem;padding:10px 16px;border-radius:10px;text-decoration:none;display:inline-flex;align-items:center;gap:6px;">
            <i class="fas fa-plus text-xs"></i>New Withdrawal
        </a>
    </div>
</div>

<!-- Stats -->
<div class="anim anim-1" style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px;">
    <div class="stat-card">
        <div style="width:36px;height:36px;border-radius:9px;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas fa-list" style="font-size:.85rem;color:#4D148C;"></i>
        </div>
        <div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:500;">Total</p>
            <p style="font-weight:800;font-size:.95rem;color:var(--text-primary);"><?php echo count($withdrawals); ?></p>
        </div>
    </div>
    <div class="stat-card">
        <div style="width:36px;height:36px;border-radius:9px;background:rgba(16,185,129,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas fa-circle-check" style="font-size:.85rem;color:#059669;"></i>
        </div>
        <div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:500;">Successful</p>
            <p style="font-weight:800;font-size:.95rem;color:var(--text-primary);"><?php echo $successful_count; ?></p>
        </div>
    </div>
    <div class="stat-card">
        <div style="width:36px;height:36px;border-radius:9px;background:rgba(59,130,246,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas fa-naira-sign" style="font-size:.85rem;color:#2563eb;"></i>
        </div>
        <div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:500;">Withdrawn</p>
            <p style="font-weight:800;font-size:.85rem;color:var(--text-primary);font-family:monospace;">&#8358;<?php echo number_format($total_withdrawn, 2); ?></p>
        </div>
    </div>
</div>

<!-- Withdrawal List -->
<?php if (!empty($withdrawals)): ?>
<div class="anim anim-3">
    <?php foreach ($withdrawals as $w):
        $meta = json_decode($w['metadata'] ?? '{}', true);
        $bank_name = '';
        if (!empty($meta['bank'])) {
            $bank_name = $meta['bank'];
        }
        $acct = $meta['account'] ?? '';
        $name = $meta['name'] ?? '';
        $fee  = $meta['fee'] ?? 0;

        if ($w['status'] === 'successful') { $bc='rgba(16,185,129,.08)'; $tc='#059669'; $ic='fa-circle-check'; $sl='Successful'; }
        elseif ($w['status'] === 'pending') { $bc='rgba(245,158,11,.08)'; $tc='#d97706'; $ic='fa-clock'; $sl='Pending'; }
        else { $bc='rgba(239,68,68,.08)'; $tc='#dc2626'; $ic='fa-times-circle'; $sl='Failed'; }
    ?>
    <div class="wh-card">
        <div style="display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;">
            <div style="flex:1;min-width:0;">
                <div style="display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:6px;">
                    <span style="font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:99px;background:<?php echo $bc; ?>;color:<?php echo $tc; ?>;display:flex;align-items:center;gap:4px;">
                        <i class="fas <?php echo $ic; ?>" style="font-size:.55rem;"></i><?php echo $sl; ?>
                    </span>
                    <span style="font-size:.65rem;color:var(--text-muted);font-family:monospace;"><?php echo htmlspecialchars($w['transaction_ref']); ?></span>
                </div>
                <p style="font-weight:600;font-size:.82rem;color:var(--text-primary);margin-bottom:3px;">
                    <?php echo htmlspecialchars($name ?: 'Bank Transfer'); ?>
                </p>
                <p style="font-size:.72rem;color:var(--text-muted);">
                    <?php echo htmlspecialchars($acct); ?> &bull; <?php echo htmlspecialchars($bank_name); ?>
                </p>
            </div>
            <div style="text-align:right;flex-shrink:0;">
                <p style="font-weight:800;font-size:1rem;color:#dc2626;font-family:monospace;">-&#8358;<?php echo number_format((float)$w['amount'], 2); ?></p>
                <?php if ($fee > 0): ?>
                <p style="font-size:.65rem;color:var(--text-muted);">Fee: &#8358;<?php echo number_format((float)$fee, 2); ?></p>
                <?php endif; ?>
                <p style="font-size:.68rem;color:var(--text-muted);margin-top:3px;"><?php echo date('M d, Y h:i A', strtotime($w['created_at'])); ?></p>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="anim anim-3" style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:16px;padding:40px;text-align:center;">
    <div style="width:56px;height:56px;border-radius:50%;background:rgba(77,20,140,.07);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;">
        <i class="fas fa-money-bill-transfer" style="font-size:1.4rem;color:var(--text-muted);"></i>
    </div>
    <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:6px;">No Withdrawals Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto 16px;">You haven't made any withdrawals yet.</p>
    <a href="withdraw" style="display:inline-flex;align-items:center;gap:8px;padding:11px 22px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.82rem;border-radius:10px;text-decoration:none;">
        <i class="fas fa-money-bill-transfer"></i>Withdraw Now
    </a>
</div>
<?php endif; ?>

</div>

<?php include('footer.php'); ?>
