<?php
declare(strict_types=1);

session_start();
require_once '../config.php';
$conn = getDBConnection();

header('Content-Type: application/json');
ini_set('display_errors', '0');
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['data' => []]);
    exit;
}

if (!$conn) {
    echo json_encode(['payments' => [], 'grand_total' => 0]);
    exit;
}

$dateFrom = trim((string) ($_POST['date_from'] ?? ''));
$dateTo = trim((string) ($_POST['date_to'] ?? ''));
$gateway = trim((string) ($_POST['gateway'] ?? ''));
$method = trim((string) ($_POST['method'] ?? ''));
$status = trim((string) ($_POST['status'] ?? ''));

$sql = "SELECT op.id, op.initiated_at, op.receipt_number, op.amount, op.payment_method, op.gateway, op.status,
               s.first_name, s.last_name, s.class
        FROM online_payments op
        INNER JOIN students s ON s.id = op.student_id
        WHERE 1=1";
$types = '';
$params = [];

if ($dateFrom !== '') { $sql .= " AND DATE(op.initiated_at) >= ?"; $types .= 's'; $params[] = $dateFrom; }
if ($dateTo !== '') { $sql .= " AND DATE(op.initiated_at) <= ?"; $types .= 's'; $params[] = $dateTo; }
if ($gateway !== '') { $sql .= " AND op.gateway = ?"; $types .= 's'; $params[] = $gateway; }
if ($method !== '') { $sql .= " AND op.payment_method = ?"; $types .= 's'; $params[] = $method; }
if ($status !== '') { $sql .= " AND op.status = ?"; $types .= 's'; $params[] = $status; }
$sql .= " ORDER BY op.initiated_at DESC";

$stmt = $conn->prepare($sql);
if ($types !== '') {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = [
        'date' => $row['initiated_at'],
        'receipt_number' => $row['receipt_number'],
        'student' => trim($row['first_name'] . ' ' . $row['last_name']),
        'class' => $row['class'],
        'amount' => number_format((float) $row['amount'], 2),
        'method' => $row['payment_method'],
        'gateway' => $row['gateway'],
        'status' => $row['status'],
        'action' => '<a href="payment_receipt.php?id=' . (int) $row['id'] . '" class="btn btn-sm btn-outline-primary">View Receipt</a>'
    ];
}
$stmt->close();

echo json_encode(['data' => $rows]);
