<?php
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ob_start();

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

$staff_id = (int)($_SESSION['staff_id'] ?? 1);
$action = $_POST['action'] ?? '';

$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";

function getAge($dob) {
    if (empty($dob) || $dob === '0000-00-00') return 'N/A';
    $date = date_create($dob);
    if (!$date) return 'N/A';
    return date_diff($date, date_create('today'))->y;
}

try {
    // ==========================================
    // AUTO-HEALING: UPGRADE THEATRE TABLE
    // ==========================================
    $checkCols = $conn->query("SHOW COLUMNS FROM ipd_theatre_requests LIKE 'scheduled_date'");
    if ($checkCols && $checkCols->num_rows == 0) {
        $conn->query("ALTER TABLE `ipd_theatre_requests` 
            ADD COLUMN `scheduled_date` datetime DEFAULT NULL AFTER `status`,
            ADD COLUMN `completed_at` datetime DEFAULT NULL AFTER `scheduled_date`,
            ADD COLUMN `surgical_notes` text DEFAULT NULL AFTER `completed_at`,
            ADD COLUMN `anesthetist_id` int(10) UNSIGNED DEFAULT NULL AFTER `surgeon_id`");
    }

    // ==========================================
    // 1. FETCH KPIs
    // ==========================================
    if ($action === 'fetch_kpis') {
        $date_today = date('Y-m-d');
        $kpi = ['pending' => 0, 'scheduled_today' => 0, 'completed_today' => 0, 'emergencies' => 0];

        $q = $conn->query("SELECT 
            SUM(CASE WHEN status IN ('Pending', 'Scheduled', 'In Progress') THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN status = 'Scheduled' AND DATE(scheduled_date) = '$date_today' THEN 1 ELSE 0 END) as sch_today,
            SUM(CASE WHEN status = 'Completed' AND DATE(completed_at) = '$date_today' THEN 1 ELSE 0 END) as comp_today,
            SUM(CASE WHEN urgency = 'Emergency' AND status IN ('Pending', 'Scheduled', 'In Progress') THEN 1 ELSE 0 END) as emergencies
            FROM ipd_theatre_requests");
        
        if ($q && $row = $q->fetch_assoc()) {
            $kpi['pending'] = $row['pending'] ?? 0;
            $kpi['scheduled_today'] = $row['sch_today'] ?? 0;
            $kpi['completed_today'] = $row['comp_today'] ?? 0;
            $kpi['emergencies'] = $row['emergencies'] ?? 0;
        }

        ob_end_clean(); echo json_encode(['status' => 'success', 'data' => $kpi]); exit;
    }

    // ==========================================
    // 2. FETCH ACTIVE THEATRE QUEUE
    // ==========================================
    if ($action === 'fetch_active_queue') {
        $is_filtered = filter_var($_POST['is_filtered'] ?? 'false', FILTER_VALIDATE_BOOLEAN);
        $start_date = $_POST['start_date'] ?? '';
        $end_date = $_POST['end_date'] ?? '';
        $urgency = $_POST['urgency'] ?? 'ALL';

        $sql = "SELECT t.*, 
                       p.patient_no, p.first_name, p.last_name, p.dob, g.gender_name,
                       w.ward_name, b.bed_number, rm.room_number_or_name,
                       tr.room_name as theatre_room,
                       CONCAT(s.first_name, ' ', s.last_name) as surgeon_name,
                       CONCAT(a.first_name, ' ', a.last_name) as anesthetist_name,
                       CONCAT(req.first_name, ' ', req.last_name) as requester_name
                FROM ipd_theatre_requests t
                JOIN visit_master vm ON t.visit_id = vm.id
                JOIN patient p ON vm.patient_no = p.patient_no
                LEFT JOIN gender g ON p.gender_id = g.id
                LEFT JOIN ipd_admission_episodes e ON t.origin_episode_id = e.id
                LEFT JOIN ipd_wards w ON e.ward_id = w.id
                LEFT JOIN ipd_beds b ON t.origin_bed_id = b.id
                LEFT JOIN ipd_rooms rm ON e.room_id = rm.id
                LEFT JOIN ipd_setup_theatre_rooms tr ON t.room_id = tr.id
                LEFT JOIN staff s ON t.surgeon_id = s.staff_id
                LEFT JOIN staff a ON t.anesthetist_id = a.staff_id
                LEFT JOIN staff req ON t.requested_by = req.staff_id
                WHERE t.status IN ('Pending', 'Scheduled', 'In Progress')";

        if ($is_filtered) {
            if ($urgency !== 'ALL') $sql .= " AND t.urgency = '" . $conn->real_escape_string($urgency) . "'";
            if (!empty($start_date) && !empty($end_date)) $sql .= " AND DATE(t.created_at) BETWEEN '$start_date' AND '$end_date'";
        }

        $sql .= " ORDER BY t.created_at DESC";

        $res = $conn->query($sql);
        $data = [];
        if($res) {
            while($row = $res->fetch_assoc()) {
                $row['patient_name'] = trim($row['first_name'] . ' ' . $row['last_name']);
                $row['age'] = getAge($row['dob']);
                $row['initials'] = strtoupper(substr($row['first_name'], 0, 1) . substr($row['last_name'], 0, 1));
                $row['location_str'] = $row['ward_name'] ? $row['ward_name'] . ($row['room_number_or_name'] ? ' ('.$row['room_number_or_name'].')' : '') . ' - Bed ' . $row['bed_number'] : 'OPD / External';
                $row['requested_on'] = date($global_date_format, strtotime($row['created_at']));
                $row['scheduled_on'] = $row['scheduled_date'] ? date($global_date_format, strtotime($row['scheduled_date'])) : 'Awaiting Schedule';
                $row['safe_room'] = $row['theatre_room'] ?: 'Unassigned Theatre';
                $data[] = $row;
            }
        }

        ob_end_clean(); echo json_encode(['status' => 'success', 'data' => $data]); exit;
    }

    // ==========================================
    // 3. FETCH SURGICAL HISTORY
    // ==========================================
    if ($action === 'fetch_surgical_history') {
        $is_filtered = filter_var($_POST['is_filtered'] ?? 'false', FILTER_VALIDATE_BOOLEAN);
        if (!$is_filtered) {
            ob_end_clean(); echo json_encode(['status' => 'success', 'data' => []]); exit;
        }

        $start_date = $_POST['start_date'] ?? date('Y-m-d');
        $end_date = $_POST['end_date'] ?? date('Y-m-d');

        $sql = "SELECT t.*, 
                       p.patient_no, p.first_name, p.last_name,
                       tr.room_name as theatre_room,
                       CONCAT(s.first_name, ' ', s.last_name) as surgeon_name
                FROM ipd_theatre_requests t
                JOIN visit_master vm ON t.visit_id = vm.id
                JOIN patient p ON vm.patient_no = p.patient_no
                LEFT JOIN ipd_setup_theatre_rooms tr ON t.room_id = tr.id
                LEFT JOIN staff s ON t.surgeon_id = s.staff_id
                WHERE t.status = 'Completed' AND DATE(t.completed_at) BETWEEN '$start_date' AND '$end_date'
                ORDER BY t.completed_at DESC";

        $res = $conn->query($sql);
        $data = [];
        if($res) {
            while($row = $res->fetch_assoc()) {
                $row['patient_name'] = trim($row['first_name'] . ' ' . $row['last_name']);
                $row['completed_on'] = date($global_date_format, strtotime($row['completed_at']));
                $data[] = $row;
            }
        }

        ob_end_clean(); echo json_encode(['status' => 'success', 'data' => $data]); exit;
    }

    // ==========================================
    // 4. GET DROPDOWNS (Surgeons & Anesthetists)
    // ==========================================
    if ($action === 'get_theatre_staff') {
        $surgeons = []; $anes = [];
        
        $qStf = $conn->query("SELECT t.staff_id, s.first_name, s.last_name, r.role_name FROM ipd_setup_theatre_staff t JOIN staff s ON t.staff_id = s.staff_id JOIN ipd_setup_theatre_roles r ON t.role_id = r.id WHERE t.is_active=1");
        if($qStf && $qStf->num_rows > 0) {
            while($s = $qStf->fetch_assoc()) {
                $name = "Dr. " . trim($s['first_name'] . ' ' . $s['last_name']);
                if (stripos($s['role_name'], 'Surgeon') !== false) $surgeons[] = ['id' => $s['staff_id'], 'name' => $name];
                if (stripos($s['role_name'], 'Anes') !== false) $anes[] = ['id' => $s['staff_id'], 'name' => $name];
            }
        } else {
            // Fallback: Fetch all active doctors
            $qs = $conn->query("SELECT staff_id, first_name, last_name FROM staff WHERE is_doctor_id = 1 AND is_active = 1");
            if($qs) {
                while($s = $qs->fetch_assoc()) {
                    $name = "Dr. " . trim($s['first_name'] . ' ' . $s['last_name']);
                    $surgeons[] = ['id' => $s['staff_id'], 'name' => $name];
                    $anes[] = ['id' => $s['staff_id'], 'name' => $name];
                }
            }
        }
        ob_end_clean(); echo json_encode(['status' => 'success', 'surgeons' => $surgeons, 'anesthetists' => $anes]); exit;
    }

    // ==========================================
    // 5. SCHEDULE SURGERY
    // ==========================================
    if ($action === 'schedule_surgery') {
        $req_id = (int)$_POST['req_id'];
        $surg_id = (int)$_POST['surgeon_id'];
        $anes_id = !empty($_POST['anesthetist_id']) ? (int)$_POST['anesthetist_id'] : null;
        $sch_date = trim($_POST['scheduled_date']);

        $stmt = $conn->prepare("UPDATE ipd_theatre_requests SET status = 'Scheduled', surgeon_id = ?, anesthetist_id = ?, scheduled_date = ? WHERE id = ?");
        $stmt->bind_param("iisi", $surg_id, $anes_id, $sch_date, $req_id);
        
        if ($stmt->execute()) {
            ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Surgery successfully scheduled.']);
        } else {
            throw new Exception("Database error while scheduling surgery.");
        }
        exit;
    }

    // ==========================================
    // 6. COMPLETE SURGERY (AUTO-REVERT WARD BED)
    // ==========================================
    if ($action === 'complete_surgery') {
        $req_id = (int)$_POST['comp_req_id'];
        $notes = trim($_POST['surgical_notes']);

        $conn->begin_transaction();

        // 1. Mark Surgery as Completed
        $stmt = $conn->prepare("UPDATE ipd_theatre_requests SET status = 'Completed', completed_at = NOW(), surgical_notes = ? WHERE id = ?");
        $stmt->bind_param("si", $notes, $req_id);
        
        if (!$stmt->execute()) throw new Exception("Database error while updating surgery record.");

        // 2. Fetch Origin Details to Reactivate Patient in Ward
        $qOr = $conn->query("SELECT origin_episode_id, origin_bed_id, visit_id FROM ipd_theatre_requests WHERE id = $req_id");
        $or = $qOr->fetch_assoc();

        if ($or && $or['origin_episode_id']) {
            // Restore Episode Status back to Admitted from 'In Theatre'
            $conn->query("UPDATE ipd_admission_episodes SET status = 'Admitted' WHERE id = {$or['origin_episode_id']}");
            
            // Restore Bed Status back to Occupied from 'Undergoing Surgical Procedure'
            if($or['origin_bed_id']) {
                $conn->query("UPDATE ipd_beds SET bed_status_id = 2, bed_status = 'Occupied', occupancy_status = 'Occupied' WHERE id = {$or['origin_bed_id']}");
            }
        }

        // 3. Audit Log
        $ip_addr = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        $old_val = json_encode(['request_id' => $req_id, 'status' => 'In Theatre']);
        $new_val = json_encode(['request_id' => $req_id, 'status' => 'Completed', 'notes' => $notes]);
        $stmtAud = $conn->prepare("INSERT INTO system_audit_logs (staff_id, action_type, table_name, record_id, old_values, new_values, ip_address) VALUES (?, 'UPDATE', 'ipd_theatre_requests', ?, ?, ?, ?)");
        $strReq = (string)$req_id;
        $stmtAud->bind_param("issss", $staff_id, $strReq, $old_val, $new_val, $ip_addr);
        $stmtAud->execute();

        $conn->commit();
        ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Surgery completed successfully. Patient safely returned to active Ward Roster.']);
        exit;
    }

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