<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Withdrawal History';
include 'side.php';
$conn = getConnection();

/* ── BACKEND — UNCHANGED ─────────────────────────────── */
$userCountry = $userData['country'] ?? 'Kenya';
$stmt = $conn->prepare("SELECT * FROM countries WHERE name=? AND status='active'");
$stmt->bind_param("s", $userCountry); $stmt->execute();
$cs = $stmt->get_result()->fetch_assoc();
if (!$cs) $cs = ['currency_symbol' => 'KSh'];
$cSym = $cs['currency_symbol'] ?? 'KSh';

$stats = $conn->query("
    SELECT
        COUNT(*) as total,
        SUM(CASE WHEN status IN ('completed','approved') OR (hashback_status='SENT' AND status NOT IN ('pending','processing','rejected')) THEN 1 ELSE 0 END) as done,
        SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END) as pend,
        SUM(CASE WHEN status IN ('completed','approved') OR (hashback_status='SENT' AND status NOT IN ('pending','processing','rejected')) THEN net_amount ELSE 0 END) as earned
    FROM withdrawals WHERE user_id={$userId}
")->fetch_assoc();

$stmt = $conn->prepare("SELECT * FROM withdrawals WHERE user_id=? ORDER BY requested_at DESC LIMIT 50");
$stmt->bind_param("i", $userId); $stmt->execute();
$withdrawals = $stmt->get_result();
$rows = [];
while ($r = $withdrawals->fetch_assoc()) $rows[] = $r;

function resolveStatus(array $w): string {
    $st   = trim($w['status'] ?? '');
    $hbSt = trim($w['hashback_status'] ?? '');
    if ($st !== '') return $st;
    if ($hbSt === 'SENT') return 'completed';
    if ($hbSt === 'API_ERROR') return 'pending';
    return 'pending';
}

/* ── Group rows by month ─────────────────────────────── */
$grouped = [];
foreach ($rows as $r) {
    $mk = !empty($r['requested_at']) ? date('F Y', strtotime($r['requested_at'])) : 'Other';
    $grouped[$mk][] = $r;
}

$walletNames = [
    'referral'=>'Affiliate','main'=>'Main','bonus'=>'Bonus',
    'video'=>'Video','trivia'=>'Trivia','survey'=>'Survey',
    'ads'=>'Ads','spin'=>'Spin','blog'=>'Blog','meme'=>'Meme',
    'chat'=>'Chat','transcription'=>'Transcribe',
];
$walletColors = [
    'referral'=>'#8b5cf6','main'=>'#6366f1','bonus'=>'#10b981',
    'video'=>'#ef4444','trivia'=>'#a855f7','survey'=>'#06b6d4',
    'ads'=>'#8b5cf6','spin'=>'#14b8a6','blog'=>'#10b981',
    'meme'=>'#ec4899','chat'=>'#3b82f6','transcription'=>'#f97316',
];
$walletIcons = [
    'referral'=>'fa-sitemap','main'=>'fa-vault','bonus'=>'fa-coins',
    'video'=>'fa-film','trivia'=>'fa-bolt','survey'=>'fa-magnifying-glass-chart',
    'ads'=>'fa-tower-broadcast','spin'=>'fa-dharmachakra','blog'=>'fa-rss',
    'meme'=>'fa-masks-theater','chat'=>'fa-comments','transcription'=>'fa-wave-square',
];
?>
<style>
/* ══════════════════════════════════════════════════
   WITHDRAWAL HISTORY — Account Statement UI
   Concept: top hero balance, scrollable month
   accordion timeline, status color-coded rows.
   Completely different from original dark card list.
══════════════════════════════════════════════════ */
.wh { padding:14px 14px 90px; }
@media(max-width:480px){ .wh { padding:10px 10px 90px } }

