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

require_once '../db.php';

header('Content-Type: application/json');

// ==============================================================================
// AJAX ENDPOINT: CANCEL PENDING ADMISSIONS
// ==============================================================================
if (isset($_POST['action']) && $_POST['action'] === 'cancel_pending_admission') {
    $request_id = (int)$_POST['request_id'];
    
    $stmt = $conn->prepare("UPDATE clinical_admission_requests SET status = 'Cancelled' WHERE id = ?");
    $stmt->bind_param("i", $request_id);
    
    if ($stmt->execute()) {
        ob_end_clean(); echo json_encode(['status' => 'success']); exit;
    } else {
        ob_end_clean(); echo json_encode(['status' => 'error', 'message' => 'Failed to cancel the request.']); exit;
    }
}

// ==============================================================================
// MAIN FORM SUBMISSION LOGIC FOR UPDATES
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['update_encounter'])) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => 'Invalid Submission. Expected update_encounter flag.']); exit;
}

$visit_id = (int)$_POST['visit_id'];
$patient_no = trim($_POST['patient_no']);
$doctor_id = !empty($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0; 

$dynamic_fields = $_POST['dynamic_fields'] ?? [];

$chief_complaint = trim($dynamic_fields['chief_complaint'] ?? '');
$clinical_history = trim($dynamic_fields['hpi_notes'] ?? '');
$examination_notes = trim($dynamic_fields['general_examination'] ?? '');
$base_treatment_plan = trim($dynamic_fields['treatment_plan'] ?? '');
$next_review = !empty($dynamic_fields['next_review_date']) ? $dynamic_fields['next_review_date'] : null;

$outcome = $_POST['clinical_outcome'] ?? 'Discharged';
if (stripos($outcome, 'Labs') !== false) {
    $visit_status = 'In Progress'; 
} else {
    $visit_status = 'Completed';
}

$conn->begin_transaction();

try {
    // 2. UPDATE VISIT MASTER
    $stmtVM = $conn->prepare("UPDATE visit_master SET status = ?, clinical_outcome = ?, next_review_date = ? WHERE id = ?");
    $stmtVM->bind_param("sssi", $visit_status, $outcome, $next_review, $visit_id);
    if (!$stmtVM->execute()) throw new Exception("Failed to update Visit Master.");

    // 3. OVERWRITE LEGACY CLINICAL NOTES 
    $conn->query("DELETE FROM clinical_notes WHERE visit_id = $visit_id");
    $stmtN = $conn->prepare("INSERT INTO clinical_notes (visit_id, patient_no, doctor_id, chief_complaint, clinical_history, examination_notes, treatment_plan_notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmtN->bind_param("issssss", $visit_id, $patient_no, $doctor_id, $chief_complaint, $clinical_history, $examination_notes, $base_treatment_plan);
    if (!$stmtN->execute()) throw new Exception("Failed to save Clinical Notes.");

    // 4. OVERWRITE DYNAMIC CLINICAL RESPONSES
    $conn->query("DELETE FROM clinical_dynamic_responses WHERE visit_id = $visit_id");
    if (!empty($dynamic_fields)) {
        $stmtDyn = $conn->prepare("INSERT INTO clinical_dynamic_responses (visit_id, patient_no, field_name, field_value, recorded_by) VALUES (?, ?, ?, ?, ?)");
        foreach ($dynamic_fields as $key => $value) {
            $val = is_array($value) ? implode(', ', $value) : trim($value); 
            if ($val !== '') {
                $stmtDyn->bind_param("isssi", $visit_id, $patient_no, $key, $val, $doctor_id);
                $stmtDyn->execute();
            }
        }
    }

    // 5. OVERWRITE DIAGNOSES (With Strict Principal Marker)
    $conn->query("DELETE FROM clinical_diagnoses WHERE visit_id = $visit_id");
    if (!empty($_POST['diag_code'])) {
        $stmtD = $conn->prepare("INSERT INTO clinical_diagnoses (visit_id, patient_no, code_type, code, description, diagnosis_type, is_principal, doctor_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        
        $principal_radio_val = $_POST['is_principal'] ?? null;
        $row_ids = $_POST['diag_row_id'] ?? [];
        
        foreach ($_POST['diag_code'] as $index => $code) {
            if (empty($code)) continue;
            
            $clean_code = explode(' - ', $code)[0];
            $type = $_POST['diag_type'][$index] ?? 'ICD-10';
            $desc = $_POST['diag_desc'][$index] ?? '';
            $status = $_POST['diag_status'][$index] ?? 'New';
            
            $current_row_id = $row_ids[$index] ?? $index;
            $is_princ = ($current_row_id == $principal_radio_val) ? 1 : 0; 
            
            $stmtD->bind_param("isssssii", $visit_id, $patient_no, $type, $clean_code, $desc, $status, $is_princ, $doctor_id);
            $stmtD->execute();
        }
    }

    // 6. APPEND ONLY NEW PRESCRIPTIONS (Never delete old Rx in updates to protect pharmacy billing)
    if (!empty($_POST['rx_drug'])) {
        $dispensary = $_POST['dispensing_pharmacy'] ?? 'Main Pharmacy';
        $stmtRx = $conn->prepare("INSERT INTO clinical_prescriptions (visit_id, patient_no, service_id, drug_name, formulation, strength, dose, frequency, duration_days, quantity, dispensing_pharmacy, remarks, prescribed_by, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending Pharmacy')");
        
        foreach ($_POST['rx_drug'] as $index => $drug_compound) {
            if (empty($drug_compound)) continue;
            
            $parts = explode('||', $drug_compound);
            $service_id = isset($parts[0]) && is_numeric($parts[0]) ? (int)$parts[0] : null;
            $drug_name = isset($parts[1]) ? $parts[1] : $drug_compound;

            $form = $_POST['rx_form'][$index] ?? '';
            $strength = $_POST['rx_strength'][$index] ?? '';
            $dose = $_POST['rx_dose'][$index] ?? '';
            $freq = $_POST['rx_freq'][$index] ?? '';
            $dur = (int)($_POST['rx_dur'][$index] ?? 0);
            $qty = (int)($_POST['rx_qty'][$index] ?? 0);
            $rem = $_POST['rx_remarks'][$index] ?? '';
            
            $stmtRx->bind_param("isisssssiissi", $visit_id, $patient_no, $service_id, $drug_name, $form, $strength, $dose, $freq, $dur, $qty, $dispensary, $rem, $doctor_id);
            $stmtRx->execute();
        }
    }

    // 7. OVERWRITE ENCOUNTER HELPERS
    $conn->query("DELETE FROM clinical_encounter_helpers WHERE visit_id = $visit_id");
    if (!empty($_POST['procedure_helpers'])) {
        $stmtH = $conn->prepare("INSERT INTO clinical_encounter_helpers (visit_id, staff_name) VALUES (?, ?)");
        foreach ($_POST['procedure_helpers'] as $helper) {
            if (empty($helper)) continue;
            $stmtH->bind_param("is", $visit_id, $helper);
            $stmtH->execute();
        }
    }

    // 8. ADMISSION ROUTING (With Guardrails)
    if (stripos($outcome, 'Admission') !== false && !empty($_POST['admit_ward'])) {
        
        // Gatekeeper: Reject if patient is already actively admitted
        $chkActive = $conn->prepare("SELECT id, ward_id, (SELECT ward_name FROM ipd_wards WHERE id = ward_id) as ward_name FROM ipd_admission_episodes WHERE patient_no = ? AND status IN ('Admitted', 'Transferred') LIMIT 1");
        $chkActive->bind_param("s", $patient_no);
        $chkActive->execute();
        $resActive = $chkActive->get_result();
        if ($resActive->num_rows > 0) {
            $act = $resActive->fetch_assoc();
            throw new Exception("Patient is already admitted to {$act['ward_name']}. You cannot create a new admission recommendation until they are discharged.");
        }
        $chkActive->close();

        // Gatekeeper: Reject if another pending request exists that wasn't cancelled
        $chkPending = $conn->prepare("SELECT id FROM clinical_admission_requests WHERE patient_no = ? AND status = 'Pending' AND visit_master_id != ?");
        $chkPending->bind_param("si", $patient_no, $visit_id);
        $chkPending->execute();
        if ($chkPending->get_result()->num_rows > 0) {
            throw new Exception("Patient already has a pending admission recommendation in the queue. Please cancel it from the Update Module first.");
        }
        $chkPending->close();

        // Safe to Insert/Update
        $conn->query("DELETE FROM clinical_admission_requests WHERE visit_master_id = $visit_id AND status = 'Pending'");
        
        $stmtAdm = $conn->prepare("INSERT INTO clinical_admission_requests (visit_master_id, patient_no, requested_ward, admission_diagnosis, treatment_plan, requested_by) VALUES (?, ?, ?, ?, ?, ?)");
        
        $ward = $_POST['admit_ward'];
        $diag = trim($_POST['admit_diag'] ?? '');
        
        // Auto-pull Principal Diagnosis if left blank
        if(empty($diag)) {
            $principal_radio_val = $_POST['is_principal'] ?? null;
            $row_ids = $_POST['diag_row_id'] ?? [];
            foreach ($_POST['diag_code'] as $index => $code) {
                if (empty($code)) continue;
                $current_row_id = $row_ids[$index] ?? $index;
                if ($current_row_id == $principal_radio_val) {
                    $diag_parts = explode(' - ', $code);
                    $diag = isset($diag_parts[1]) ? trim($diag_parts[1]) : trim($diag_parts[0]);
                    break;
                }
            }
        }
        if(empty($diag)) $diag = "Undetermined - Check Clinical Notes";
        
        // Pull Ward Instructions
        $ward_plan = trim($_POST['ward_instructions'] ?? '');
        if(empty($ward_plan)) $ward_plan = $base_treatment_plan; 
        
        $stmtAdm->bind_param("issssi", $visit_id, $patient_no, $ward, $diag, $ward_plan, $doctor_id);
        $stmtAdm->execute();
        
    } else {
        // Discharged/Referred Out -> wipe any pending admissions tied to this visit
        $conn->query("DELETE FROM clinical_admission_requests WHERE visit_master_id = $visit_id AND status = 'Pending'");
    }

    // 9. APPEND ONLY NEW AUTOMATICALLY ROUTED SERVICE REQUESTS
    if (!empty($_POST['lab_test'])) {
        $stmtQueue = $conn->prepare("INSERT INTO service_request_queue (visit_id, patient_no, service_id, requested_by, priority, payment_status, current_stage) VALUES (?, ?, ?, ?, 'Routine', 'Unpaid', 'Pending Payment')");
        $stmtLab = $conn->prepare("INSERT INTO clinical_lab_requests (visit_id, patient_no, department_id, service_id, test_name, requested_by, status) VALUES (?, ?, ?, ?, ?, ?, 'Pending')");
        
        foreach ($_POST['lab_test'] as $index => $test_compound) {
            if (empty($test_compound)) continue;
            
            $parts = explode('||', $test_compound);
            $service_id = isset($parts[0]) && is_numeric($parts[0]) ? (int)$parts[0] : null;
            $test_name = isset($parts[1]) ? $parts[1] : $test_compound;
            $dept_id = !empty($_POST['lab_dept_id'][$index]) ? (int)$_POST['lab_dept_id'][$index] : 0;
            
            if ($service_id) {
                $stmtQueue->bind_param("isii", $visit_id, $patient_no, $service_id, $doctor_id);
                $stmtQueue->execute();
            }
            $stmtLab->bind_param("isiisi", $visit_id, $patient_no, $dept_id, $service_id, $test_name, $doctor_id);
            $stmtLab->execute();
        }
    }

    $conn->commit();
    ob_end_clean();
    echo json_encode(['status' => 'success', 'message' => 'Encounter successfully updated and signed off.']);
    exit;

} catch (Exception $e) {
    $conn->rollback();
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    exit;
}
?>