<?php
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
ob_start();

require_once '../db.php';
header('Content-Type: application/json');

$action = $_POST['action'] ?? '';
$visit_id = (int)($_POST['visit_id'] ?? 0);

$sys = $conn->query("SELECT date_format, time_format FROM system_workflow_rules LIMIT 1")->fetch_assoc();
$df = $sys['date_format'] ?? 'd-M-Y';
$tf = ($sys['time_format'] == '24') ? 'H:i' : 'h:i A';
$global_date_format = "$df, $tf";

if ($action === 'generate_clinical_report') {
    $type = $_POST['report_type'];
    $response = ['status' => 'success', 'chartData' => null, 'tableHtml' => ''];

    if ($type === 'Report: Vital Signs Flowsheet') {
        $response['title'] = 'Vital Signs Flowsheet';
        $q = $conn->query("SELECT recorded_at, field_name, field_value FROM ipd_dynamic_responses WHERE visit_id=$visit_id AND field_name IN ('Temperature (°C)', 'Pulse (/min)', 'Systolic BP (mmHg)', 'Diastolic BP (mmHg)', 'SpO2 (%)', 'Respiration (/min)') AND is_deleted=0 ORDER BY recorded_at ASC");
        
        $timestamps = [];
        $datasets = ['Temperature (°C)' => [], 'Pulse (/min)' => [], 'Systolic BP (mmHg)' => [], 'Diastolic BP (mmHg)' => [], 'SpO2 (%)' => [], 'Respiration (/min)' => []];
        $table = "<table class='table table-sm table-bordered text-center align-middle'><thead class='table-light'><tr><th>Date / Time</th><th>Temp (°C)</th><th>Pulse (/min)</th><th>BP (mmHg)</th><th>SpO2 (%)</th><th>Resp (/min)</th></tr></thead><tbody>";

        $grouped = [];
        while($r = $q->fetch_assoc()) {
            $time = date($global_date_format, strtotime($r['recorded_at']));
            $grouped[$time][$r['field_name']] = $r['field_value'];
        }

        foreach($grouped as $time => $vals) {
            $timestamps[] = $time;
            $datasets['Temperature (°C)'][] = isset($vals['Temperature (°C)']) ? (float)$vals['Temperature (°C)'] : null;
            $datasets['Pulse (/min)'][] = isset($vals['Pulse (/min)']) ? (float)$vals['Pulse (/min)'] : null;
            $datasets['Systolic BP (mmHg)'][] = isset($vals['Systolic BP (mmHg)']) ? (float)$vals['Systolic BP (mmHg)'] : null;
            $datasets['SpO2 (%)'][] = isset($vals['SpO2 (%)']) ? (float)$vals['SpO2 (%)'] : null;

            $bp = (isset($vals['Systolic BP (mmHg)']) && isset($vals['Diastolic BP (mmHg)'])) ? $vals['Systolic BP (mmHg)'].'/'.$vals['Diastolic BP (mmHg)'] : '-';
            $table .= "<tr><td class='fw-bold text-muted'>{$time}</td><td class='text-danger fw-bold'>".($vals['Temperature (°C)'] ?? '-')."</td><td class='text-primary fw-bold'>".($vals['Pulse (/min)'] ?? '-')."</td><td class='text-dark fw-bold'>{$bp}</td><td class='text-info fw-bold'>".($vals['SpO2 (%)'] ?? '-')."</td><td class='text-secondary fw-bold'>".($vals['Respiration (/min)'] ?? '-')."</td></tr>";
        }
        $table .= "</tbody></table>";

        if(!empty($timestamps)) {
            $response['chartType'] = 'line';
            $response['chartData'] = [
                'labels' => $timestamps,
                'datasets' => [
                    ['label' => 'Temperature (°C)', 'data' => $datasets['Temperature (°C)'], 'borderColor' => '#dc3545', 'backgroundColor'=> 'rgba(220, 53, 69, 0.1)', 'tension' => 0.4, 'spanGaps' => true, 'fill' => true],
                    ['label' => 'Pulse (bpm)', 'data' => $datasets['Pulse (/min)'], 'borderColor' => '#0d6efd', 'backgroundColor'=> 'transparent', 'tension' => 0.4, 'spanGaps' => true]
                ]
            ];
        } else {
            $table = "<div class='p-5 text-center text-muted'>No vital signs have been charted yet.</div>";
        }
        $response['tableHtml'] = $table;
    } 
    elseif ($type === 'Report: Fluid IO Chart') {
        $response['title'] = 'Fluid Intake / Output Chart';
        $q = $conn->query("SELECT f.fluid_type, f.volume_ml, f.recorded_at, t.fluid_category FROM ipd_fluid_charts f LEFT JOIN ipd_setup_fluid_types t ON f.fluid_type = t.fluid_name WHERE f.visit_id = $visit_id AND f.is_deleted=0 ORDER BY f.recorded_at ASC");
        $timestamps = []; $inData = []; $outData = [];
        $table = "<table class='table table-sm table-bordered text-center align-middle'><thead class='table-light'><tr><th>Date / Time</th><th>Fluid Category</th><th>Fluid Type</th><th>Volume (ml)</th></tr></thead><tbody>";

        $grouped = [];
        while($r = $q->fetch_assoc()) {
            $time = date($global_date_format, strtotime($r['recorded_at']));
            $day = date('d M Y', strtotime($r['recorded_at']));
            if(!isset($grouped[$day])) { $grouped[$day] = ['IN' => 0, 'OUT' => 0]; }
            $cat = $r['fluid_category'] ?? 'Intake'; 
            if($cat === 'Intake') { $grouped[$day]['IN'] += $r['volume_ml']; } else { $grouped[$day]['OUT'] += $r['volume_ml']; }

            $catBadge = $cat === 'Intake' ? "<span class='badge bg-info'>IN</span>" : "<span class='badge bg-warning text-dark'>OUT</span>";
            $volColor = $cat === 'Intake' ? "text-info" : "text-warning";
            $table .= "<tr><td class='fw-bold text-muted'>{$time}</td><td>{$catBadge}</td><td>{$r['fluid_type']}</td><td class='fw-bold {$volColor}'>{$r['volume_ml']} ml</td></tr>";
        }
        $table .= "</tbody></table>";

        foreach($grouped as $day => $v) { $timestamps[] = $day; $inData[] = $v['IN']; $outData[] = $v['OUT']; }

        if(!empty($timestamps)) {
            $response['chartType'] = 'bar';
            $response['chartData'] = ['labels' => $timestamps, 'datasets' => [['label' => 'Total Intake (ml)', 'data' => $inData, 'backgroundColor' => '#0dcaf0'],['label' => 'Total Output (ml)', 'data' => $outData, 'backgroundColor' => '#ffc107']]];
        } else {
            $table = "<div class='p-5 text-center text-muted'>No fluids have been charted yet.</div>";
        }
        $response['tableHtml'] = $table;
    }
    elseif ($type === 'Report: Medication Chart') {
        $response['title'] = 'Medication Administration Chart (MAR)';
        $q = $conn->query("SELECT m.administered_dose, m.status, m.remarks, m.administered_at, s.first_name, s.last_name, p.drug_name, p.dose, p.frequency FROM ipd_medication_charts m JOIN clinical_prescriptions p ON m.prescription_id = p.id LEFT JOIN staff s ON m.administered_by = s.staff_id WHERE m.visit_id = $visit_id AND m.is_deleted=0 ORDER BY m.administered_at DESC");
        if($q->num_rows > 0) {
            $table = "<table class='table table-sm table-bordered align-middle'><thead class='table-light'><tr><th>Date & Time</th><th>Medication Details</th><th>Dose Given</th><th>Status</th><th>Remarks</th><th>Administered By</th></tr></thead><tbody>";
            while($r = $q->fetch_assoc()) {
                $badge = ($r['status'] == 'Given' || $r['status'] == 'Administered Successfully') ? 'bg-success' : 'bg-danger';
                $doseGiven = !empty($r['administered_dose']) ? $r['administered_dose'] : $r['dose'];
                $table .= "<tr><td class='fw-bold text-muted' style='white-space:nowrap;'>".date($global_date_format, strtotime($r['administered_at']))."</td><td><b class='text-primary'>{$r['drug_name']}</b><br><span class='small fw-bold'>Prescribed: {$r['dose']} {$r['frequency']}</span></td><td class='fw-bold text-dark'>{$doseGiven}</td><td><span class='badge {$badge}'>{$r['status']}</span></td><td>{$r['remarks']}</td><td class='small'>Nurse {$r['first_name']} {$r['last_name']}</td></tr>";
            }
            $table .= "</tbody></table>";
            $response['tableHtml'] = $table;
        } else {
            $response['tableHtml'] = "<div class='p-5 text-center text-muted'>No medications have been administered/charted yet.</div>";
        }
    }
    ob_end_clean(); echo json_encode($response); exit;
}
?>