/* ── HERO BALANCE BLOCK ── */
.wh-hero {
    border-radius:20px;padding:22px 20px 18px;
    margin-bottom:14px;position:relative;overflow:hidden;
    background:var(--card);border:1px solid var(--bdr);
    transition:background .25s;
}
/* Accent top line */
.wh-hero::before {
    content:'';position:absolute;top:0;left:0;right:0;height:3px;
    background:linear-gradient(90deg,var(--P),rgba(var(--Pr),.0));
}
.wh-hero-row {
    display:flex;align-items:flex-start;
    justify-content:space-between;gap:14px;flex-wrap:wrap;
}
.wh-hero-left {}
.wh-hero-eyebrow {
    font-size:9px;font-weight:800;letter-spacing:2px;
    text-transform:uppercase;color:var(--txt2);
    margin-bottom:8px;display:flex;align-items:center;gap:7px;
}
.wh-hero-eyebrow::after {
    content:'';flex:0 0 18px;height:2px;
    background:var(--OK);border-radius:1px;
}
.wh-hero-num {
    font-size:36px;font-weight:900;color:var(--OK);
    letter-spacing:-2px;line-height:1;
    font-variant-numeric:tabular-nums;
}
.wh-hero-sub {
    margin-top:8px;font-size:11px;color:var(--txt2);
    display:flex;align-items:center;gap:10px;flex-wrap:wrap;
}
.wh-hero-sub b { color:var(--txt);font-weight:700 }

/* Right side — 3 mini stats */
.wh-mini {
    display:flex;flex-direction:column;gap:5px;
    min-width:110px;flex-shrink:0;
    padding:10px 14px;background:var(--bg3);
    border-radius:12px;border:1px solid var(--bdr);
}
@media(max-width:380px) {
    .wh-mini { flex-direction:row;flex-wrap:wrap;min-width:0;width:100%;padding:8px 10px }
}
.wh-ms {
    display:flex;justify-content:space-between;align-items:center;gap:8px;
}
.wh-ms-k { font-size:10px;color:var(--txt2);font-weight:600 }
.wh-ms-v {
    font-size:11px;font-weight:800;
    font-variant-numeric:tabular-nums;
}
.wh-ms-v.ok  { color:var(--OK) }
.wh-ms-v.wn  { color:var(--WN) }
.wh-ms-v.p   { color:var(--P) }
.wh-ms-div   { height:1px;background:var(--bdr) }

