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

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

// --- ACTION LOGIC (Approve / Decline / Delete) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && isset($_POST['trans_id'])) {
    $trans_id = (int)$_POST['trans_id'];
    $action = $_POST['action'];

    // 1. DELETE ACTION
    if ($action === 'delete') {
        $del_query = "DELETE FROM `transactions` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_query)) {
            mysqli_stmt_bind_param($stmt, "i", $trans_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Transaction record permanently deleted.";
                $_SESSION['swal_title'] = "Deleted!";
            }
            mysqli_stmt_close($stmt);
        }
    } 
    
    // 2. APPROVE / DECLINE ACTION
    else {
        $fetch_query = "SELECT t.user_id, t.amount, t.status, u.full_name 
                        FROM `transactions` t 
                        JOIN `users` u ON t.user_id = u.id 
                        WHERE t.id = ? LIMIT 1";
        
        if ($stmt = mysqli_prepare($conn, $fetch_query)) {
            mysqli_stmt_bind_param($stmt, "i", $trans_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $tr_user_id, $tr_amount, $tr_status, $tr_full_name);
            
            if (mysqli_stmt_fetch($stmt)) {
                $user_id = $tr_user_id;
                $amount = $tr_amount;
                $status = $tr_status;
                $full_name = $tr_full_name;
                mysqli_stmt_close($stmt);

                if ($status === 'pending') {
                    if ($action === 'approve') {
                        $update_t = "UPDATE `transactions` SET `status` = 'completed' WHERE `id` = ?";
                        $stmt_t = mysqli_prepare($conn, $update_t);
                        mysqli_stmt_bind_param($stmt_t, "i", $trans_id);
                        
                        $update_u = "UPDATE `users` SET `balance` = `balance` + ? WHERE `id` = ?";
                        $stmt_u = mysqli_prepare($conn, $update_u);
                        mysqli_stmt_bind_param($stmt_u, "di", $amount, $user_id);

                        if (mysqli_stmt_execute($stmt_t) && mysqli_stmt_execute($stmt_u)) {
                            $_SESSION['swal_success'] = "Deposit of $" . number_format($amount, 2) . " approved for " . $full_name;
                            $_SESSION['swal_title'] = "Approved!";
                        }
                        mysqli_stmt_close($stmt_t);
                        mysqli_stmt_close($stmt_u);

                    } elseif ($action === 'decline') {
                        $decline_q = "UPDATE `transactions` SET `status` = 'failed' WHERE `id` = ?";
                        if ($stmt_d = mysqli_prepare($conn, $decline_q)) {
                            mysqli_stmt_bind_param($stmt_d, "i", $trans_id);
                            if (mysqli_stmt_execute($stmt_d)) {
                                $_SESSION['swal_success'] = "Deposit request declined.";
                                $_SESSION['swal_title'] = "Declined";
                            }
                            mysqli_stmt_close($stmt_d);
                        }
                    }
                }
            } else { mysqli_stmt_close($stmt); }
        }
    }
    header("Location: manage_deposits.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION LOGIC ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `transactions` WHERE `type` = 'deposit'");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'];
$total_pages = ceil($total_records / $limit);

