<?php
session_start();
require_once '../../includes/db.php';

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    $staff_id = $_SESSION['staff_id'] ?? null;

    // 1. Create a New Ward
    if ($action === 'create_ward') {
        $name = $_POST['ward_name'];
        $floor_id = !empty($_POST['floor_id']) ? (int)$_POST['floor_id'] : null;
        $ward_type = (int)$_POST['ward_type_id'];
        $dept_id = !empty($_POST['managing_department_id']) ? (int)$_POST['managing_department_id'] : null;
        $gender_id = !empty($_POST['gender_restriction_id']) ? (int)$_POST['gender_restriction_id'] : null;
        $min_age = (int)$_POST['min_age_restriction'];
        $max_age = (int)$_POST['max_age_restriction'];
        $manager_id = !empty($_POST['ward_manager_id']) ? (int)$_POST['ward_manager_id'] : null;

        // If no floor is provided, we default to 0 or bypass it based on your DB strictness.
        // Assuming your DB allows NULL for floor_id if block/floor structure isn't mapped yet.
        if($floor_id === null) {
            $stmt = $conn->prepare("INSERT INTO ipd_wards (ward_name, ward_type_id, managing_department_id, gender_restriction_id, min_age_restriction, max_age_restriction, ward_manager_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("siiiiiii", $name, $ward_type, $dept_id, $gender_id, $min_age, $max_age, $manager_id, $staff_id);
        } else {
            $stmt = $conn->prepare("INSERT INTO ipd_wards (ward_name, floor_id, ward_type_id, managing_department_id, gender_restriction_id, min_age_restriction, max_age_restriction, ward_manager_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("siiiiiiii", $name, $floor_id, $ward_type, $dept_id, $gender_id, $min_age, $max_age, $manager_id, $staff_id);
        }
        
        if ($stmt->execute()) {
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => $stmt->error]);
        }
        $stmt->close();
        exit;
    }

    // 2. Generate Rooms & Deploy Beds
    if ($action === 'generate_room_beds') {
        $ward_id = (int)$_POST['ward_id'];
        $room_type = (int)$_POST['room_type_id'];
        $room_name = $_POST['room_number_or_name'];
        $num_beds = (int)$_POST['number_of_beds'];

        // Begin Transaction for Data Integrity
        $conn->begin_transaction();

        try {
            // Step A: Create the physical Room grouping
            $stmtRoom = $conn->prepare("INSERT INTO ipd_rooms (ward_id, room_type_id, room_number_or_name, physical_bed_capacity, created_by) VALUES (?, ?, ?, ?, ?)");
            $stmtRoom->bind_param("iisii", $ward_id, $room_type, $room_name, $num_beds, $staff_id);
            $stmtRoom->execute();
            $new_room_id = $stmtRoom->insert_id;
            $stmtRoom->close();

            // Step B: The Bed Generator Loop (1 = Vacant status from ipd_setup_bed_statuses)
            $vacant_status_id = 1; 
            $stmtBed = $conn->prepare("INSERT INTO ipd_beds (room_id, bed_number, bed_status_id, created_by) VALUES (?, ?, ?, ?)");
            
            for ($i = 1; $i <= $num_beds; $i++) {
                $bed_name = "Bed " . $i;
                $stmtBed->bind_param("isii", $new_room_id, $bed_name, $vacant_status_id, $staff_id);
                $stmtBed->execute();
            }
            $stmtBed->close();

            // Step C: Automatically Update the Ward's total capacity metrics
            $conn->query("UPDATE ipd_wards SET physical_bed_capacity = physical_bed_capacity + $num_beds WHERE id = $ward_id");

            $conn->commit();
            echo json_encode(['status' => 'success', 'message' => "Successfully deployed $num_beds beds to $room_name."]);

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

    // 3. Map IPD Dynamic Helpers
    if ($action === 'map_ipd_helper') {
        $section = $_POST['section_name'];
        $label = $_POST['field_label'];
        $name = $_POST['field_name'];
        $type = $_POST['field_type'];
        $options = !empty($_POST['field_options']) ? $_POST['field_options'] : null;
        $req = (int)$_POST['is_required'];

        // We utilize the existing consultation_form_setup structure to handle EAV mapping. 
        $stmt = $conn->prepare("INSERT INTO consultation_form_setup (section_name, field_label, field_name, field_type, field_options, is_required) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssi", $section, $label, $name, $type, $options, $req);
        
        if ($stmt->execute()) {
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => $stmt->error]);
        }
        $stmt->close();
        exit;
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Request Method.']);
    exit;
}
?>