/* ── TOOLBAR ── */
.wh-toolbar {
    display:flex;align-items:center;gap:7px;
    margin-bottom:14px;flex-wrap:wrap;
}
.wh-new {
    display:flex;align-items:center;gap:6px;
    padding:8px 15px;border-radius:9px;
    background:var(--P);color:#fff;
    font-size:12px;font-weight:700;text-decoration:none;
    transition:.15s;white-space:nowrap;
}
.wh-new:hover { filter:brightness(1.1);color:#fff }
.wh-toolbar-r { margin-left:auto;font-size:11px;color:var(--txt2) }

/* ── MONTH ACCORDION SECTIONS ── */
.wh-month {
    margin-bottom:6px;
    border-radius:14px;overflow:hidden;
    background:var(--card);border:1px solid var(--bdr);
    transition:background .25s,border-color .25s;
}
.wh-month-hdr {
    display:flex;align-items:center;gap:10px;
    padding:11px 15px;cursor:pointer;
    transition:background .12s;
    user-select:none;
}
.wh-month-hdr:hover { background:var(--P-bg) }
.wh-month-dot {
    width:8px;height:8px;border-radius:50%;
    background:var(--P);flex-shrink:0;
}
.wh-month-lbl {
    font-size:12px;font-weight:800;color:var(--txt);flex:1;
    letter-spacing:-.2px;
}
.wh-month-sum {
    font-size:12px;font-weight:700;color:var(--OK);
    font-variant-numeric:tabular-nums;flex-shrink:0;
}
.wh-month-count {
    font-size:10px;color:var(--txt2);
    background:var(--bg3);border:1px solid var(--bdr);
    padding:2px 8px;border-radius:10px;flex-shrink:0;
}
.wh-month-arr {
    font-size:10px;color:var(--txt3);flex-shrink:0;
    transition:transform .2s;
}
.wh-month.closed .wh-month-arr { transform:rotate(-90deg) }
.wh-month-body { overflow:hidden }
.wh-month.closed .wh-month-body { display:none }
.wh-month-divider { height:1px;background:var(--bdr);margin:0 15px }

/* ── TRANSACTION ROW ── */
.wh-tx {
    display:flex;align-items:center;gap:12px;
    padding:12px 15px;
    border-top:1px solid var(--bdr);
    transition:background .12s;
    position:relative;
}
.wh-tx:first-child { border-top:none }
.wh-tx:hover { background:var(--P-bg) }

/* Status stripe — left edge */
.wh-tx::before {
    content:'';position:absolute;left:0;top:8px;bottom:8px;
    width:3px;border-radius:0 3px 3px 0;
}
.wh-tx.ok::before  { background:var(--OK) }
.wh-tx.pnd::before { background:var(--WN) }
.wh-tx.rej::before { background:var(--DN) }
.wh-tx.pro::before { background:var(--P) }

/* Wallet icon — square */
.wh-tx-ico {
    width:40px;height:40px;border-radius:11px;
    display:flex;align-items:center;justify-content:center;
    font-size:16px;color:#fff;flex-shrink:0;
}

/* Info */
.wh-tx-info { flex:1;min-width:0 }
.wh-tx-top {
    display:flex;align-items:center;gap:7px;
    margin-bottom:4px;flex-wrap:wrap;
}
.wh-tx-name {
    font-size:13px;font-weight:700;color:var(--txt);
}
.wh-tx-badge {
    font-size:9px;font-weight:800;padding:2px 7px;
    border-radius:20px;text-transform:uppercase;letter-spacing:.3px;
    flex-shrink:0;
}
.wh-tx-badge.ok  { background:var(--OK-bg);color:var(--OK) }
.wh-tx-badge.pnd { background:var(--WN-bg);color:var(--WN) }
.wh-tx-badge.rej { background:var(--DN-bg);color:var(--DN) }
.wh-tx-badge.pro { background:var(--P-bg); color:var(--P)  }
.wh-tx-instant {
    font-size:9px;font-weight:800;color:var(--OK);
    display:flex;align-items:center;gap:3px;flex-shrink:0;
}
.wh-tx-meta {
    font-size:10.5px;color:var(--txt2);
    display:flex;align-items:center;gap:9px;flex-wrap:wrap;
}
.wh-tx-meta span { display:flex;align-items:center;gap:3px }
.wh-tx-meta i    { font-size:8px;color:var(--txt3) }

/* Right amount */
.wh-tx-amt { text-align:right;flex-shrink:0 }
.wh-tx-net {
    font-size:15px;font-weight:900;
    font-variant-numeric:tabular-nums;letter-spacing:-.4px;line-height:1;
}
.wh-tx-net.ok  { color:var(--OK) }
.wh-tx-net.pnd { color:var(--WN) }
.wh-tx-net.rej { color:var(--DN) }
.wh-tx-gross {
    font-size:9.5px;color:var(--txt3);margin-top:3px;
    font-variant-numeric:tabular-nums;
}
.wh-tx-fee {
    font-size:9.5px;color:var(--DN);margin-top:1px;
    font-variant-numeric:tabular-nums;
}

/* Tx ref toggle */
.wh-tx-refbtn {
    background:none;border:none;padding:3px 0 0;
    font-size:9px;color:var(--P);font-weight:700;opacity:.8;
    cursor:pointer;font-family:inherit;
    display:flex;align-items:center;gap:3px;transition:.15s;
}
.wh-tx-refbtn:hover { opacity:1 }
.wh-tx-ref {
    display:none;margin:6px 15px 10px;
    padding:8px 11px;background:var(--bg3);
    border:1px solid var(--bdr);border-radius:8px;
    border-left:3px solid var(--P);
    font-family:monospace;font-size:9.5px;
    color:var(--txt2);word-break:break-all;line-height:1.6;
}
.wh-tx-ref.open { display:block }

/* Note boxes */
.wh-note {
    margin:0 15px 10px;padding:8px 11px;
    border-radius:8px;font-size:11px;line-height:1.55;
}
.wh-note.err { background:var(--DN-bg);color:var(--DN);border:1px solid rgba(239,68,68,.2) }
.wh-note.wn  { background:var(--WN-bg);color:var(--WN);border:1px solid rgba(245,158,11,.2) }

/* ── EMPTY ── */
.wh-empty {
    background:var(--card);border:1px solid var(--bdr);
    border-radius:14px;padding:50px 20px;text-align:center;
}
.wh-empty-ic {
    width:62px;height:62px;border-radius:18px;
    background:var(--bg3);border:1px solid var(--bdr);
    display:flex;align-items:center;justify-content:center;
    font-size:24px;color:var(--txt3);margin:0 auto 14px;
}
.wh-empty-t { font-size:16px;font-weight:700;color:var(--txt);margin-bottom:5px }
.wh-empty-s { font-size:12px;color:var(--txt2);line-height:1.6 }
.wh-empty-cta {
    display:inline-flex;align-items:center;gap:6px;
    margin-top:14px;padding:10px 20px;border-radius:10px;
    background:var(--P);color:#fff;font-size:12px;font-weight:700;
    text-decoration:none;transition:.15s;
}
.wh-empty-cta:hover { filter:brightness(1.1) }

@keyframes whIn { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:none} }
.wh-hero    { animation:whIn .32s ease both }
.wh-toolbar { animation:whIn .32s ease .05s both }
</style>