// Fetch deposits with limit and offset
$query = "SELECT t.*, u.username, u.full_name 
          FROM `transactions` t 
          JOIN `users` u ON t.user_id = u.id 
          WHERE t.type = 'deposit' 
          ORDER BY t.created_at DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; }
    .pagination-btn:hover:not(.active) { background: #1e293b; color: white; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8">
        <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Premiumtrustglobal Admin</div>
        <h1 class="text-3xl font-bold text-white tracking-tight">Deposit History</h1>
        <p class="text-slate-400 mt-1 text-sm">Reviewing <?php echo $total_records; ?> total deposit requests</p>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col min-h-[500px]">
        <div class="overflow-x-auto flex-grow">
            <table class="w-full text-left border-collapse min-w-[900px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">User Details</th>
                        <th class="p-4">Amount</th>
                        <th class="p-4">Method</th>
                        <th class="p-4">Proof</th>
                        <th class="p-4">Status</th>
                        <th class="p-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if(mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['full_name']); ?></div>
                                <div class="text-[11px] text-slate-500">@<?php echo htmlspecialchars($row['username']); ?> • <?php echo date('M d, H:i', strtotime($row['created_at'])); ?></div>
                            </td>
                            <td class="p-4">
                                <span class="text-emerald-400 font-mono font-bold">$<?php echo number_format($row['amount'], 2); ?></span>
                            </td>
                            <td class="p-4">
                                <div class="text-slate-200"><?php echo htmlspecialchars($row['method']); ?></div>
                                <div class="text-[10px] text-slate-500 font-mono"><?php echo htmlspecialchars($row['ref'] ?: 'No Reference'); ?></div>
                            </td>
                            <td class="p-4">
                                <?php if($row['proof_img']): ?>
                                    <button onclick="viewProof('../uploads/proofs/<?php echo $row['proof_img']; ?>')" class="text-blue-500 hover:text-blue-400 text-xs font-bold underline">View Image</button>
                                <?php else: ?>
                                    <span class="text-slate-600 text-xs italic">N/A</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4">
                                <?php if($row['status'] === 'pending'): ?>
                                    <span class="status-pill bg-amber-500/10 text-amber-500 border border-amber-500/20">Pending</span>
                                <?php elseif($row['status'] === 'completed'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Approved</span>
                                <?php else: ?>
                                    <span class="status-pill bg-red-500/10 text-red-500 border border-red-500/20">Declined</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3 items-center">
                                    <?php if($row['status'] === 'pending'): ?>
                                        <form method="POST" class="inline m-0">
                                            <input type="hidden" name="trans_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="action" value="approve">
                                            <button type="button" onclick="confirmTrans(this.form, 'approve')" class="text-emerald-500 font-bold text-[10px] uppercase tracking-tighter">Approve</button>
                                        </form>
                                        <form method="POST" class="inline m-0">
                                            <input type="hidden" name="trans_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="action" value="decline">
                                            <button type="button" onclick="confirmTrans(this.form, 'decline')" class="text-orange-500 font-bold text-[10px] uppercase tracking-tighter">Decline</button>
                                        </form>
                                    <?php endif; ?>

                                    <form method="POST" class="inline m-0">
                                        <input type="hidden" name="trans_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="button" onclick="confirmTrans(this.form, 'delete')" class="bg-red-500/10 text-red-500 p-1.5 rounded hover:bg-red-500 hover:text-white transition-all">
                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500 font-medium">
                Page <?php echo $page; ?> of <?php echo $total_pages; ?>
            </div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs text-slate-400">Prev</a>
                <?php endif; ?>

                <?php 
                $start = max(1, $page - 2);
                $end = min($total_pages, $page + 2);
                for($i = $start; $i <= $end; $i++): 
                ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs <?php echo ($i == $page) ? 'active' : 'text-slate-400'; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>

                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs text-slate-400">Next</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<script>
function viewProof(url) {
    Swal.fire({ imageUrl: url, background: '#0f172a', showConfirmButton: false, showCloseButton: true });
}

function confirmTrans(form, type) {
    let title = 'Process Request?';
    let text = 'This action will update the user account.';
    let icon = 'question';
    let btnColor = '#3b82f6';

    if(type === 'delete') {
        title = 'Delete Record?';
        text = 'This will permanently remove the transaction record from history.';
        icon = 'warning';
        btnColor = '#ef4444';
    } else if(type === 'decline') {
        btnColor = '#f59e0b';
    } else if(type === 'approve') {
        btnColor = '#10b981';
        text = "This will add funds to the user's balance.";
    }

    Swal.fire({
        title: title,
        text: text,
        icon: icon,
        showCancelButton: true,
        confirmButtonColor: btnColor,
        cancelButtonColor: '#1e293b',
        confirmButtonText: 'Confirm',
        background: '#0f172a',
        color: '#f1f5f9'
    }).then((result) => { if (result.isConfirmed) form.submit(); });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>