<?php
require_once '../includes/config.php';
require_once '../includes/telegram.php';
requireAdmin();
$db = getDB();

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id     = intval($_POST['txn_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    $note   = sanitize($_POST['note'] ?? '');

    $txn = $db->prepare("SELECT t.*, u.name as uname, u.balance FROM transactions t JOIN users u ON t.user_id=u.id WHERE t.id=?");
    $txn->execute([$id]);
    $t = $txn->fetch();

    if ($t && in_array($t['status'], ['pending','processing'])) {
        if ($action === 'success') {
            $db->prepare("UPDATE transactions SET status='success', note=?, updated_at=NOW() WHERE id=?")->execute([$note ?: 'Completed by admin', $id]);
            require_once '../includes/commission.php';
            applyCommission($db, $t['user_id'], $t['type'], $t['amount'], $t['reference']);
            $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$t['user_id'],'✅ Transaction Successful!','Ref: '.$t['reference'].' — '.CURRENCY.number_format($t['amount'],2)]);
            $_SESSION['flash'] = ['ok'=>true,'msg'=>'✅ Approved!'];

        } elseif ($action === 'processing') {
            $db->prepare("UPDATE transactions SET status='processing', note=?, updated_at=NOW() WHERE id=?")->execute([$note ?: 'Processing', $id]);
            $_SESSION['flash'] = ['ok'=>true,'msg'=>'🔄 Processing!'];

        } elseif ($action === 'failed') {
            $db->beginTransaction();
            try {
                $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$t['amount'],$t['user_id']]);
                $newBal = $t['balance'] + $t['amount'];
                $db->prepare("UPDATE transactions SET status='refunded', note=?, balance_after=?, updated_at=NOW() WHERE id=?")->execute([$note ?: 'Rejected & refunded', $newBal, $id]);
                $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")->execute([$t['user_id'],'refund',$t['amount'],$t['amount'],$t['balance'],$newBal,'RF-'.$t['reference'],'success','Refund: '.$t['reference']]);
                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'warning')")->execute([$t['user_id'],'↩️ Refunded',CURRENCY.number_format($t['amount'],2).' refunded to your balance.']);
                $db->commit();
                $_SESSION['flash'] = ['ok'=>true,'msg'=>'❌ Rejected & '.CURRENCY.number_format($t['amount'],2).' refunded!'];
            } catch(Exception $e) { $db->rollBack(); $_SESSION['flash'] = ['ok'=>false,'msg'=>'Error: '.$e->getMessage()]; }
        }
    }
    header('Location: transactions.php?'.http_build_query(array_filter($_GET))); exit;
}

$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);

// Filters
$status    = $_GET['status']   ?? 'all';
$search    = sanitize($_GET['search']   ?? '');
$type      = sanitize($_GET['type']     ?? '');
$dateFrom  = sanitize($_GET['date_from']?? '');
$dateTo    = sanitize($_GET['date_to']  ?? '');
$userId    = intval($_GET['user_id']    ?? 0);

$where  = "WHERE 1=1";
$params = [];

if ($status !== 'all')  { $where .= " AND t.status=?";     $params[] = $status; }
if ($type)              { $where .= " AND t.type=?";        $params[] = $type; }
if ($dateFrom)          { $where .= " AND DATE(t.created_at)>=?"; $params[] = $dateFrom; }
if ($dateTo)            { $where .= " AND DATE(t.created_at)<=?"; $params[] = $dateTo; }
if ($userId)            { $where .= " AND t.user_id=?";     $params[] = $userId; }
if ($search) {
    $where .= " AND (u.name LIKE ? OR u.username LIKE ? OR t.phone_number LIKE ? OR t.reference LIKE ?)";
    $s = "%$search%"; $params = array_merge($params,[$s,$s,$s,$s]);
}