<div class="wh">

    <!-- ── HERO ── -->
    <div class="wh-hero">
        <div class="wh-hero-row">
            <div class="wh-hero-left">
                <div class="wh-hero-eyebrow">Total Paid Out</div>
                <div class="wh-hero-num"><?= $cSym.' '.number_format($stats['earned']??0,2) ?></div>
                <div class="wh-hero-sub">
                    <span><b><?= number_format($stats['done']??0) ?></b> completed</span>
                    <span>·</span>
                    <span><b><?= number_format($stats['total']??0) ?></b> total requests</span>
                </div>
            </div>
            <div class="wh-mini">
                <div class="wh-ms">
                    <span class="wh-ms-k">Completed</span>
                    <span class="wh-ms-v ok"><?= number_format($stats['done']??0) ?></span>
                </div>
                <div class="wh-ms-div"></div>
                <div class="wh-ms">
                    <span class="wh-ms-k">Pending</span>
                    <span class="wh-ms-v wn"><?= number_format($stats['pend']??0) ?></span>
                </div>
                <div class="wh-ms-div"></div>
                <div class="wh-ms">
                    <span class="wh-ms-k">All</span>
                    <span class="wh-ms-v p"><?= number_format($stats['total']??0) ?></span>
                </div>
            </div>
        </div>
    </div>

    <!-- ── TOOLBAR ── -->
    <div class="wh-toolbar">
        <a href="withdraw.php" class="wh-new">
            <i class="fa-solid fa-plus"></i> New Withdrawal
        </a>
        <span class="wh-toolbar-r"><?= count($rows) ?> record<?= count($rows)!==1?'s':'' ?> shown</span>
    </div>

    <!-- ── CONTENT ── -->
    <?php if(empty($rows)): ?>
    <div class="wh-empty">
        <div class="wh-empty-ic"><i class="fa-solid fa-receipt"></i></div>
        <div class="wh-empty-t">No withdrawals yet</div>
        <div class="wh-empty-s">Your withdrawal history will appear here once you make your first request.</div>
        <a href="withdraw.php" class="wh-empty-cta">
            <i class="fa-solid fa-paper-plane"></i> Make First Withdrawal
        </a>
    </div>

    <?php else:
        /* Status helpers */
        $stCls = ['completed'=>'ok','approved'=>'ok','pending'=>'pnd','processing'=>'pro','rejected'=>'rej'];
        $stLbl = ['completed'=>'Paid','approved'=>'Paid','pending'=>'Pending','processing'=>'Processing','rejected'=>'Rejected'];

        foreach($grouped as $month => $mRows):
            /* Month paid total — only completed/approved rows */
            $mPaid = array_sum(array_map(function($r){ $s=resolveStatus($r); return in_array($s,['completed','approved'])?floatval($r['net_amount']??0):0; }, $mRows));
            $isFirst = ($month === array_key_first($grouped));
    ?>
    <div class="wh-month <?= $isFirst?'':'closed' ?>" id="month_<?= md5($month) ?>">
        <div class="wh-month-hdr" onclick="toggleMonth('<?= md5($month) ?>')">
            <span class="wh-month-dot"></span>
            <span class="wh-month-lbl"><?= $month ?></span>
            <?php if($mPaid > 0): ?>
            <span class="wh-month-sum"><?= $cSym.' '.number_format($mPaid,2) ?></span>
            <?php endif; ?>
            <span class="wh-month-count"><?= count($mRows) ?></span>
            <i class="fa-solid fa-chevron-down wh-month-arr"></i>
        </div>
        <div class="wh-month-body">
        <?php foreach($mRows as $w):
            $st      = resolveStatus($w);
            $cls     = $stCls[$st]  ?? 'pnd';
            $lbl     = $stLbl[$st]  ?? ucfirst($st);
            $hbSt    = trim($w['hashback_status'] ?? '');
            $hbRef   = trim($w['hashback_reference'] ?? '');
            $isAuto  = ($hbSt==='SENT' && !empty($hbRef) && !in_array($st,['pending','rejected']));
            $wType   = trim($w['wallet_type'] ?? 'main');
            $wName   = $walletNames[$wType]  ?? ucfirst($wType);
            $wColor  = $walletColors[$wType] ?? '#6366f1';
            $wIcon   = $walletIcons[$wType]  ?? 'fa-wallet';
            $dStr    = !empty($w['requested_at']) ? date('M j · g:ia', strtotime($w['requested_at'])) : '—';
            $procDate= !empty($w['processed_at'])  ? date('M j', strtotime($w['processed_at'])) : null;
            $adminNote= trim($w['admin_note'] ?? '');
            $hbDesc  = trim($w['hashback_result_desc'] ?? '');
            $rid     = intval($w['id']);
        ?>
        <div class="wh-tx <?= $cls ?>">
            <!-- Wallet icon -->
            <div class="wh-tx-ico" style="background:<?= $wColor ?>1a;color:<?= $wColor ?>">
                <i class="fa-solid <?= $wIcon ?>"></i>
            </div>
            <!-- Info -->
            <div class="wh-tx-info">
                <div class="wh-tx-top">
                    <span class="wh-tx-name"><?= $wName ?> Wallet</span>
                    <span class="wh-tx-badge <?= $cls ?>">
                        <?= $lbl ?><?= $procDate?' · '.$procDate:'' ?>
                    </span>
                    <?php if($isAuto): ?>
                    <span class="wh-tx-instant"><i class="fa-solid fa-bolt" style="font-size:8px"></i> Instant</span>
                    <?php endif; ?>
                </div>
                <div class="wh-tx-meta">
                    <span><i class="fa-regular fa-clock"></i><?= $dStr ?></span>
                    <?php if(!empty($w['phone_number'])): ?>
                    <span><i class="fa-solid fa-sim-card"></i><?= htmlspecialchars($w['phone_number']) ?></span>
                    <?php endif; ?>
                    <span><i class="fa-solid fa-hashtag"></i><?= $rid ?></span>
                </div>
                <?php if(!empty($hbRef)): ?>
                <button class="wh-tx-refbtn" onclick="toggleRef(<?= $rid ?>)">
                    <i class="fa-solid fa-fingerprint"></i> Tx Ref
                </button>
                <?php endif; ?>
            </div>
            <!-- Amount -->
            <div class="wh-tx-amt">
                <div class="wh-tx-net <?= $cls ?>"><?= $cSym.' '.number_format($w['net_amount']??0,2) ?></div>
                <?php if(floatval($w['amount']??0) !== floatval($w['net_amount']??0)): ?>
                <div class="wh-tx-gross">Gross <?= $cSym.' '.number_format($w['amount']??0,2) ?></div>
                <?php endif; ?>
                <?php if(floatval($w['fee']??0) > 0): ?>
                <div class="wh-tx-fee">−<?= $cSym.' '.number_format($w['fee'],2) ?> fee</div>
                <?php endif; ?>
            </div>
        </div>
        <?php if(!empty($hbRef)): ?>
        <div class="wh-tx-ref" id="ref_<?= $rid ?>">
            <div style="font-size:9px;color:var(--txt3);font-weight:800;letter-spacing:.5px;margin-bottom:3px">TX REFERENCE</div>
            <?= htmlspecialchars($hbRef) ?>
        </div>
        <?php endif; ?>
        <?php if($st==='rejected' && !empty($adminNote)): ?>
        <div class="wh-note err"><i class="fa-solid fa-circle-info" style="font-size:9px;margin-right:4px"></i><?= htmlspecialchars($adminNote) ?></div>
        <?php elseif(!empty($hbDesc) && $st==='pending'): ?>
        <div class="wh-note wn"><i class="fa-solid fa-triangle-exclamation" style="font-size:9px;margin-right:4px"></i><?= htmlspecialchars($hbDesc) ?></div>
        <?php endif; ?>
        <?php endforeach; ?>
        </div><!-- /.wh-month-body -->
    </div>
    <?php endforeach; endif; ?>

</div><!-- /.wh -->

<script>
function toggleMonth(id) {
    const m = document.getElementById('month_' + id);
    if (m) m.classList.toggle('closed');
}
function toggleRef(id) {
    const el = document.getElementById('ref_' + id);
    if (el) el.classList.toggle('open');
}
</script>
<?php include 'footer.php'; ?>