<?php
session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT', 'FRONT_OFFICE'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: ../index.php');
    exit();
}

// Get filter parameters
$start_date = isset($_GET['start_date']) ? mysqli_real_escape_string($conn, $_GET['start_date']) : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? mysqli_real_escape_string($conn, $_GET['end_date']) : date('Y-m-d');
$status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
$payment_method = isset($_GET['payment_method']) ? mysqli_real_escape_string($conn, $_GET['payment_method']) : '';

// Build query with filters
$query = "SELECT p.payment_number, p.payment_date, p.amount, p.payment_method, 
          p.status, p.transaction_reference, p.currency,
          i.invoice_number,
          pat.patient_number,
          u.full_name as patient_name,
          u.phone_number,
          receiver.full_name as received_by_name,
          dept.department_name
          FROM payments p
          JOIN invoices i ON p.invoice_id = i.invoice_id
          JOIN patients pat ON p.patient_id = pat.patient_id
          JOIN users u ON pat.user_id = u.user_id
          LEFT JOIN users receiver ON p.received_by = receiver.user_id
          LEFT JOIN departments dept ON pat.department_id = dept.department_id
          WHERE DATE(p.payment_date) BETWEEN '$start_date' AND '$end_date'";

if (!empty($status)) {
    $query .= " AND p.status = '$status'";
}

if (!empty($payment_method)) {
    $query .= " AND p.payment_method = '$payment_method'";
}

$query .= " ORDER BY p.payment_date DESC, p.created_at DESC";

$result = mysqli_query($conn, $query);

// Set headers for CSV download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=payments_export_' . date('Y-m-d_His') . '.csv');

// Create output stream
$output = fopen('php://output', 'w');

// Add BOM for Excel UTF-8 support
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Add CSV headers
fputcsv($output, [
    'Payment Number',
    'Payment Date',
    'Invoice Number',
    'Patient Name',
    'Patient Number',
    'Phone Number',
    'Department',
    'Amount (KES)',
    'Currency',
    'Payment Method',
    'Transaction Reference',
    'Status',
    'Received By'
]);

// Add data rows
if (mysqli_num_rows($result) > 0) {
    $total_amount = 0;
    while ($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, [
            $row['payment_number'],
            date('Y-m-d H:i:s', strtotime($row['payment_date'])),
            $row['invoice_number'],
            $row['patient_name'],
            $row['patient_number'],
            $row['phone_number'],
            $row['department_name'] ?? 'N/A',
            number_format($row['amount'], 2),
            $row['currency'],
            str_replace('_', ' ', $row['payment_method']),
            $row['transaction_reference'] ?? 'N/A',
            $row['status'],
            $row['received_by_name']
        ]);
        
        if ($row['status'] == 'COMPLETED') {
            $total_amount += $row['amount'];
        }
    }
    
    // Add summary row
    fputcsv($output, []);
    fputcsv($output, ['TOTAL COMPLETED PAYMENTS', '', '', '', '', '', '', number_format($total_amount, 2)]);
} else {
    // Add empty row if no data
    fputcsv($output, ['No payments found for the selected criteria']);
}

fclose($output);
mysqli_close($conn);
exit();
?>