<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("check_installation.php");
include("fetch_settings.php");
require_once("../config/functions.php");
require_once("../config/topup_helpers.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

ensureTopupSchema($con);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $requestId = isset($_POST['request_id']) ? (int) $_POST['request_id'] : 0;
    $adminNote = trim($_POST['admin_note'] ?? '');
    $adminId = (string) $_SESSION['adminid'];

    if ($requestId > 0 && isset($_POST['approve_request'])) {
        $con->begin_transaction();
        try {
            $stmt = $con->prepare("
                SELECT tr.*, pm.method_name, c.firstname, c.lastname, c.email
                FROM topup_requests tr
                INNER JOIN payment_methods pm ON pm.id = tr.method_id
                INNER JOIN customers c ON c.customerid = tr.customerid
                WHERE tr.id = ?
                LIMIT 1
            ");
            $stmt->bind_param("i", $requestId);
            $stmt->execute();
            $request = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$request) {
                throw new Exception("Top up request not found.");
            }
            if ($request['status'] !== 'pending') {
                throw new Exception("This top up request has already been processed.");
            }

            $customerId = (int) $request['customerid'];
            $amount = (float) $request['amount'];
            $now = date("Y-m-d H:i:s");

            $stmtBal = $con->prepare("UPDATE accounts SET accountbalance = accountbalance + ? WHERE customerid = ?");
            $stmtBal->bind_param("di", $amount, $customerId);
            $stmtBal->execute();
            $stmtBal->close();

            $stmtTxn = $con->prepare("
                INSERT INTO transactions (cashier, type, paymentdate, receiveid, amount, paymentstat)
                VALUES (?, 'Credit', ?, ?, ?, 'active')
            ");
            $receiveId = (string) $customerId;
            $amountString = (string) $amount;
            $stmtTxn->bind_param("ssss", $adminId, $now, $receiveId, $amountString);
            $stmtTxn->execute();
            $stmtTxn->close();

            $stmtUpdate = $con->prepare("
                UPDATE topup_requests
                SET status='approved', notified_customer=0, admin_note=?, processed_by=?, processed_at=NOW()
                WHERE id=?
            ");
            $stmtUpdate->bind_param("ssi", $adminNote, $adminId, $requestId);
            $stmtUpdate->execute();
            $stmtUpdate->close();

            $con->commit();

            if (!empty($request['email'])) {
                $customerName = htmlspecialchars(trim($request['firstname'] . ' ' . $request['lastname']));
                $formattedAmount = htmlspecialchars($cur) . number_format($amount, 2);
                $reference = htmlspecialchars($request['reference']);
                $methodName = htmlspecialchars($request['method_name']);
                $subject = "Top Up Approved - {$reference}";
                $body = "
                <!DOCTYPE html>
                <html>
                <head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'></head>
                <body style='margin:0;padding:0;background:#f8fafc;font-family:Arial,sans-serif;'>
                    <table width='100%' cellpadding='0' cellspacing='0' style='padding:30px 15px;'>
                        <tr><td align='center'>
                            <table width='100%' cellpadding='0' cellspacing='0' style='max-width:600px;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 4px 15px rgba(0,0,0,0.05);'>
                                <tr><td style='background:linear-gradient(135deg,#003399 0%,#005D9D 100%);padding:24px;text-align:center;color:#fff;'><h2 style='margin:0;'>Top Up Approved</h2></td></tr>
                                <tr><td style='padding:28px;color:#0f172a;line-height:1.6;'>
                                    <p>Hello {$customerName},</p>
                                    <p>Your top up request has been approved and your account has been credited successfully.</p>
                                    <div style='background:#e6efff;border-left:4px solid #003399;padding:16px;border-radius:0 8px 8px 0;'>
                                        <p style='margin:0 0 6px;'><strong>Reference:</strong> {$reference}</p>
                                        <p style='margin:0 0 6px;'><strong>Method:</strong> {$methodName}</p>
                                        <p style='margin:0;'><strong>Amount Credited:</strong> {$formattedAmount}</p>
                                    </div>
                                </td></tr>
                                <tr><td style='padding:16px;text-align:center;font-size:12px;color:#94a3b8;background:#f1f5f9;'>&copy; " . date('Y') . " " . htmlspecialchars($sbank) . ".</td></tr>
                            </table>
                        </td></tr>
                    </table>
                </body>
                </html>
                ";
                sendMail($request['email'], $subject, $body);
            }

            $_SESSION['message'] = ['type' => 'success', 'text' => 'Top up approved and account credited successfully.'];
        } catch (Exception $e) {
            $con->rollback();
            $_SESSION['message'] = ['type' => 'error', 'text' => $e->getMessage()];
        }
    }

    if ($requestId > 0 && isset($_POST['reject_request'])) {
        $stmt = $con->prepare("
            SELECT tr.*, pm.method_name, c.firstname, c.lastname, c.email
            FROM topup_requests tr
            INNER JOIN payment_methods pm ON pm.id = tr.method_id
            INNER JOIN customers c ON c.customerid = tr.customerid
            WHERE tr.id = ?
            LIMIT 1
        ");
        $stmt->bind_param("i", $requestId);
        $stmt->execute();
        $request = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($request && $request['status'] === 'pending') {
            $stmtReject = $con->prepare("
                UPDATE topup_requests
                SET status='rejected', notified_customer=0, admin_note=?, processed_by=?, processed_at=NOW()
                WHERE id=?
            ");
            $stmtReject->bind_param("ssi", $adminNote, $adminId, $requestId);
            $stmtReject->execute();
            $stmtReject->close();

            if (!empty($request['email'])) {
                $customerName = htmlspecialchars(trim($request['firstname'] . ' ' . $request['lastname']));
                $formattedAmount = htmlspecialchars($cur) . number_format((float) $request['amount'], 2);
                $reference = htmlspecialchars($request['reference']);
                $methodName = htmlspecialchars($request['method_name']);
                $subject = "Top Up Update - {$reference}";
                $body = "
                <!DOCTYPE html>
                <html>
                <head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'></head>
                <body style='margin:0;padding:0;background:#f8fafc;font-family:Arial,sans-serif;'>
                    <table width='100%' cellpadding='0' cellspacing='0' style='padding:30px 15px;'>
                        <tr><td align='center'>
                            <table width='100%' cellpadding='0' cellspacing='0' style='max-width:600px;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 4px 15px rgba(0,0,0,0.05);'>
                                <tr><td style='background:linear-gradient(135deg,#9b1c1c 0%,#dc2626 100%);padding:24px;text-align:center;color:#fff;'><h2 style='margin:0;'>Top Up Rejected</h2></td></tr>
                                <tr><td style='padding:28px;color:#0f172a;line-height:1.6;'>
                                    <p>Hello {$customerName},</p>
                                    <p>Your top up request was reviewed and could not be approved.</p>
                                    <div style='background:#fee2e2;border-left:4px solid #dc2626;padding:16px;border-radius:0 8px 8px 0;'>
                                        <p style='margin:0 0 6px;'><strong>Reference:</strong> {$reference}</p>
                                        <p style='margin:0 0 6px;'><strong>Method:</strong> {$methodName}</p>
                                        <p style='margin:0 0 6px;'><strong>Amount:</strong> {$formattedAmount}</p>
                                        <p style='margin:0;'><strong>Admin Note:</strong> " . htmlspecialchars($adminNote !== '' ? $adminNote : 'No additional note provided.') . "</p>
                                    </div>
                                </td></tr>
                                <tr><td style='padding:16px;text-align:center;font-size:12px;color:#94a3b8;background:#f1f5f9;'>&copy; " . date('Y') . " " . htmlspecialchars($sbank) . ".</td></tr>
                            </table>
                        </td></tr>
                    </table>
                </body>
                </html>
                ";
                sendMail($request['email'], $subject, $body);
            }

            $_SESSION['message'] = ['type' => 'success', 'text' => 'Top up request rejected successfully.'];
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Top up request not found or already processed.'];
        }
    }

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

$requests = [];
$resultRequests = $con->query("
    SELECT tr.*, pm.method_name, c.firstname, c.lastname, c.email
    FROM topup_requests tr
    INNER JOIN payment_methods pm ON pm.id = tr.method_id
    INNER JOIN customers c ON c.customerid = tr.customerid
    ORDER BY tr.created_at DESC
");
while ($row = $resultRequests->fetch_assoc()) {
    $requests[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Top Up Requests</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <style>
        .status-pill { padding: 6px 10px; border-radius: 999px; font-size: 12px; font-weight: 700; text-transform: capitalize; }
        .status-pending { background: #fff3cd; color: #946200; }
        .status-approved { background: #d1e7dd; color: #0f5132; }
        .status-rejected { background: #f8d7da; color: #842029; }
    </style>
</head>
<body>
<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">
            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <h1 class="h3 mb-2 mb-sm-0">Top Up Requests</h1>
                    <p class="text-muted mb-0">Review customer top up requests and process them.</p>
                </div>
            </div>

            <?php if (isset($_SESSION['message'])): $message = $_SESSION['message']; unset($_SESSION['message']); ?>
                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        Swal.fire({
                            title: '<?= $message['type'] === 'success' ? 'Success' : 'Error'; ?>',
                            text: '<?= $message['text']; ?>',
                            icon: '<?= $message['type']; ?>',
                            confirmButtonText: 'OK'
                        });
                    });
                </script>
            <?php endif; ?>

            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h5 class="card-title mb-0">All Requests</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($requests)): ?>
                        <p class="mb-0 text-muted">No top up request has been submitted yet.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Reference</th>
                                    <th>Customer</th>
                                    <th>Method</th>
                                    <th>Amount</th>
                                    <th>Receipt</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($requests as $req): ?>
                                    <tr>
                                        <td>
                                            <div class="fw-bold"><?= htmlspecialchars($req['reference']); ?></div>
                                            <small class="text-muted"><?= date("d M Y H:i", strtotime($req['created_at'])); ?></small>
                                        </td>
                                        <td>
                                            <div><?= htmlspecialchars(trim($req['firstname'] . ' ' . $req['lastname'])); ?></div>
                                            <small class="text-muted"><?= htmlspecialchars($req['email']); ?></small>
                                        </td>
                                        <td><?= htmlspecialchars($req['method_name']); ?></td>
                                        <td><?= htmlspecialchars($cur) . number_format((float) $req['amount'], 2); ?></td>
                                        <td>
                                            <?php if (!empty($req['receipt_path'])): ?>
                                                <a class="btn btn-sm btn-light" target="_blank" href="../customer/<?= htmlspecialchars($req['receipt_path']); ?>">View</a>
                                            <?php else: ?>
                                                <span class="text-muted">N/A</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="status-pill status-<?= htmlspecialchars($req['status']); ?>">
                                                <?= htmlspecialchars($req['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($req['status'] === 'pending'): ?>
                                                <button
                                                    class="btn btn-sm btn-success"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#processModal"
                                                    data-request-id="<?= (int) $req['id']; ?>"
                                                    data-request-action="approve"
                                                >Approve</button>
                                                <button
                                                    class="btn btn-sm btn-danger"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#processModal"
                                                    data-request-id="<?= (int) $req['id']; ?>"
                                                    data-request-action="reject"
                                                >Reject</button>
                                            <?php else: ?>
                                                <small class="text-muted"><?= htmlspecialchars($req['processed_by'] ?? '-'); ?></small>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="processModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h5 class="modal-title" id="processModalTitle">Process Top Up Request</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="request_id" id="modal_request_id">
                    <input type="hidden" name="approve_request" id="modal_approve" value="">
                    <input type="hidden" name="reject_request" id="modal_reject" value="">
                    <div class="mb-3">
                        <label class="form-label">Admin Note</label>
                        <textarea class="form-control" name="admin_note" rows="4" placeholder="Optional note for this decision"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="processSubmitBtn">Continue</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>
<script>
    const processModal = document.getElementById('processModal');
    if (processModal) {
        processModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const requestId = button.getAttribute('data-request-id');
            const action = button.getAttribute('data-request-action');

            document.getElementById('modal_request_id').value = requestId;
            document.getElementById('modal_approve').value = '';
            document.getElementById('modal_reject').value = '';

            const title = document.getElementById('processModalTitle');
            const submitBtn = document.getElementById('processSubmitBtn');

            if (action === 'approve') {
                title.textContent = 'Approve Top Up Request';
                submitBtn.textContent = 'Approve';
                submitBtn.className = 'btn btn-success';
                document.getElementById('modal_approve').value = '1';
            } else {
                title.textContent = 'Reject Top Up Request';
                submitBtn.textContent = 'Reject';
                submitBtn.className = 'btn btn-danger';
                document.getElementById('modal_reject').value = '1';
            }
        });
    }
</script>
</body>
</html>

