<?php
/**
 * Export Cases to CSV
 * Export filtered cases list to CSV
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];

$status = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';

$where = "user_id = ?";
$params = [$userId];

if ($status != 'all') {
    $where .= " AND status = ?";
    $params[] = $status;
}
if (!empty($search)) {
    $where .= " AND (patient_name LIKE ? OR patient_mobile LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$sql = "SELECT c.id, c.patient_name, c.patient_mobile, c.patient_age, c.patient_gender,
        c.chief_complaint, c.created_at, c.status, c.follow_up_date,
        r.name as remedy_name, c.prescription_potency
        FROM cases c
        LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
        WHERE $where
        ORDER BY c.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$cases = $stmt->fetchAll();

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="cases_export_' . date('Y-m-d') . '.csv"');

$output = fopen('php://output', 'w');
fputcsv($output, ['ID', 'Patient Name', 'Mobile', 'Age', 'Gender', 'Chief Complaint', 'Created Date', 'Status', 'Follow-up Date', 'Prescribed Remedy', 'Potency']);

foreach ($cases as $case) {
    fputcsv($output, [
        $case['id'], $case['patient_name'], $case['patient_mobile'], $case['patient_age'],
        $case['patient_gender'], $case['chief_complaint'], $case['created_at'],
        $case['status'], $case['follow_up_date'], $case['remedy_name'], $case['prescription_potency']
    ]);
}
fclose($output);
exit;
?>