$txns = $db->prepare("SELECT t.*, u.name as uname, u.username, u.balance, o.name as op_name
    FROM transactions t JOIN users u ON t.user_id=u.id LEFT JOIN operators o ON t.operator_id=o.id
    $where ORDER BY t.created_at DESC LIMIT 200");
$txns->execute($params);
$transactions = $txns->fetchAll();

// Summary for filtered results
$sumStmt = $db->prepare("SELECT COUNT(*) as cnt, COALESCE(SUM(t.amount),0) as total FROM transactions t JOIN users u ON t.user_id=u.id $where");
$sumStmt->execute($params);
$summary = $sumStmt->fetch();

// Counts
$counts = [];
foreach (['pending','processing','success','refunded','failed','all'] as $s) {
    $w = $s === 'all' ? "WHERE 1=1" : "WHERE status='$s'";
    $counts[$s] = $db->query("SELECT COUNT(*) FROM transactions $w")->fetchColumn();
}

// Users for dropdown
$users = $db->query("SELECT id, name, username FROM users WHERE role='user' ORDER BY name LIMIT 100")->fetchAll();

// Type icons/colors
$typeMap = [
    'topup'       => ['emoji'=>'📱','color'=>'#1a3c8f','bg'=>'#eef2ff','label'=>'Topup'],
    'drive'       => ['emoji'=>'⚡','color'=>'#d69e2e','bg'=>'#fffff0','label'=>'Drive'],
    'deposit'     => ['emoji'=>'💰','color'=>'#38a169','bg'=>'#f0fff4','label'=>'Deposit'],
    'refund'      => ['emoji'=>'↩️','color'=>'#805ad5','bg'=>'#faf5ff','label'=>'Refund'],
    'commission'  => ['emoji'=>'💸','color'=>'#319795','bg'=>'#e6fffa','label'=>'Commission'],
    'international'=>['emoji'=>'🌍','color'=>'#2b6cb0','bg'=>'#ebf8ff','label'=>'Intl'],
    'pin'         => ['emoji'=>'🔑','color'=>'#c05621','bg'=>'#fffaf0','label'=>'PIN'],
    'gift'        => ['emoji'=>'🎁','color'=>'#e53e3e','bg'=>'#fff5f5','label'=>'Gift'],
    'card'        => ['emoji'=>'📞','color'=>'#276749','bg'=>'#f0fff4','label'=>'Card'],
    'package_fee' => ['emoji'=>'🎯','color'=>'#805ad5','bg'=>'#faf5ff','label'=>'Package'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>All Transactions - Admin</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.stats-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:10px;margin-bottom:16px}
.stat-box{background:white;border-radius:10px;padding:12px;text-align:center;box-shadow:0 2px 6px rgba(0,0,0,0.05);border-top:3px solid #e8ecf4;cursor:pointer;text-decoration:none;display:block;transition:0.15s}
.stat-box:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,0.1)}
.stat-box.active-stat{border-top-color:var(--primary);background:#f0f4ff}
.stat-box.yellow{border-top-color:#d69e2e}.stat-box.blue{border-top-color:#3182ce}.stat-box.green{border-top-color:#38a169}.stat-box.red{border-top-color:#e53e3e}.stat-box.purple{border-top-color:#805ad5}
.stat-num{font-size:18px;font-weight:800;color:var(--dark)}.stat-lbl{font-size:10px;color:#888;font-weight:600;margin-top:1px}
.filter-card{background:white;border-radius:12px;padding:16px;box-shadow:0 2px 8px rgba(0,0,0,0.05);margin-bottom:16px}
.filter-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px}
.fg{display:flex;flex-direction:column;gap:4px}
.fg label{font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:0.4px}
.fg input,.fg select{padding:9px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none}
.fg input:focus,.fg select:focus{border-color:var(--primary)}
.filter-actions{display:flex;gap:8px;margin-top:10px;align-items:center}
.btn-filter{padding:10px 18px;background:var(--primary);color:white;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:6px}
.btn-clear{padding:10px 14px;background:#f5f5f5;color:#666;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;text-decoration:none;display:flex;align-items:center;gap:5px}
.summary-bar{display:flex;gap:12px;flex-wrap:wrap;padding:10px 14px;background:#f0f4ff;border-radius:10px;margin-bottom:14px;font-size:13px;font-weight:600;color:var(--dark);align-items:center}
.alert{padding:10px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:12px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
/* Transaction cards */
.txn-card{background:white;border-radius:12px;margin-bottom:8px;box-shadow:0 1px 6px rgba(0,0,0,0.06);overflow:hidden;border-left:4px solid #e8ecf4}
.txn-card.pending{border-left-color:#d69e2e}.txn-card.processing{border-left-color:#3182ce}.txn-card.success{border-left-color:#38a169}.txn-card.refunded{border-left-color:#805ad5}.txn-card.failed{border-left-color:#e53e3e}
.txn-head{display:flex;align-items:center;gap:12px;padding:12px 14px;cursor:pointer;user-select:none}
.txn-head:hover{background:#fafafa}
.txn-ic{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:17px;flex-shrink:0}
.txn-info{flex:1;min-width:0}
.txn-title{font-size:13px;font-weight:700;color:#222}
.txn-sub{font-size:11px;color:#aaa;margin-top:1px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.txn-right{text-align:right;flex-shrink:0}
.txn-amt{font-size:15px;font-weight:800}
.txn-amt.plus{color:#38a169}.txn-amt.minus{color:#e53e3e}.txn-amt.neutral{color:#805ad5}
.txn-badge{font-size:10px;font-weight:700;padding:2px 8px;border-radius:20px;display:inline-block;margin-top:2px}
.b-pending{background:#fffaf0;color:#d69e2e}.b-processing{background:#ebf8ff;color:#3182ce}.b-success{background:#f0fff4;color:#38a169}.b-refunded{background:#faf5ff;color:#805ad5}.b-failed{background:#fff5f5;color:#e53e3e}
.txn-detail{display:none;padding:14px;border-top:1px solid #f5f5f5;background:#fafafa}
.txn-detail.show{display:block}
.dg{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:8px;margin-bottom:12px}
.dg-item{background:white;border-radius:9px;padding:9px 11px;box-shadow:0 1px 4px rgba(0,0,0,0.05)}
.dg-lbl{font-size:10px;color:#aaa;font-weight:700;text-transform:uppercase;margin-bottom:2px}
.dg-val{font-size:13px;font-weight:700;color:#333}
.act-row{display:flex;gap:7px;flex-wrap:wrap}
.note-in{width:100%;padding:8px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;margin-bottom:8px}
.note-in:focus{border-color:var(--primary)}
.btn{padding:8px 14px;border:none;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px}
.btn-ok{background:#38a169;color:white}.btn-pr{background:#3182ce;color:white}.btn-fail{background:#e53e3e;color:white}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">💳 All Transactions</span>
    </div>
    <div class="topbar-right" style="display:flex;gap:8px;font-size:12px">
        <span style="background:#fffaf0;color:#d69e2e;padding:5px 10px;border-radius:20px;font-weight:700">⏳ <?= $counts['pending'] ?></span>
        <span style="background:#ebf8ff;color:#3182ce;padding:5px 10px;border-radius:20px;font-weight:700">🔄 <?= $counts['processing'] ?></span>
    </div>
</div>
<div class="content">

<?php if($flash): ?>
<div class="alert <?= $flash['ok']?'alert-ok':'alert-err' ?>"><?= $flash['ok']?'✅':'❌' ?> <?= htmlspecialchars($flash['msg']) ?></div>
<?php endif; ?>

<!-- Stats -->
<div class="stats-grid">
    <?php
    $statDefs = ['all'=>['lbl'=>'All','cls'=>''],'pending'=>['lbl'=>'⏳ Pending','cls'=>'yellow'],'processing'=>['lbl'=>'🔄 Processing','cls'=>'blue'],'success'=>['lbl'=>'✅ Success','cls'=>'green'],'refunded'=>['lbl'=>'↩️ Refunded','cls'=>'purple'],'failed'=>['lbl'=>'❌ Failed','cls'=>'red']];
    foreach($statDefs as $s=>$d): ?>
    <a href="?status=<?= $s ?>&type=<?= urlencode($type) ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($dateFrom) ?>&date_to=<?= urlencode($dateTo) ?>&user_id=<?= $userId ?>"
       class="stat-box <?= $d['cls'] ?> <?= $status===$s?'active-stat':'' ?>">
        <div class="stat-num"><?= $counts[$s] ?></div>
        <div class="stat-lbl"><?= $d['lbl'] ?></div>
    </a>
    <?php endforeach; ?>
</div>

<!-- Filters -->
<div class="filter-card">
    <form method="GET" id="filterForm">
        <input type="hidden" name="status" value="<?= $status ?>">
        <div class="filter-grid">
            <div class="fg" style="grid-column:1/-1">
                <label>🔍 Search</label>
                <input type="text" name="search" placeholder="Name / Phone / Reference..." value="<?= htmlspecialchars($search) ?>">
            </div>
            <div class="fg">
                <label>👤 User</label>
                <select name="user_id">
                    <option value="">All Users</option>
                    <?php foreach($users as $u): ?>
                    <option value="<?= $u['id'] ?>" <?= $userId==$u['id']?'selected':'' ?>><?= htmlspecialchars($u['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fg">
                <label>📂 Type</label>
                <select name="type">
                    <option value="">All Types</option>
                    <?php foreach(array_keys($typeMap) as $t): ?>
                    <option value="<?= $t ?>" <?= $type===$t?'selected':'' ?>><?= $typeMap[$t]['emoji'].' '.ucfirst($t) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fg">
                <label>📅 From Date</label>
                <input type="date" name="date_from" value="<?= $dateFrom ?>">
            </div>
            <div class="fg">
                <label>📅 To Date</label>
                <input type="date" name="date_to" value="<?= $dateTo ?>">
            </div>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn-filter"><i class="fas fa-search"></i> Filter</button>
            <a href="transactions.php" class="btn-clear"><i class="fas fa-times"></i> Clear</a>
            <span style="font-size:12px;color:#888;margin-left:4px">
                <?= number_format($summary['cnt']) ?> results · <?= CURRENCY ?><?= number_format($summary['total'],2) ?>
            </span>
        </div>
    </form>
</div>

<!-- Summary bar if filtered -->
<?php if($search||$type||$dateFrom||$dateTo||$userId): ?>
<div class="summary-bar">
    <span><i class="fas fa-filter" style="color:var(--primary)"></i> Active filters:</span>
    <?php if($search): ?><span style="background:white;padding:3px 10px;border-radius:20px">🔍 "<?= htmlspecialchars($search) ?>"</span><?php endif; ?>
    <?php if($type): ?><span style="background:white;padding:3px 10px;border-radius:20px"><?= $typeMap[$type]['emoji']??'' ?> <?= ucfirst($type) ?></span><?php endif; ?>
    <?php if($dateFrom||$dateTo): ?><span style="background:white;padding:3px 10px;border-radius:20px">📅 <?= $dateFrom ?: '...' ?> → <?= $dateTo ?: '...' ?></span><?php endif; ?>
    <?php if($userId): ?><span style="background:white;padding:3px 10px;border-radius:20px">👤 User #<?= $userId ?></span><?php endif; ?>
    <span style="margin-left:auto;color:var(--primary)"><?= number_format($summary['cnt']) ?> results · <?= CURRENCY ?><?= number_format($summary['total'],2) ?></span>
</div>
<?php endif; ?>

<!-- Transaction List -->
<?php if(empty($transactions)): ?>
<div style="text-align:center;padding:50px;color:#aaa;background:white;border-radius:12px">
    <i class="fas fa-inbox" style="font-size:36px;display:block;margin-bottom:12px"></i>No transactions found
</div>
<?php else: ?>
<?php foreach($transactions as $r):
    $tm = $typeMap[$r['type']] ?? ['emoji'=>'💳','color'=>'#718096','bg'=>'#f5f5f5','label'=>ucfirst($r['type'])];
    $isPlus = in_array($r['type'],['deposit','commission','refund']);
    $canAct = in_array($r['status'],['pending','processing']);
?>
<div class="txn-card <?= $r['status'] ?>">
    <div class="txn-head" onclick="toggleTxn(<?= $r['id'] ?>)">
        <div class="txn-ic" style="background:<?= $tm['bg'] ?>;color:<?= $tm['color'] ?>"><?= $tm['emoji'] ?></div>
        <div class="txn-info">
            <div class="txn-title">
                <?= $tm['emoji'] ?> <?= $tm['label'] ?>
                <?php if($r['op_name']): ?> — <?= htmlspecialchars($r['op_name']) ?><?php endif; ?>
                <span style="font-size:11px;color:#aaa;font-weight:500;margin-left:6px"><?= htmlspecialchars($r['uname']) ?></span>
            </div>
            <div class="txn-sub">
                <?= $r['phone_number'] ? $r['phone_number'].' · ' : '' ?>
                <?= $r['reference'] ?> · <?= date('d M y, h:i A',strtotime($r['created_at'])) ?>
            </div>
        </div>
        <div class="txn-right">
            <div class="txn-amt <?= $isPlus?'plus':($r['type']==='refund'?'neutral':'minus') ?>">
                <?= $isPlus?'+':'-' ?><?= CURRENCY ?><?= number_format($r['amount'],2) ?>
            </div>
            <span class="txn-badge b-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span>
        </div>
        <i class="fas fa-chevron-down" id="ch<?= $r['id'] ?>" style="color:#ddd;font-size:11px;margin-left:6px;transition:0.2s;flex-shrink:0"></i>
    </div>

    <div class="txn-detail" id="det<?= $r['id'] ?>">
        <div class="dg">
            <div class="dg-item"><div class="dg-lbl">User</div><div class="dg-val"><?= htmlspecialchars($r['uname']) ?><br><span style="font-size:10px;color:#aaa">@<?= $r['username'] ?></span></div></div>
            <div class="dg-item"><div class="dg-lbl">Amount</div><div class="dg-val" style="color:<?= $isPlus?'#38a169':'#e53e3e' ?>"><?= $isPlus?'+':'-' ?><?= CURRENCY ?><?= number_format($r['amount'],2) ?></div></div>
            <?php if($r['phone_number']): ?>
            <div class="dg-item"><div class="dg-lbl">Phone</div><div class="dg-val" style="font-family:monospace"><?= $r['phone_number'] ?></div></div>
            <?php endif; ?>
            <?php if($r['op_name']): ?>
            <div class="dg-item"><div class="dg-lbl">Operator</div><div class="dg-val"><?= htmlspecialchars($r['op_name']) ?></div></div>
            <?php endif; ?>
            <div class="dg-item"><div class="dg-lbl">Bal Before</div><div class="dg-val"><?= CURRENCY ?><?= number_format($r['balance_before'],2) ?></div></div>
            <div class="dg-item"><div class="dg-lbl">Bal After</div><div class="dg-val"><?= CURRENCY ?><?= number_format($r['balance_after'],2) ?></div></div>
            <div class="dg-item"><div class="dg-lbl">Date</div><div class="dg-val"><?= date('d M Y, h:i A',strtotime($r['created_at'])) ?></div></div>
            <div class="dg-item" style="grid-column:1/-1"><div class="dg-lbl">Reference</div><div class="dg-val" style="font-family:monospace"><?= $r['reference'] ?></div></div>
            <?php if($r['note']): ?>
            <div class="dg-item" style="grid-column:1/-1"><div class="dg-lbl">Note</div><div class="dg-val" style="font-size:12px;color:#555"><?= htmlspecialchars($r['note']) ?></div></div>
            <?php endif; ?>
        </div>

        <?php if($canAct): ?>
        <form method="POST" id="f<?= $r['id'] ?>">
            <input type="hidden" name="txn_id" value="<?= $r['id'] ?>">
            <input type="hidden" name="action" id="a<?= $r['id'] ?>">
            <input type="text" name="note" class="note-in" placeholder="Note (optional)...">
            <div class="act-row">
                <?php if($r['status']==='pending'): ?>
                <button type="button" class="btn btn-pr" onclick="doAct(<?= $r['id'] ?>,'processing')"><i class="fas fa-clock"></i> Processing</button>
                <?php endif; ?>
                <button type="button" class="btn btn-ok" onclick="doAct(<?= $r['id'] ?>,'success')"><i class="fas fa-check"></i> ✅ Approve</button>
                <button type="button" class="btn btn-fail" onclick="doAct(<?= $r['id'] ?>,'failed')"><i class="fas fa-times"></i> ❌ Refund</button>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>

</div>
</div>

<script>
function toggleTxn(id) {
    const det = document.getElementById('det'+id);
    const ch  = document.getElementById('ch'+id);
    const show = det.classList.toggle('show');
    ch.style.transform = show ? 'rotate(180deg)' : '';
}
function doAct(id, action) {
    const labels = {success:'✅ Approve?', processing:'🔄 Processing?', failed:'❌ Reject & Refund?'};
    if (!confirm(labels[action])) return;
    document.getElementById('a'+id).value = action;
    document.getElementById('f'+id).submit();
}
// Auto expand pending
document.querySelectorAll('.txn-card.pending').forEach(c => {
    const id = c.querySelector('[id^="det"]')?.id?.replace('det','');
    if(id) { document.getElementById('det'+id)?.classList.add('show'); const ch=document.getElementById('ch'+id); if(ch) ch.style.transform='rotate(180deg)'; }
});
</script>
</body>
</html>
