<?php
session_start();
if (!isset($_SESSION['username'])) {
    $_SESSION['username'] = "Guest"; 
}

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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'super-admin') {
    header("Location: login.php");
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    $action = $_POST['action'];
    $admin_id = $_SESSION['user_id']; 

    if ($action === "approve") {
        $conn->begin_transaction();
        try {
            // Fetch all pending withdrawals
            $stmt = $conn->prepare("SELECT w.id, u.username, u.email, u.phone, w.amount 
                                    FROM tbl_withdrawals w 
                                    JOIN users u ON w.user_id = u.id 
                                    WHERE w.status = 'Pending'");
            $stmt->execute();
            $result = $stmt->get_result();
            $withdrawals = [];
    
            while ($row = $result->fetch_assoc()) {
                $withdrawals[] = $row;
            }
            $stmt->close();


            // Update payout status and withdrawal status
            foreach ($withdrawals as $withdrawal) {
                $stmt = $conn->prepare("INSERT INTO tbl_payouts (admin_id, recipient_name, phone, amount, status) VALUES (?, ?, ?, ?, 'Processing')");
                $stmt->bind_param("issi", $admin_id, $withdrawal['username'], $withdrawal['phone'], $withdrawal['amount']);
                $stmt->execute();
                $stmt->close();

                // Update withdrawal status to approved
                $stmt = $conn->prepare("UPDATE tbl_withdrawals SET status = 'Approved', approved_at = NOW(), processed_by = ? WHERE id = ?");
                $stmt->bind_param("ii", $admin_id, $withdrawal['id']);
                $stmt->execute();
                $stmt->close();
            }

            // Commit the transaction
            $conn->commit();

            // Redirect or show success message
            header("Location: approvals.php?status=success");
            exit();
        } catch (Exception $e) {
            $conn->rollback();
            error_log("Error: " . $e->getMessage());
            header("Location: approvals.php?status=error");
            exit();
        }
    }
}

// Fetch withdrawal statistics
$query_counts = "SELECT 
    COUNT(CASE WHEN status = 'Approved' THEN 1 END) AS total_approved, 
    COUNT(CASE WHEN status = 'Pending' THEN 1 END) AS total_pending, 
    COUNT(CASE WHEN status = 'Rejected' THEN 1 END) AS total_rejected 
    FROM tbl_withdrawals";
$result_counts = $conn->query($query_counts);
$counts = $result_counts->fetch_assoc();

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

// Fetch withdrawals with usernames
$query_withdrawals = "SELECT w.id, u.username, w.amount, w.status, w.created_at 
                      FROM tbl_withdrawals w 
                      JOIN users u ON w.user_id = u.id 
                      ORDER BY w.created_at DESC 
                      LIMIT $limit OFFSET $offset";
$result_withdrawals = $conn->query($query_withdrawals);

// Count total withdrawals for pagination
$total_query = "SELECT COUNT(*) AS total FROM tbl_withdrawals";
$total_result = $conn->query($total_query);
$total_withdrawals = $total_result->fetch_assoc()['total'];
$total_pages = ceil($total_withdrawals / $limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Approvals</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="includes/css/style.css">
</head>
<body>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-10 content">
            <div class="row">
            <div class="table-container mt-4">
                <h3>Approvals</h3>
                
                <table class="table table-bordered">
                    <thead class="table-dark">
                        <tr>
                            <th>Username</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Created At</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $result_withdrawals->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($row['username']); ?></td>
                                <td>GHS <?php echo number_format($row['amount'], 2); ?></td>
                                <td><?php echo $row['status']; ?></td>
                                <td><?php echo $row['created_at']; ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <div class="d-flex justify-content-center">
                <nav>
                <div class="d-flex justify-content-center mt-4">
    <nav>
        <ul class="pagination">
            <!-- Previous Button -->
            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                <a class="page-link" href="approvals.php?page=<?php echo max(1, $page - 1); ?>">Previous</a>
            </li>

            <!-- Page Numbers -->
            <?php
            $max_pages_to_show = 5;
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $start_page + $max_pages_to_show - 1);

            if ($start_page > 1) {
                echo '<li class="page-item"><a class="page-link" href="approvals.php?page=1">1</a></li>';
                if ($start_page > 2) {
                    echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                }
            }

            for ($i = $start_page; $i <= $end_page; $i++) {
                echo '<li class="page-item ' . ($i == $page ? 'active' : '') . '">
                        <a class="page-link" href="approvals.php?page=' . $i . '">' . $i . '</a>
                      </li>';
            }

            if ($end_page < $total_pages) {
                if ($end_page < $total_pages - 1) {
                    echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                }
                echo '<li class="page-item"><a class="page-link" href="approvals.php?page=' . $total_pages . '">' . $total_pages . '</a></li>';
            }
            ?>

            <!-- Next Button -->
            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                <a class="page-link" href="approvals.php?page=<?php echo min($total_pages, $page + 1); ?>">Next</a>
            </li>
        </ul>
    </nav>
</div>
        </div>
    </div>
</div>

</body>
</html>
