<?php
require_once __DIR__ . '/../../includes/export_helpers.php';

require_login();
$db = get_db_connection();

$filters = [
    'start_date' => $_GET['start_date'] ?? '',
    'end_date' => $_GET['end_date'] ?? '',
    'status' => isset($_GET['status']) ? sanitize_input($_GET['status']) : '',
    'client_id' => isset($_GET['client_id']) ? (int) $_GET['client_id'] : 0,
];

$conditions = [];
$params = [];
$types = '';

if ($filters['start_date']) {
    $conditions[] = 'p.invoice_date >= ?';
    $types .= 's';
    $params[] = $filters['start_date'];
}
if ($filters['end_date']) {
    $conditions[] = 'p.invoice_date <= ?';
    $types .= 's';
    $params[] = $filters['end_date'];
}
if ($filters['status']) {
    $conditions[] = 'p.payment_status = ?';
    $types .= 's';
    $params[] = $filters['status'];
}
if ($filters['client_id'] > 0) {
    $conditions[] = 'p.client_id = ?';
    $types .= 'i';
    $params[] = $filters['client_id'];
}

$whereClause = '';
if (!empty($conditions)) {
    $whereClause = 'WHERE ' . implode(' AND ', $conditions);
}

$sql = 'SELECT p.invoice_number, c.full_name, p.amount, p.payment_status, p.invoice_date, p.due_date, p.payment_date FROM payments p JOIN clients c ON c.id = p.client_id ' . $whereClause . ' ORDER BY p.invoice_date DESC';
$stmt = $db->prepare($sql);

if ($stmt === false) {
    export_to_pdf('report_payments', 'Laporan Pembayaran', ['Invoice', 'Pelanggan', 'Nominal', 'Status', 'Invoice', 'Jatuh Tempo', 'Pembayaran'], []);
}

if ($types !== '') {
    $bindParams = [];
    $bindParams[] = &$types;
    foreach ($params as $key => $value) {
        $bindParams[] = &$params[$key];
    }
    call_user_func_array([$stmt, 'bind_param'], $bindParams);
}

$stmt->execute();
$result = $stmt->get_result();

$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = [
        $row['invoice_number'],
        $row['full_name'],
        format_currency((float) $row['amount']),
        ucfirst($row['payment_status']),
        format_date($row['invoice_date']),
        format_date($row['due_date']),
        $row['payment_date'] ? format_date($row['payment_date']) : '-',
    ];
}

export_to_pdf(
    'report_payments',
    'Laporan Pembayaran',
    ['Invoice', 'Pelanggan', 'Nominal', 'Status', 'Tanggal Invoice', 'Jatuh Tempo', 'Tanggal Bayar'],
    $rows
);
