<?php
/**
 * Export Remedies to CSV/JSON
 * Export all remedies with their details
 */

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

requireAdmin();

$pdo = getDB();
$format = $_GET['format'] ?? 'csv';
$type = $_GET['type'] ?? 'full';

if ($format == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="remedies_export_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    if ($type == 'simple') {
        fputcsv($output, ['ID', 'Remedy Name', 'Abbreviation', 'Rubric Count', 'Prescription Count']);
        
        $stmt = $pdo->query("SELECT r.id, r.name, r.abbreviation,
                            (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = r.id) as rubric_count,
                            (SELECT COUNT(*) FROM cases WHERE prescribed_remedy_id = r.id) as prescription_count
                            FROM remedies r ORDER BY r.name");
        while ($row = $stmt->fetch()) {
            fputcsv($output, [$row['id'], $row['name'], $row['abbreviation'], $row['rubric_count'], $row['prescription_count']]);
        }
    } else {
        fputcsv($output, ['ID', 'Name', 'Abbreviation', 'Materia Medica', 'Clinical Indications', 'Better Modalities', 'Worse Modalities']);
        
        $stmt = $pdo->query("SELECT * FROM remedies ORDER BY name");
        while ($remedy = $stmt->fetch()) {
            $modalities = json_decode($remedy['modalities'], true);
            fputcsv($output, [
                $remedy['id'],
                $remedy['name'],
                $remedy['abbreviation'],
                strip_tags($remedy['materia_medica_text']),
                $remedy['clinical_indications'],
                implode('; ', $modalities['better'] ?? []),
                implode('; ', $modalities['worse'] ?? [])
            ]);
        }
    }
    fclose($output);
    
} elseif ($format == 'json') {
    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename="remedies_export_' . date('Y-m-d') . '.json"');
    
    $stmt = $pdo->query("SELECT * FROM remedies ORDER BY name");
    $remedies = $stmt->fetchAll();
    
    foreach ($remedies as &$remedy) {
        $remedy['modalities'] = json_decode($remedy['modalities'], true);
    }
    
    echo json_encode($remedies, JSON_PRETTY_PRINT);
}
exit;
?>