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

require 'config.php';
include 'includes/header.php';
include 'includes/admin-sidebar.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'super-admin') {
    die("Access Denied: You are not authorized to view this page.");
}

$user_id = $_SESSION['user_id'];
$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Super Admin username
$stmt = $conn->prepare("SELECT username FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
$username = htmlspecialchars($user['username']);

// Withdrawal Stats
// Last Month
$stmt = $conn->prepare("SELECT SUM(amount) AS last_month FROM tbl_withdrawals WHERE created_at >= CURDATE() - INTERVAL 1 MONTH");
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$last_month_withdrawals = $result['last_month'] ?? 0;
$stmt->close();

// This Month
$stmt = $conn->prepare("SELECT SUM(amount) AS this_month FROM tbl_withdrawals WHERE MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE())");
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$this_month_withdrawals = $result['this_month'] ?? 0;
$stmt->close();

// Total
$stmt = $conn->prepare("SELECT SUM(amount) AS total FROM tbl_withdrawals");
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$total_withdrawals = $result['total'] ?? 0;
$stmt->close();

// Withdrawals table
$stmt = $conn->prepare("
    SELECT w.*, u.username, u.phone, u.email 
    FROM tbl_withdrawals w 
    JOIN users u ON w.user_id = u.id 
    ORDER BY w.created_at DESC 
    LIMIT ? OFFSET ?
");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$transactions = $stmt->get_result();
$stmt->close();

// Total for pagination
$stmt = $conn->prepare("SELECT COUNT(*) AS total FROM tbl_withdrawals");
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();
$total_pages = ceil($total_records / $limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Withdrawal History</title>
    <link rel="stylesheet" href="includes/css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
</head>
<style>
/* Cards */
.card.last {
    background-color: #d1e7dd;;
}
.card.current {
    background-color: #ffeee6;
}
.card.total {
    background-color: #ecf1ff;
}
.card h5 {
    font-size: 1rem;
    color: #555;
}
.card h3 {
    font-weight: bold;
}

/* Status Badges */
.status-badge {
    padding: 5px 12px;
    border-radius: 20px;
    font-weight: bold;
    font-size: 0.85rem;
    text-transform: capitalize;
    display: inline-block;
}
.status-pending {
    background-color: #fff3cd;
    color: #856404;
}
.status-approved {
    background-color: #d4edda;
    color: #155724;
}
.status-rejected {
    background-color: #f8d7da;
    color: #721c24;
}

/* Table Styling */
.table {
    background-color: #fff;
}
.table th {
    background-color: #f2f2f2;
    color: #333;
    font-weight: 600;
}
.table-striped > tbody > tr:nth-of-type(odd) {
    background-color: #f9f9f9;
}
.table-hover tbody tr:hover {
    background-color: #eef1f5;
}

/* Withdrawal Button */
.btn-danger {
    background-color: #dc3545;
    border: none;
}
.btn-danger:hover {
    background-color: #c82333;
}

/* Responsive tweaks */
@media (max-width: 768px) {
    .table thead {
        display: none;
    }

    .table tbody td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
    }

    .table tbody td::before {
        content: attr(data-label);
        position: absolute;
        left: 0;
        width: 50%;
        padding-left: 15px;
        font-weight: bold;
        text-align: left;
    }
}
</style>
<body style="background-color: #f8f9fa;">
<div class="container-fluid">
    <div class="row">
        <div class="col-md-10 content">
        <div class="d-flex justify-content-between mb-4">
                        <a href="withdraw_admin.php" class="btn btn-danger">Make a Withdrawal</a>
                    </div>
            <!-- Withdrawal Cards -->
            <div class="row mt-4">
                <div class="col-md-4">
                    <div class="card card last p-3">
                        <h5>Last Month Withdrawals</h5>
                        <h3>GHS <?php echo number_format($last_month_withdrawals, 2); ?></h3>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card card current p-3">
                        <h5>This Month Withdrawals</h5>
                        <h3>GHS <?php echo number_format($this_month_withdrawals, 2); ?></h3>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card card total p-3">
                        <h5>Total Withdrawals</h5>
                        <h3>GHS <?php echo number_format($total_withdrawals, 2); ?></h3>
                    </div>
                </div>
            </div>
            <h4 class="mt-4">Withdrawals History</h4>
            <!-- History Table -->
            <table class="table table-bordered table-hover table-striped">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Username</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Amount</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($transactions->num_rows > 0): ?>
                        <?php while ($row = $transactions->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo $row['created_at']; ?></td>
                                <td><?php echo htmlspecialchars($row['username']); ?></td>
                                <td><?php echo htmlspecialchars($row['phone']); ?></td>
                                <td><?php echo htmlspecialchars($row['email']); ?></td>
                                <td>GHS <?php echo number_format($row['amount'], 2); ?></td>
                                <td>
                                    <span class="status-badge 
                                        <?php 
                                            echo $row['status'] === 'pending' ? 'status-pending' : 
                                                 ($row['status'] === 'approved' ? 'status-approved' : 'status-rejected'); 
                                        ?>">
                                        <?php echo ucfirst($row['status']); ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="text-center">No withdrawal history available.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Pagination -->
            <nav>
                <ul class="pagination">
    <?php
    $max_pages_to_show = 6;
    $start = max(1, $page - floor($max_pages_to_show / 2));
    $end = min($start + $max_pages_to_show - 1, $total_pages);

    if ($start > 1): ?>
        <li class="page-item">
            <a class="page-link" href="withdrawal_history.php?page=1">1</a>
        </li>
        <li class="page-item disabled"><span class="page-link">...</span></li>
    <?php endif; ?>

    <?php for ($i = $start; $i <= $end; $i++): ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
            <a class="page-link" href="withdraw_history.php?page=<?php echo $i; ?>"><?php echo $i; ?></a>
        </li>
    <?php endfor; ?>

    <?php if ($end < $total_pages): ?>
        <li class="page-item disabled"><span class="page-link">...</span></li>
        <li class="page-item">
            <a class="page-link" href="withdraw_history.php?page=<?php echo $total_pages; ?>"><?php echo $total_pages; ?></a>
        </li>
    <?php endif; ?>

    <?php if ($page < $total_pages): ?>
        <li class="page-item">
            <a class="page-link" href="withdraw_history.php?page=<?php echo $page + 1; ?>">Next</a>
        </li>
    <?php endif; ?>
</ul>
            </nav>

        </div>
    </div>
</div>
</body>
</html>
