<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';

// --- Page-Specific Logic Starts Here ---

// 2. HANDLE FORM SUBMISSIONS (APPROVE / REJECT)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // --- APPROVE A TOP-UP ---
    if ($action === 'approve_topup') {
        $transaction_id = filter_input(INPUT_POST, 'transaction_id', FILTER_VALIDATE_INT);
        if ($transaction_id) {
            $conn->begin_transaction();
            try {
                // 1. Get transaction details (lock the row for update)
                $stmt_get = $conn->prepare("SELECT user_id, amount FROM transactions WHERE id = ? AND status = 'Pending' FOR UPDATE");
                $stmt_get->bind_param("i", $transaction_id);
                $stmt_get->execute();
                $transaction = $stmt_get->get_result()->fetch_assoc();
                $stmt_get->close();

                if ($transaction) {
                    // 2. Update transaction status to 'Completed'
                    $stmt_update_trans = $conn->prepare("UPDATE transactions SET status = 'Completed' WHERE id = ?");
                    $stmt_update_trans->bind_param("i", $transaction_id);
                    $stmt_update_trans->execute();
                    $stmt_update_trans->close();

                    // 3. Add amount to user's wallet
                    $stmt_update_wallet = $conn->prepare("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?");
                    $stmt_update_wallet->bind_param("di", $transaction['amount'], $transaction['user_id']);
                    $stmt_update_wallet->execute();
                    $stmt_update_wallet->close();
                    
                    $conn->commit();
                    $_SESSION['success_message'] = "Top-up request #$transaction_id approved and wallet credited.";
                } else {
                    throw new Exception("Transaction not found or already processed.");
                }
            } catch (Exception $e) {
                $conn->rollback();
                $_SESSION['error_message'] = "An error occurred: " . $e->getMessage();
            }
        }
    }

    // --- REJECT A TOP-UP ---
    if ($action === 'reject_topup') {
        $transaction_id = filter_input(INPUT_POST, 'transaction_id', FILTER_VALIDATE_INT);
        $rejection_reason = trim($_POST['rejection_reason']);
        if ($transaction_id) {
            $stmt = $conn->prepare("UPDATE transactions SET status = 'Rejected', admin_notes = ? WHERE id = ?");
            $stmt->bind_param("si", $rejection_reason, $transaction_id);
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Top-up request #$transaction_id has been rejected.";
            } else {
                $_SESSION['error_message'] = "Error rejecting request.";
            }
            $stmt->close();
        }
    }
    
    header("Location: top-up-requests.php");
    exit();
}

// 3. FETCH TOP-UP REQUESTS FOR DISPLAY
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$where_clauses = ["t.transaction_type = 'Top-up'"];
$params = []; $types = '';

$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(u.full_name LIKE ? OR t.id = ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $search_term);
    $types .= 'ss';
}

$status_filter = $_GET['status'] ?? 'Pending'; // Default to show Pending requests
if (!empty($status_filter)) {
    $where_clauses[] = "t.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

$where_sql = "WHERE " . implode(' AND ', $where_clauses);

// Count for pagination
$count_sql = "SELECT COUNT(t.id) as total FROM transactions t JOIN users u ON t.user_id = u.id $where_sql";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

// Fetch requests for display
$fetch_sql = "SELECT t.*, u.full_name FROM transactions t JOIN users u ON t.user_id = u.id 
              $where_sql ORDER BY t.created_at DESC LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$requests_result = $stmt_fetch->get_result();


// 4. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Requests</div>
    <div class="card-body">
        <form action="top-up-requests.php" method="GET" class="row g-3">
            <div class="col-md-6"><input type="text" name="search" class="form-control" placeholder="Search by User Name or Transaction ID..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">All Statuses</option>
                    <option value="Pending" <?php if($status_filter == 'Pending') echo 'selected'; ?>>Pending</option>
                    <option value="Completed" <?php if($status_filter == 'Completed') echo 'selected'; ?>>Completed</option>
                    <option value="Rejected" <?php if($status_filter == 'Rejected') echo 'selected'; ?>>Rejected</option>
                </select>
            </div>
            <div class="col-md-3 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="top-up-requests.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr>
                <th>ID</th><th>User</th><th>Amount</th><th>Method / Reference</th><th>Date</th><th class="text-center">Proof</th><th class="text-center">Status</th><th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($requests_result->num_rows > 0): while ($request = $requests_result->fetch_assoc()): ?>
            <tr>
                <td><strong>#<?php echo $request['id']; ?></strong></td>
                <td><?php echo htmlspecialchars($request['full_name']); ?></td>
                <td class="fw-bold">₱<?php echo number_format($request['amount'], 2); ?></td>
                <td>
                    <div class="fw-bold"><?php echo htmlspecialchars($request['payment_method']); ?></div>
                    <small class="text-muted"><?php echo htmlspecialchars($request['payment_ref']); ?></small>
                </td>
                <td><?php echo date('M d, Y, h:i A', strtotime($request['created_at'])); ?></td>
                <td class="text-center">
                    <?php if(!empty($request['proof_url'])): ?>
                        <a href="../<?php echo htmlspecialchars($request['proof_url']); ?>" target="_blank" class="btn btn-sm btn-outline-info">View</a>
                    <?php else: ?>
                        <span class="text-muted">N/A</span>
                    <?php endif; ?>
                </td>
                <td class="text-center">
                    <?php $status_badge = ['Pending' => 'warning', 'Completed' => 'success', 'Rejected' => 'danger']; ?>
                    <span class="badge bg-<?php echo $status_badge[$request['status']] ?? 'secondary'; ?>"><?php echo htmlspecialchars($request['status']); ?></span>
                </td>
                <td class="text-end">
                    <?php if ($request['status'] === 'Pending'): ?>
                    <div class="d-inline-flex gap-1">
                        <form method="POST" action="top-up-requests.php" onsubmit="return confirm('Are you sure you want to approve this top-up? This action cannot be undone.');">
                            <input type="hidden" name="action" value="approve_topup">
                            <input type="hidden" name="transaction_id" value="<?php echo $request['id']; ?>">
                            <button type="submit" class="btn btn-sm btn-success" title="Approve"><i class="bi bi-check-lg"></i></button>
                        </form>
                        <button type="button" class="btn btn-sm btn-danger reject-btn" data-bs-toggle="modal" data-bs-target="#rejectModal" data-id="<?php echo $request['id']; ?>" title="Reject">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    </div>
                    <?php else: ?>
                        <em class="text-muted small">Processed</em>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="8" class="text-center p-4">No top-up requests found matching your criteria.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<div class="modal fade" id="rejectModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<form action="top-up-requests.php" method="POST"><div class="modal-header"><h5 class="modal-title">Reject Top-Up Request</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body">
    <input type="hidden" name="action" value="reject_topup">
    <input type="hidden" name="transaction_id" id="modal-transaction-id">
    <div class="mb-3"><label for="rejection_reason" class="form-label">Reason for Rejection <span class="text-danger">*</span></label><textarea class="form-control" id="rejection_reason" name="rejection_reason" rows="3" placeholder="e.g., Unclear receipt, amount mismatch..." required></textarea></div>
</div>
<div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-danger">Confirm Rejection</button></div>
</form></div></div></div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const rejectModal = document.getElementById('rejectModal');
    rejectModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const transactionId = button.getAttribute('data-id');
        document.getElementById('modal-transaction-id').value = transactionId;
    });
});
</script>

<?php include 'admin-footer.php'; ?>
