<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require '../includes/db.php';
session_start();
if(!isset($_SESSION['admin_id'])){
    header("Location: login.php");
    exit;
}

$admin_name = $_SESSION['admin_name'];

$msg = "";
$error = "";

/* =========================
   APPROVE TRANSFER
========================= */
if(isset($_POST['approve_transfer'])){

    $id = (int)$_POST['id'];

    $stmt = $pdo->prepare("SELECT * FROM transfers WHERE id=?");
    $stmt->execute([$id]);
    $t = $stmt->fetch(PDO::FETCH_ASSOC);

    if($t && $t['status'] === 'pending'){

        $pdo->prepare("
            UPDATE transfers 
            SET status='approved', approved_at=NOW()
            WHERE id=?
        ")->execute([$id]);

        $msg = "Transfer approved";
    }

    header("Location: dashboard.php");
    exit;
}

/* =========================
   DECLINE TRANSFER + REFUND
========================= */
if(isset($_POST['decline_transfer'])){

    $id = (int)$_POST['id'];

    $stmt = $pdo->prepare("SELECT * FROM transfers WHERE id=?");
    $stmt->execute([$id]);
    $t = $stmt->fetch(PDO::FETCH_ASSOC);

    if($t && $t['status'] === 'pending'){

        // refund user
        $pdo->prepare("
            UPDATE users 
            SET checking_balance = checking_balance + ?
            WHERE id=?
        ")->execute([$t['amount'], $t['user_id']]);

        // mark declined
        $pdo->prepare("
            UPDATE transfers 
            SET status='declined', approved_at=NOW(), admin_note='Declined by admin'
            WHERE id=?
        ")->execute([$id]);

        $msg = "Transfer declined & refunded";
    }

    header("Location: dashboard.php");
    exit;
}

/* =========================
   APPROVE CRYPTO
========================= */
if(isset($_POST['approve_crypto'])){

    $id = (int)$_POST['id'];

    $pdo->prepare("
        UPDATE crypto_orders 
        SET status='approved', approved_at=NOW()
        WHERE id=?
    ")->execute([$id]);

    header("Location: dashboard.php");
    exit;
}

/* =========================
   DECLINE CRYPTO + REFUND
========================= */
if(isset($_POST['decline_crypto'])){

    $id = (int)$_POST['id'];

    $stmt = $pdo->prepare("SELECT * FROM crypto_orders WHERE id=?");
    $stmt->execute([$id]);
    $c = $stmt->fetch(PDO::FETCH_ASSOC);

    if($c && $c['status'] === 'pending'){

        $pdo->prepare("
            UPDATE users 
            SET checking_balance = checking_balance + ?
            WHERE id=?
        ")->execute([$c['amount '], $c['user_id']]);

        $pdo->prepare("
            UPDATE crypto_orders 
            SET status='declined', admin_note='Declined by admin'
            WHERE id=?
        ")->execute([$id]);
    }

    header("Location: dashboard.php");
    exit;
}

/* =========================
   DATA FETCH
========================= */
$users = $pdo->query("SELECT * FROM users ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

$transactions = $pdo->query("
    SELECT t.*, u.full_name 
    FROM transactions t 
    JOIN users u ON u.id = t.user_id 
    ORDER BY t.id DESC LIMIT 10
")->fetchAll(PDO::FETCH_ASSOC);

$total_users = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$total_balance = $pdo->query("SELECT SUM(checking_balance) FROM users")->fetchColumn();

/* PENDING SYSTEMS */
$pendingTransfers = $pdo->query("
    SELECT t.*, u.full_name, u.account_number
    FROM transfers t
    JOIN users u ON u.id = t.user_id
    WHERE t.status='pending'
    ORDER BY t.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

$pendingCrypto = $pdo->query("
    SELECT c.*, u.full_name, u.account_number
    FROM crypto_orders c
    JOIN users u ON u.id = c.user_id
    WHERE c.status='pending'
    ORDER BY c.id DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Dashboard</title>

<style>
body{
    margin:0;
    font-family:Inter, sans-serif;
    background:#0b1220;
    color:white;
    padding:20px;
}

.header{
    display:flex;
    justify-content:space-between;
    align-items:center;
}

.logout{
    background:#ef4444;
    padding:8px 12px;
    border-radius:8px;
    color:white;
    text-decoration:none;
}

.stats{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:15px;
    margin:20px 0;
}

.stat{
    background:rgba(255,255,255,0.08);
    padding:15px;
    border-radius:12px;
}

.grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:20px;
}

.card{
    background:rgba(255,255,255,0.08);
    padding:20px;
    border-radius:15px;
}

.item{
    padding:12px;
    background:rgba(255,255,255,0.05);
    margin-bottom:10px;
    border-radius:10px;
}

button{
    padding:8px 12px;
    border:none;
    border-radius:6px;
    color:white;
    cursor:pointer;
}

.msg{
    background:#22c55e;
    padding:10px;
    margin:10px 0;
    border-radius:8px;
}
</style>

</head>
<body>

<div class="header">
    <h2>Welcome, <?= htmlspecialchars($admin_name) ?></h2>
    <a class="logout" href="logout.php">Logout</a>
</div>

<?php if($msg): ?>
    <div class="msg"><?= $msg ?></div>
<?php endif; ?>

<!-- STATS -->
<div class="stats">
    <div class="stat">
        <h3><?= $total_users ?></h3>
        <p>Users</p>
    </div>

    <div class="stat">
        <h3><?= $total_balance ?></h3>
        <p>Total Balance</p>
    </div>

    <div class="stat">
        <h3>Active</h3>
        <p>System Status</p>
    </div>
</div>

<!-- MAIN GRID -->
<div class="grid">

    <!-- USERS -->
    <div class="card">
        <h3>Users</h3>
        <?php foreach($users as $u): ?>
            <div class="item">
                <b><?= $u['full_name'] ?></b><br>
                <?= $u['account_number'] ?><br>
                Balance: <?= $u['checking_balance'] ?>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- TRANSACTIONS -->
    <div class="card">
        <h3>Recent Transactions</h3>
        <?php foreach($transactions as $t): ?>
            <div class="item">
                <b><?= $t['full_name'] ?></b><br>
                <?= $t['type'] ?> - <?= $t['amount'] ?><br>
                <small><?= $t['description'] ?></small>
            </div>
        <?php endforeach; ?>
    </div>

</div>

<!-- APPROVAL SYSTEM -->
<div class="grid">

    <!-- TRANSFERS -->
    <div class="card">
        <h3>Pending Transfers</h3>

        <?php foreach($pendingTransfers as $t): ?>
            <div class="item">
                <b><?= $t['full_name'] ?></b><br>
                <?= $t['account_number'] ?><br>
                $<?= $t['amount'] ?><br>

                <form method="POST">
                    <input type="hidden" name="id" value="<?= $t['id'] ?>">
                    <button name="approve_transfer" style="background:green;">Approve</button>
                    <button name="decline_transfer" style="background:red;">Decline</button>
                </form>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- CRYPTO -->
    <div class="card">
        <h3>Pending Crypto Orders</h3>

        <?php foreach($pendingCrypto as $c): ?>
            <div class="item">
                <b><?= $c['full_name'] ?></b><br>
                <?= $c['crypto_symbol'] ?> - $<?= $c['amount'] ?><br>

                <form method="POST">
                    <input type="hidden" name="id" value="<?= $c['id'] ?>">
                    <button name="approve_crypto" style="background:green;">Approve</button>
                    <button name="decline_crypto" style="background:red;">Decline</button>
                </form>
            </div>
        <?php endforeach; ?>
    </div>

</div>

</body>
</html>