<?php
// Use the permission system. This must be done before any HTML output.
require_once '../core/bootstrap.php';
requirePermission('payments:view');

$pageTitle = 'Payment Transactions';
include 'includes/header.php';
include 'includes/sidebar.php';

// --- Get filter dates ---
$start_date = $_GET['start_date'] ?? null;
$end_date = $_GET['end_date'] ?? null;

// Pagination
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// --- Instantiate Models and Fetch Data ---
$paymentModel = new Payment();
$settingModel = new Setting();

$total_payments = $paymentModel->getTotalPaymentsCount($start_date, $end_date);
$total_pages = ceil($total_payments / $limit);
$payments = $paymentModel->getAllWithDetails($start_date, $end_date, $limit, $offset);

// Get currency symbol
$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

?>

<!-- Begin Page Content -->
<div class="container-fluid">

    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Payment Transactions</h1>
    </div>

    <!-- Filter Form -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Filter Payments</h6>
        </div>
        <div class="card-body">
            <form action="payments.php" method="GET" class="form-inline">
                <div class="form-group mr-3 mb-2">
                    <label for="start_date" class="mr-2">Start Date:</label>
                    <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo htmlspecialchars($start_date ?? ''); ?>">
                </div>
                <div class="form-group mr-3 mb-2">
                    <label for="end_date" class="mr-2">End Date:</label>
                    <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo htmlspecialchars($end_date ?? ''); ?>">
                </div>
                <button type="submit" class="btn btn-primary mb-2">Filter</button>
                <a href="payments.php" class="btn btn-secondary ml-2 mb-2">Reset</a>
            </form>
        </div>
    </div>

    <!-- DataTales Example -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">All Recorded Payments</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <?php if (!empty($payments)): ?>
                    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>User</th>
                                <th>Amount</th>
                                <th>Transaction Ref</th>
                                <th>Gateway</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($payments as $payment): ?>
                                <tr>
                                    <td><?php echo date('d M Y, H:i', strtotime($payment->created_at)); ?></td>
                                    <td><?php echo htmlspecialchars($payment->user_name); ?></td>
                                    <td><?php echo $currency_symbol; ?><?php echo number_format($payment->amount, 2); ?></td>
                                    <td><?php echo htmlspecialchars($payment->transaction_ref); ?></td>
                                    <td><span class="badge badge-info"><?php echo htmlspecialchars(ucfirst($payment->payment_gateway)); ?></span></td>
                                    <td><span class="badge badge-success"><?php echo htmlspecialchars(ucfirst($payment->status)); ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p class="text-center">No payment transactions have been recorded yet.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
        <div class="d-flex justify-content-center">
            <nav>
                <ul class="pagination">
                    <?php
                        // Build query string for pagination links, preserving filters
                        $query_params = http_build_query(['start_date' => $start_date, 'end_date' => $end_date]);
                    ?>
                    <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&<?php echo $query_params; ?>">Previous</a>
                    </li>
                    <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&<?php echo $query_params; ?>">Next</a>
                    </li>
                </ul>
            </nav>
        </div>
    <?php endif; ?>

</div>
<!-- /.container-fluid -->

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