<?php
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once __DIR__ . '/../db/config.php';
    require_once __DIR__ . '/../helpers.php';
    $db = db();


    // Check for post_max_size overflow
    if (empty($_POST) && empty($_FILES) && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
        $_SESSION['flash_message'] = 'Error: File too large (exceeds post_max_size).';
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit;
    }

    function parse_import_file($file_input) {
        if (!isset($file_input['error']) || $file_input['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['import_error'] = 'Upload error code: ' . ($file_input['error'] ?? 'unknown');
            return false;
        }
        $ext = strtolower(pathinfo($file_input['name'], PATHINFO_EXTENSION));
        $rows = [];
        
        if ($ext === 'csv') {
            $handle = fopen($file_input['tmp_name'], 'r');
            if ($handle === false) {
                $_SESSION['import_error'] = 'Failed to open CSV file.';
                return false;
            }
            # Skip header
            fgetcsv($handle);
            while (($row = fgetcsv($handle)) !== false) {
                if (array_filter($row)) {
                    $rows[] = $row;
                }
            }
            fclose($handle);
            if (empty($rows)) {
                 $_SESSION['import_error'] = 'CSV file is empty or could not be parsed.';
            }
        } elseif ($ext === 'xlsx' || $ext === 'xls') {
            require_once __DIR__ . '/SimpleXLSX.php';
            if ($xlsx = \Shuchkin\SimpleXLSX::parse($file_input['tmp_name'])) {
                $rows = $xlsx->rows();
                array_shift($rows); # Skip header
                if (empty($rows)) {
                    $_SESSION['import_error'] = 'Excel file is empty.';
                }
            } else {
                $_SESSION['import_error'] = 'SimpleXLSX Error: ' . \Shuchkin\SimpleXLSX::parseError();
                return false;
            }
        } else {
            $_SESSION['import_error'] = "Unsupported file extension: $ext. Please upload .csv or .xlsx";
            return false;
        }
        return $rows;
    }


    function upload_file($file_array, $index, $target_dir = "assets/uploads/") { 
        if (!isset($file_array["name"][$index]) || $file_array["error"][$index] !== UPLOAD_ERR_OK) { 
            return null; 
        } 
        if (!is_dir(__DIR__ . "/../" . $target_dir)) { 
            mkdir(__DIR__ . "/../" . $target_dir, 0775, true); 
        } 
        $filename = time() . "_" . basename($file_array["name"][$index]); 
        $target_file = $target_dir . $filename; 
        if (move_uploaded_file($file_array["tmp_name"][$index], __DIR__ . "/../" . $target_file)) { 
            return $target_file; 
        } 
        return null; 
    }

    function upload_multiple_files_key($key_name, $target_dir = "assets/uploads/") {
        $uploaded = [];
        if (!isset($_FILES[$key_name])) return [];
        
        $files = $_FILES[$key_name];
        // Normalize array structure
        if (is_array($files['name'])) {
            $count = count($files['name']);
            if (!is_dir(__DIR__ . "/../" . $target_dir)) { 
                mkdir(__DIR__ . "/../" . $target_dir, 0775, true); 
            }
            for ($i = 0; $i < $count; $i++) {
                if ($files['error'][$i] === UPLOAD_ERR_OK) {
                    $filename = time() . "_" . uniqid() . "_" . basename($files['name'][$i]);
                    $target_file = $target_dir . $filename;
                    if (move_uploaded_file($files['tmp_name'][$i], __DIR__ . "/../" . $target_file)) {
                        $uploaded[] = ['name' => $files['name'][$i], 'path' => $target_file];
                    }
                }
            }
        }
        return $uploaded;
    }

    $lang = $_SESSION['lang'] ?? 'en';
    $redirect = false;

    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add_patient') {
            $name = $_POST['name'] ?? '';
            $phone = $_POST['phone'] ?? '';
            $dob = $_POST['dob'] ?: null;
            $gender = $_POST['gender'] ?? '';
            $blood_group = $_POST['blood_group'] ?? '';
            $insurance_company_id = $_POST['insurance_company_id'] ?: null;
            $policy_number = $_POST['policy_number'] ?? '';
            $address = $_POST['address'] ?? '';
            $civil_id = $_POST['civil_id'] ?? '';
            $nationality = $_POST['nationality'] ?? '';
            $city = $_POST['city'] ?? '';
            
            if ($name) {
                $stmt = $db->prepare("INSERT INTO patients (name, phone, dob, gender, blood_group, insurance_company_id, policy_number, address, civil_id, nationality, city) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $phone, $dob, $gender, $blood_group, $insurance_company_id, $policy_number, $address, $civil_id, $nationality, $city]);
                $_SESSION['flash_message'] = __('add_patient') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_patient') {
            $id = $_POST['id'] ?? '';
            $name = $_POST['name'] ?? '';
            $phone = $_POST['phone'] ?? '';
            $dob = $_POST['dob'] ?: null;
            $gender = $_POST['gender'] ?? '';
            $blood_group = $_POST['blood_group'] ?? '';
            $insurance_company_id = $_POST['insurance_company_id'] ?: null;
            $policy_number = $_POST['policy_number'] ?? '';
            $address = $_POST['address'] ?? '';
            $civil_id = $_POST['civil_id'] ?? '';
            $nationality = $_POST['nationality'] ?? '';
            $city = $_POST['city'] ?? '';
            
            if ($id && $name) {
                $stmt = $db->prepare("UPDATE patients SET name = ?, phone = ?, dob = ?, gender = ?, blood_group = ?, insurance_company_id = ?, policy_number = ?, address = ?, civil_id = ?, nationality = ?, city = ? WHERE id = ?");
                $stmt->execute([$name, $phone, $dob, $gender, $blood_group, $insurance_company_id, $policy_number, $address, $civil_id, $nationality, $city, $id]);
                $_SESSION['flash_message'] = __('edit_patient') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_patient') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM patients WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_department') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $show_in_queue = isset($_POST['show_in_queue']) ? 1 : 0;
            $active = isset($_POST['active']) ? 1 : 0;
            $requires_vitals = isset($_POST['requires_vitals']) ? 1 : 0;
            $is_vitals_room = isset($_POST['is_vitals_room']) ? 1 : 0;
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO departments (name_en, name_ar, show_in_queue, active, requires_vitals, is_vitals_room) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $show_in_queue, $active, $requires_vitals, $is_vitals_room]);
                $_SESSION['flash_message'] = __('add_department') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_department') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $show_in_queue = isset($_POST['show_in_queue']) ? 1 : 0;
            $active = isset($_POST['active']) ? 1 : 0;
            $requires_vitals = isset($_POST['requires_vitals']) ? 1 : 0;
            $is_vitals_room = isset($_POST['is_vitals_room']) ? 1 : 0;
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE departments SET name_en = ?, name_ar = ?, show_in_queue = ?, active = ?, requires_vitals = ?, is_vitals_room = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $show_in_queue, $active, $requires_vitals, $is_vitals_room, $id]);
                $_SESSION['flash_message'] = __('edit_department') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_department') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM departments WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_city') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO cities (name_en, name_ar) VALUES (?, ?)");
                $stmt->execute([$name_en, $name_ar]);
                $_SESSION['flash_message'] = __('add_city') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_city') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE cities SET name_en = ?, name_ar = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $id]);
                $_SESSION['flash_message'] = __('edit_city') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_city') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM cities WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'book_appointment') {
            $patient_id = $_POST['patient_id'] ?? '';
            $doctor_id = $_POST['doctor_id'] ?? '';
            $date = $_POST['date'] ?? '';
            $reason = $_POST['reason'] ?? '';
            
            if ($patient_id && $doctor_id && $date) {
                $stmt = $db->prepare("INSERT INTO appointments (patient_id, doctor_id, start_time, end_time, reason) VALUES (?, ?, ?, DATE_ADD(?, INTERVAL 30 MINUTE), ?)");
                $stmt->execute([$patient_id, $doctor_id, $date, $date, $reason]);
                $_SESSION['flash_message'] = __('book_appointment') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'record_visit') {
            $patient_id = $_POST['patient_id'] ?? '';
            $doctor_id = $_POST['doctor_id'] ?: null; // Nullable
            $nurse_id = $_POST['nurse_id'] ?: null; // Nullable
            $visit_type = $_POST['visit_type'] ?? 'Clinic';
            $appointment_id = $_POST['appointment_id'] ?: null;
            $weight = $_POST['weight'] ?? '';
            $bp = $_POST['blood_pressure'] ?? '';
            $hr = $_POST['heart_rate'] ?? '';
            $temp = $_POST['temperature'] ?? '';
            $symptoms = $_POST['symptoms'] ?? '';
            $diagnosis = $_POST['diagnosis'] ?? '';
            $treatment = $_POST['treatment_plan'] ?? '';
            $nursing_notes = $_POST['nursing_notes'] ?? '';
$sick_leave_start_date = !empty($_POST['sick_leave_start_date']) ? $_POST['sick_leave_start_date'] : null;
            $sick_leave_days = !empty($_POST['sick_leave_days']) ? (int)$_POST['sick_leave_days'] : null;
            $sick_leave_remarks = $_POST['sick_leave_remarks'] ?? null;
            
            if ($patient_id && ($doctor_id || $nurse_id)) {
                $db->beginTransaction();
                
                // Fetch address from appointment if not provided via some other means
                // For now, we rely on appointment_id if present to get the address
                $address = null;
                if ($appointment_id) {
                    $stmtApt = $db->prepare("SELECT address FROM appointments WHERE id = ?");
                    $stmtApt->execute([$appointment_id]);
                    $apt = $stmtApt->fetch();
                    $address = $apt['address'] ?? null;
                }

                $stmt = $db->prepare("INSERT INTO visits (patient_id, doctor_id, nurse_id, visit_type, address, appointment_id, weight, blood_pressure, heart_rate, temperature, symptoms, diagnosis, treatment_plan, nursing_notes, sick_leave_start_date, sick_leave_days, sick_leave_remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$patient_id, $doctor_id, $nurse_id, $visit_type, $address, $appointment_id, $weight, $bp, $hr, $temp, $symptoms, $diagnosis, $treatment, $nursing_notes, $sick_leave_start_date, $sick_leave_days, $sick_leave_remarks]);
                $visit_id = $db->lastInsertId();
                $token_message = '';
                
                // Token Generation (Only for Doctor visits in Clinic usually)
                if (isset($_POST['generate_token']) && $_POST['generate_token'] == '1' && $doctor_id) {
                    // Updated to query employees table
                    $stmtDoc = $db->prepare("SELECT department_id FROM employees WHERE id = ?");
                    $stmtDoc->execute([$doctor_id]);
                    $docData = $stmtDoc->fetch();
                    $dept_id = $docData ? $docData['department_id'] : null;
                    
                    if ($dept_id) {
                        $today = date('Y-m-d');
                        $stmtTok = $db->prepare("SELECT MAX(token_number) FROM patient_queue WHERE department_id = ? AND DATE(created_at) = ?");
                        $stmtTok->execute([$dept_id, $today]);
                        $max_token = $stmtTok->fetchColumn();
                        $next_token = ($max_token) ? $max_token + 1 : 1;
                        
                        $stmtQueue = $db->prepare("INSERT INTO patient_queue (patient_id, department_id, doctor_id, visit_id, token_number, status, created_at) VALUES (?, ?, ?, ?, ?, 'waiting', NOW())");
                        $stmtQueue->execute([$patient_id, $dept_id, $doctor_id, $visit_id, $next_token]);
                        $queue_id = $db->lastInsertId();
                        $_SESSION['print_token_id'] = $queue_id;
                        
                        $token_message = " (" . __('token') . ": #" . $next_token . ")";
                    }
                }
                if (isset($_POST['prescriptions']) && is_array($_POST['prescriptions'])) {
                    $drug_names = $_POST['prescriptions']['drug_name'] ?? [];
                    $dosages = $_POST['prescriptions']['dosage'] ?? [];
                    $instructions = $_POST['prescriptions']['instructions'] ?? [];
                    $pStmt = $db->prepare("INSERT INTO visit_prescriptions (visit_id, drug_name, dosage, instructions) VALUES (?, ?, ?, ?)");
                    foreach ($drug_names as $i => $drug) {
                        if (!empty($drug)) {
                            $pStmt->execute([$visit_id, $drug, $dosages[$i] ?? '', $instructions[$i] ?? '']);
                        }
                    }
                }
                
                if ($appointment_id) {
                    $stmt = $db->prepare("UPDATE appointments SET status = 'Completed' WHERE id = ?");
                    $stmt->execute([$appointment_id]);
                }

                // Auto-create bill if requested (e.g. from Home Visits)
                if (isset($_POST['create_bill']) && $_POST['create_bill'] == '1') {
                    $stmtIns = $db->prepare("SELECT insurance_company_id FROM patients WHERE id = ?");
                    $stmtIns->execute([$patient_id]);
                    $patient = $stmtIns->fetch();
                    
                    $total = 0; 
                    $insurance_covered = 0;
                    $patient_payable = 0;

                    $stmtBill = $db->prepare("INSERT INTO bills (patient_id, visit_id, total_amount, insurance_covered, patient_payable, status) VALUES (?, ?, ?, ?, ?, 'Pending')");
                    $stmtBill->execute([$patient_id, $visit_id, $total, $insurance_covered, $patient_payable]);
                    $bill_id = $db->lastInsertId();
                    
                    $stmtItem = $db->prepare("INSERT INTO bill_items (bill_id, description, amount) VALUES (?, ?, ?)");
                    $stmtItem->execute([$bill_id, 'Home Visit Service', 0]);
                }

                $db->commit();
                $_SESSION['flash_message'] = __('add_visit') . ' ' . __('successfully') . $token_message;
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_visit') {
            $id = $_POST['id'] ?? '';
            // Note: patient_id is not updated as it should be immutable
            $doctor_id = $_POST['doctor_id'] ?: null;
            $weight = $_POST['weight'] ?? '';
            $bp = $_POST['blood_pressure'] ?? '';
            $hr = $_POST['heart_rate'] ?? '';
            $temp = $_POST['temperature'] ?? '';
            $symptoms = $_POST['symptoms'] ?? '';
            $diagnosis = $_POST['diagnosis'] ?? '';
            $treatment = $_POST['treatment_plan'] ?? '';
            $nursing_notes = $_POST['nursing_notes'] ?? '';
$sick_leave_start_date = !empty($_POST['sick_leave_start_date']) ? $_POST['sick_leave_start_date'] : null;
            $sick_leave_days = !empty($_POST['sick_leave_days']) ? (int)$_POST['sick_leave_days'] : null;
            $sick_leave_remarks = $_POST['sick_leave_remarks'] ?? null;
            
            // Check for 24h restriction
            $stmtSet = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = 'disable_visit_edit_24h'");
            $stmtSet->execute();
            $setting = $stmtSet->fetch();
            $disableEdit24h = ($setting && $setting['setting_value'] == '1');

            if ($disableEdit24h && $id) {
                $stmtDate = $db->prepare("SELECT visit_date FROM visits WHERE id = ?");
                $stmtDate->execute([$id]);
                $visit = $stmtDate->fetch();
                
                if ($visit) {
                    $visitDate = new DateTime($visit['visit_date']);
                    $now = new DateTime();
                    // If more than 24 hours (86400 seconds)
                    if (($now->getTimestamp() - $visitDate->getTimestamp()) > 86400) {
                        $_SESSION['flash_message'] = __('error') . ': ' . __('disable_visit_edit_24h_desc');
                        header("Location: " . $_SERVER['REQUEST_URI']);
                        exit;
                    }
                }
            }
            
            if ($id) {
                // Removed patient_id from UPDATE
                $stmt = $db->prepare("UPDATE visits SET doctor_id = ?, weight = ?, blood_pressure = ?, heart_rate = ?, temperature = ?, symptoms = ?, diagnosis = ?, treatment_plan = ?, nursing_notes = ?, sick_leave_start_date = ?, sick_leave_days = ?, sick_leave_remarks = ? WHERE id = ?");
                $stmt->execute([$doctor_id, $weight, $bp, $hr, $temp, $symptoms, $diagnosis, $treatment, $nursing_notes, $sick_leave_start_date, $sick_leave_days, $sick_leave_remarks, $id]);
                $stmt = $db->prepare("DELETE FROM visit_prescriptions WHERE visit_id = ?");
                $stmt->execute([$id]);
                if (isset($_POST['prescriptions']) && is_array($_POST['prescriptions'])) {
                    $drug_names = $_POST['prescriptions']['drug_name'] ?? [];
                    $dosages = $_POST['prescriptions']['dosage'] ?? [];
                    $instructions = $_POST['prescriptions']['instructions'] ?? [];
                    $pStmt = $db->prepare("INSERT INTO visit_prescriptions (visit_id, drug_name, dosage, instructions) VALUES (?, ?, ?, ?)");
                    foreach ($drug_names as $i => $drug) {
                        if (!empty($drug)) {
                            $pStmt->execute([$id, $drug, $dosages[$i] ?? '', $instructions[$i] ?? '']);
                        }
                    }
                }
                $_SESSION['flash_message'] = __('edit_visit') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_visit') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM visits WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'create_bill') {
            $patient_id = $_POST['patient_id'] ?? '';
            $visit_id = $_POST['visit_id'] ?: null;
            $items = $_POST['items'] ?? [];
            $amounts = $_POST['amounts'] ?? [];
            
            if ($patient_id && !empty($items)) {
                $db->beginTransaction();
                
                $total = array_sum($amounts);
                
                // Check if patient has insurance
                $stmt = $db->prepare("SELECT insurance_company_id FROM patients WHERE id = ?");
                $stmt->execute([$patient_id]);
                $patient = $stmt->fetch();
                
                $insurance_covered = 0;
                if ($patient && $patient['insurance_company_id']) {
                    $insurance_covered = $total * 0.8; // 80% coverage
                }
                $patient_payable = $total - $insurance_covered;
                
                $stmt = $db->prepare("INSERT INTO bills (patient_id, visit_id, total_amount, insurance_covered, patient_payable) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$patient_id, $visit_id, $total, $insurance_covered, $patient_payable]);
                $bill_id = $db->lastInsertId();
                
                $stmt = $db->prepare("INSERT INTO bill_items (bill_id, description, amount) VALUES (?, ?, ?)");
                foreach ($items as $index => $desc) {
                    if ($desc && isset($amounts[$index])) {
                        $stmt->execute([$bill_id, $desc, $amounts[$index]]);
                    }
                }
                
                $db->commit();
                $_SESSION['flash_message'] = __('create_bill') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'create_report') {
            $visit_id = $_POST['visit_id'] ?? '';
            $type = $_POST['report_type'] ?? '';
            $findings = $_POST['findings'] ?? '';
            $recom = $_POST['recommendations'] ?? '';
            
            if ($visit_id && $type) {
                $stmt = $db->prepare("INSERT INTO provisional_reports (visit_id, report_type, findings, recommendations) VALUES (?, ?, ?, ?)");
                $stmt->execute([$visit_id, $type, $findings, $recom]);
                $_SESSION['flash_message'] = __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_employee') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $dob = $_POST['dob'] ?: null;
            $mobile = $_POST['mobile'] ?? '';
            $email = $_POST['email'] ?? '';
            $room_number = $_POST['room_number'] ?? '';
            $dept_id = $_POST['department_id'] ?: null;
            $position_id = $_POST['position_id'] ?: null;
            
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO employees (name_en, name_ar, dob, mobile, email, room_number, department_id, position_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $dob, $mobile, $email, $room_number, $dept_id, $position_id]);
                $_SESSION['flash_message'] = __('add_employee') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_employee') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $dob = $_POST['dob'] ?: null;
            $mobile = $_POST['mobile'] ?? '';
            $email = $_POST['email'] ?? '';
            $room_number = $_POST['room_number'] ?? '';
            $dept_id = $_POST['department_id'] ?: null;
            $position_id = $_POST['position_id'] ?: null;
            
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE employees SET name_en = ?, name_ar = ?, dob = ?, mobile = ?, email = ?, room_number = ?, department_id = ?, position_id = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $dob, $mobile, $email, $room_number, $dept_id, $position_id, $id]);
                $_SESSION['flash_message'] = __('edit_employee') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_employee') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM employees WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_position') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $desc_en = $_POST['description_en'] ?? '';
            $desc_ar = $_POST['description_ar'] ?? '';
            
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO positions (name_en, name_ar, description_en, description_ar) VALUES (?, ?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $desc_en, $desc_ar]);
                $_SESSION['flash_message'] = __('add_position') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_position') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $desc_en = $_POST['description_en'] ?? '';
            $desc_ar = $_POST['description_ar'] ?? '';
            
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE positions SET name_en = ?, name_ar = ?, description_en = ?, description_ar = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $desc_en, $desc_ar, $id]);
                $_SESSION['flash_message'] = __('edit_position') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_position') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM positions WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_test_group') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO test_groups (name_en, name_ar) VALUES (?, ?)");
                $stmt->execute([$name_en, $name_ar]);
                $_SESSION['flash_message'] = __('add_test_group') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_test_group') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE test_groups SET name_en = ?, name_ar = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $id]);
                $_SESSION['flash_message'] = __('edit_test_group') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_test_group') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM test_groups WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_test') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $group_id = $_POST['group_id'] ?: null;
            $price = $_POST['price'] ?? 0;
            $range = $_POST['normal_range'] ?? '';
            
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO laboratory_tests (name_en, name_ar, group_id, price, normal_range) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $group_id, $price, $range]);
                $_SESSION['flash_message'] = __('add_test') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_test') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $group_id = $_POST['group_id'] ?: null;
            $price = $_POST['price'] ?? 0;
            $range = $_POST['normal_range'] ?? '';
            
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE laboratory_tests SET name_en = ?, name_ar = ?, group_id = ?, price = ?, normal_range = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $group_id, $price, $range, $id]);
                $_SESSION['flash_message'] = __('edit_test') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_test') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM laboratory_tests WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete_test') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_inquiry') {
            $patient_name = $_POST['patient_name'] ?? '';
            $test_ids = $_POST['test_ids'] ?? [];
            $results = $_POST['results'] ?? [];
            $source = $_POST['source'] ?? 'Internal';
            $date = $_POST['inquiry_date'] ?: date('Y-m-d H:i');
            $status = $_POST['status'] ?? 'Pending';
            $notes = $_POST['notes'] ?? '';
            
            if ($patient_name) {
                $db->beginTransaction();
                $stmt = $db->prepare("INSERT INTO laboratory_inquiries (patient_id, visit_id, patient_name, source, inquiry_date, status, notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$_POST['patient_id'] ?: null, $_POST['visit_id'] ?: null, $patient_name, $source, $date, $status, $notes]);
                $inquiry_id = $db->lastInsertId();
                
                if (!empty($test_ids)) {
                    $testStmt = $db->prepare("INSERT INTO inquiry_tests (inquiry_id, test_id, result, attachment) VALUES (?, ?, ?, ?)");
                    foreach ($test_ids as $index => $tid) {
                        if ($tid) {
                            $attachment = upload_file($_FILES['attachments'] ?? null, $index, "assets/uploads/labs/");
                            $testStmt->execute([$inquiry_id, $tid, $results[$index] ?? '', $attachment]);
                        }
                    }
                }
                $db->commit();
                $_SESSION['flash_message'] = __('add_inquiry') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_inquiry') {
            $id = $_POST['id'] ?? '';
            $patient_name = $_POST['patient_name'] ?? '';
            $test_ids = $_POST['test_ids'] ?? [];
            $results = $_POST['results'] ?? [];
            $existing_attachments = $_POST['existing_attachments'] ?? [];
            $source = $_POST['source'] ?? 'Internal';
            $date = $_POST['inquiry_date'] ?: date('Y-m-d H:i');
            $status = $_POST['status'] ?? 'Pending';
            $notes = $_POST['notes'] ?? '';
            
            if ($id && $patient_name) {
                $db->beginTransaction();
                $stmt = $db->prepare("UPDATE laboratory_inquiries SET patient_id = ?, visit_id = ?, patient_name = ?, source = ?, inquiry_date = ?, status = ?, notes = ? WHERE id = ?");
                $stmt->execute([$_POST['patient_id'] ?: null, $_POST['visit_id'] ?: null, $patient_name, $source, $date, $status, $notes, $id]);
                
                // Remove old tests and insert new ones
                $stmt = $db->prepare("DELETE FROM inquiry_tests WHERE inquiry_id = ?");
                $stmt->execute([$id]);
                
                if (!empty($test_ids)) {
                    $testStmt = $db->prepare("INSERT INTO inquiry_tests (inquiry_id, test_id, result, attachment) VALUES (?, ?, ?, ?)");
                    foreach ($test_ids as $index => $tid) {
                        if ($tid) {
                            $attachment = upload_file($_FILES['attachments'] ?? null, $index, "assets/uploads/labs/") ?: ($existing_attachments[$index] ?? null);
                            $testStmt->execute([$id, $tid, $results[$index] ?? '', $attachment]);
                        }
                    }
                }
                $db->commit();
                $_SESSION['flash_message'] = __('edit_inquiry') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_inquiry') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM laboratory_inquiries WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_xray_group') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO xray_groups (name_en, name_ar) VALUES (?, ?)");
                $stmt->execute([$name_en, $name_ar]);
                $_SESSION['flash_message'] = __('add_xray_group') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_xray_group') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE xray_groups SET name_en = ?, name_ar = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $id]);
                $_SESSION['flash_message'] = __('edit_xray_group') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_xray_group') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM xray_groups WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_xray_test') {
            $group_id = $_POST['group_id'] ?: null;
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $price = $_POST['price'] ?? 0;
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO xray_tests (group_id, name_en, name_ar, price) VALUES (?, ?, ?, ?)");
                $stmt->execute([$group_id, $name_en, $name_ar, $price]);
                $_SESSION['flash_message'] = __('add_xray_test') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_xray_test') {
            $id = $_POST['id'] ?? '';
            $group_id = $_POST['group_id'] ?: null;
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $price = $_POST['price'] ?? 0;
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE xray_tests SET group_id = ?, name_en = ?, name_ar = ?, price = ? WHERE id = ?");
                $stmt->execute([$group_id, $name_en, $name_ar, $price, $id]);
                $_SESSION['flash_message'] = __('edit_xray_test') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_xray_test') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM xray_tests WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_xray_inquiry') {
            $patient_name = $_POST['patient_name'] ?? '';
            $xray_ids = $_POST['xray_ids'] ?? [];
            $row_indices = $_POST['row_indices'] ?? []; // Maps array index to UI row index
            $results = $_POST['results'] ?? [];
            $source = $_POST['source'] ?? 'Internal';
            $date = $_POST['inquiry_date'] ?: date('Y-m-d H:i');
            $status = $_POST['status'] ?? 'Pending';
            $notes = $_POST['notes'] ?? '';
            if ($patient_name) {
                $db->beginTransaction();
                $stmt = $db->prepare("INSERT INTO xray_inquiries (patient_id, visit_id, patient_name, source, inquiry_date, status, notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$_POST['patient_id'] ?: null, $_POST['visit_id'] ?: null, $patient_name, $source, $date, $status, $notes]);
                $inquiry_id = $db->lastInsertId();
                if (!empty($xray_ids)) {
                    $testStmt = $db->prepare("INSERT INTO xray_inquiry_items (inquiry_id, xray_id, result, attachment) VALUES (?, ?, ?, ?)");
                    foreach ($xray_ids as $index => $tid) {
                        if ($tid) {
                            $rowIndex = $row_indices[$index] ?? $index;
                            $files = upload_multiple_files_key("new_attachments_" . $rowIndex, "assets/uploads/xrays/");
                            $attachmentJson = !empty($files) ? json_encode($files) : '';
                            $testStmt->execute([$inquiry_id, $tid, $results[$index] ?? '', $attachmentJson]);
                        }
                    }
                }
                $db->commit();
                $_SESSION['flash_message'] = __('add_xray_inquiry') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_xray_inquiry') {
            $id = $_POST['id'] ?? '';
            $patient_name = $_POST['patient_name'] ?? '';
            $xray_ids = $_POST['xray_ids'] ?? [];
            $row_indices = $_POST['row_indices'] ?? [];
            $results = $_POST['results'] ?? [];
            $source = $_POST['source'] ?? 'Internal';
            $date = $_POST['inquiry_date'] ?: date('Y-m-d H:i');
            $status = $_POST['status'] ?? 'Pending';
            $notes = $_POST['notes'] ?? '';
            if ($id && $patient_name) {
                $db->beginTransaction();
                $stmt = $db->prepare("UPDATE xray_inquiries SET patient_id = ?, visit_id = ?, patient_name = ?, source = ?, inquiry_date = ?, status = ?, notes = ? WHERE id = ?");
                $stmt->execute([$_POST['patient_id'] ?: null, $_POST['visit_id'] ?: null, $patient_name, $source, $date, $status, $notes, $id]);
                $stmt = $db->prepare("DELETE FROM xray_inquiry_items WHERE inquiry_id = ?");
                $stmt->execute([$id]);
                if (!empty($xray_ids)) {
                    $testStmt = $db->prepare("INSERT INTO xray_inquiry_items (inquiry_id, xray_id, result, attachment) VALUES (?, ?, ?, ?)");
                    foreach ($xray_ids as $index => $tid) {
                        if ($tid) {
                            $rowIndex = $row_indices[$index] ?? $index;
                            
                            // Get new files
                            $newFiles = upload_multiple_files_key("new_attachments_" . $rowIndex, "assets/uploads/xrays/");
                            
                            // Get existing files
                            $existingFiles = [];
                            if (isset($_POST['existing_attachments_' . $rowIndex])) {
                                foreach ($_POST['existing_attachments_' . $rowIndex] as $fileJson) {
                                    $file = json_decode($fileJson, true);
                                    if ($file) {
                                        $existingFiles[] = $file;
                                    }
                                }
                            }
                            
                            $allFiles = array_merge($existingFiles, $newFiles);
                            $attachmentJson = !empty($allFiles) ? json_encode($allFiles) : '';
                            
                            $testStmt->execute([$id, $tid, $results[$index] ?? '', $attachmentJson]);
                        }
                    }
                }
                $db->commit();
                $_SESSION['flash_message'] = __('edit_xray_inquiry') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_xray_inquiry') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM xray_inquiries WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_drug_group') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO drugs_groups (name_en, name_ar) VALUES (?, ?)");
                $stmt->execute([$name_en, $name_ar]);
                $_SESSION['flash_message'] = __('add_drug_group') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_drug_group') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE drugs_groups SET name_en = ?, name_ar = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $id]);
                $_SESSION['flash_message'] = __('edit_drug_group') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_drug_group') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM drugs_groups WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_drug') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $group_id = $_POST['group_id'] ?: null;
            $desc_en = $_POST['description_en'] ?? '';
            $desc_ar = $_POST['description_ar'] ?? '';
            $dosage = $_POST['default_dosage'] ?? '';
            $instructions = $_POST['default_instructions'] ?? '';
            $price = $_POST['price'] ?? 0;
            $expiry_date = $_POST['expiry_date'] ?: null;
            $supplier_id = $_POST['supplier_id'] ?: null;
            $image = upload_file($_FILES['image'] ?? [], 0, "assets/uploads/drugs/");
            
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO drugs (name_en, name_ar, group_id, description_en, description_ar, default_dosage, default_instructions, price, expiry_date, supplier_id, image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $group_id, $desc_en, $desc_ar, $dosage, $instructions, $price, $expiry_date, $supplier_id, $image]);
                $_SESSION['flash_message'] = __('add_drug') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_drug') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $group_id = $_POST['group_id'] ?: null;
            $desc_en = $_POST['description_en'] ?? '';
            $desc_ar = $_POST['description_ar'] ?? '';
            $dosage = $_POST['default_dosage'] ?? '';
            $instructions = $_POST['default_instructions'] ?? '';
            $price = $_POST['price'] ?? 0;
            $expiry_date = $_POST['expiry_date'] ?: null;
            $supplier_id = $_POST['supplier_id'] ?: null;
            $image = upload_file($_FILES['image'] ?? [], 0, "assets/uploads/drugs/");
            
            if ($id && $name_en && $name_ar) {
                if ($image) {
                     $stmt = $db->prepare("UPDATE drugs SET name_en = ?, name_ar = ?, group_id = ?, description_en = ?, description_ar = ?, default_dosage = ?, default_instructions = ?, price = ?, expiry_date = ?, supplier_id = ?, image = ? WHERE id = ?");
                     $stmt->execute([$name_en, $name_ar, $group_id, $desc_en, $desc_ar, $dosage, $instructions, $price, $expiry_date, $supplier_id, $image, $id]);
                } else {
                     $stmt = $db->prepare("UPDATE drugs SET name_en = ?, name_ar = ?, group_id = ?, description_en = ?, description_ar = ?, default_dosage = ?, default_instructions = ?, price = ?, expiry_date = ?, supplier_id = ? WHERE id = ?");
                     $stmt->execute([$name_en, $name_ar, $group_id, $desc_en, $desc_ar, $dosage, $instructions, $price, $expiry_date, $supplier_id, $id]);
                }
                $_SESSION['flash_message'] = __('edit_drug') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_drug') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM drugs WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_supplier') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $contact = $_POST['contact_person'] ?? '';
            $phone = $_POST['phone'] ?? '';
            $email = $_POST['email'] ?? '';
            $address = $_POST['address'] ?? '';
            $civil_id = $_POST['civil_id'] ?? '';
            $nationality = $_POST['nationality'] ?? '';
            $city = $_POST['city'] ?? '';
            
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO suppliers (name_en, name_ar, contact_person, phone, email, address) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $contact, $phone, $email, $address]);
                $_SESSION['flash_message'] = __('add_supplier') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_supplier') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $contact = $_POST['contact_person'] ?? '';
            $phone = $_POST['phone'] ?? '';
            $email = $_POST['email'] ?? '';
            $address = $_POST['address'] ?? '';
            $civil_id = $_POST['civil_id'] ?? '';
            $nationality = $_POST['nationality'] ?? '';
            $city = $_POST['city'] ?? '';
            
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE suppliers SET name_en = ?, name_ar = ?, contact_person = ?, phone = ?, email = ?, address = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $contact, $phone, $email, $address, $id]);
                $_SESSION['flash_message'] = __('edit_supplier') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_supplier') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM suppliers WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
                        } elseif ($_POST['action'] === 'import_patients') {
            if (isset($_FILES['file'])) {
                try {
                    $rows = parse_import_file($_FILES['file']);
                    if ($rows) {
                        $db->beginTransaction();
                        $stmt = $db->prepare("INSERT INTO patients (name, dob, nationality, phone, city) VALUES (?, ?, ?, ?, ?)");
                        
                        foreach ($rows as $row) {
                            $name = trim($row[0] ?? '');
                            if (empty($name)) continue;
                            
                            $dob = trim($row[1] ?? '');
                            if (!empty($dob)) {
                                $parsed_date = strtotime(str_replace('/', '-', $dob));
                                if ($parsed_date) {
                                    $dob = date('Y-m-d', $parsed_date);
                                } else {
                                    $dob = null;
                                }
                            } else {
                                $dob = null;
                            }
                            
                            $nationality = trim($row[2] ?? '');
                            $phone = trim($row[3] ?? '');
                            $city = trim($row[4] ?? '');
                            
                            $stmt->execute([$name, $dob, $nationality, $phone, $city]);
                        }
                        
                        $db->commit();
                        $_SESSION['flash_message'] = __('patients').' '.__('imported_successfully') ?? 'Import successful';
                    } else {
                        $_SESSION['flash_message'] = $_SESSION['import_error'] ?? 'Failed to parse file or empty.'; unset($_SESSION['import_error']);
                    }
                } catch (Exception $e) {
                    if ($db->inTransaction()) {
                        $db->rollBack();
                    }
                    $_SESSION['flash_message'] = "Error importing data: " . $e->getMessage();
                }
            } else {
                $_SESSION['flash_message'] = "No file selected.";
            }
            header('Location: ../patients.php');
            exit;
} elseif ($_POST['action'] === 'import_drugs_groups') {
            if (isset($_FILES['csv_file'])) {
                try {
                    $rows = parse_import_file($_FILES['csv_file']);
                    
                    if ($rows) {
                        $db->beginTransaction();
                        $stmt = $db->prepare("INSERT INTO drugs_groups (name_en, name_ar) VALUES (?, ?)");
                        $checkStmt = $db->prepare("SELECT id FROM drugs_groups WHERE name_en = ?");
                        
                        foreach ($rows as $row) {
                            $name_en = $row[0] ?? '';
                            $name_ar = $row[1] ?? '';
                            
                            if ($name_en) {
                                $checkStmt->execute([$name_en]);
                                if (!$checkStmt->fetch()) {
                                    $stmt->execute([$name_en, $name_ar]);
                                }
                            }
                        }
                        $db->commit();
                        $_SESSION['flash_message'] = __('import_successfully');
                        $redirect = true;
                    } else {
                        $_SESSION['flash_message'] = $_SESSION['import_error'] ?? 'Failed to parse file or empty.'; unset($_SESSION['import_error']);
                        $redirect = true;
                    }
                } catch (Throwable $e) {
                    if ($db->inTransaction()) {
                        $db->rollBack();
                    }
                    error_log("Import Error: " . $e->getMessage());
                    $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
                    $redirect = true;
                }
            }
        } elseif ($_POST['action'] === 'import_drugs') {
            if (isset($_FILES['csv_file'])) {
                try {
                    $rows = parse_import_file($_FILES['csv_file']);
                    
                    if ($rows) {
                        $db->beginTransaction();
                        $stmt = $db->prepare("INSERT INTO drugs (name_en, name_ar, group_id, price, expiry_date, supplier_id) VALUES (?, ?, ?, ?, ?, ?)");
                        
                        $groupMap = [];
                        $supplierMap = [];
                        
                        foreach ($rows as $row) {
                            $name_en = $row[0] ?? '';
                            $name_ar = $row[1] ?? '';
                            $group_name = $row[2] ?? '';
                            $price = $row[3] ?? 0; if (!is_numeric($price)) { $price = 0; }
                            // $expiry = $row[4] ?? null;
                            // Force expiry to null as requested to bypass parsing issues
                            $expiry = null; 
                            $supplier_name = $row[5] ?? '';
                            
                            if ($name_en) {
                                $group_id = null;
                                if ($group_name) {
                                    if (isset($groupMap[$group_name])) {
                                        $group_id = $groupMap[$group_name];
                                    } else {
                                        $gStmt = $db->prepare("SELECT id FROM drugs_groups WHERE name_en = ? OR name_ar = ?");
                                        $gStmt->execute([$group_name, $group_name]);
                                        $gRes = $gStmt->fetch();
                                        if ($gRes) {
                                            $group_id = $gRes['id'];
                                        } else {
                                            $cgStmt = $db->prepare("INSERT INTO drugs_groups (name_en, name_ar) VALUES (?, ?)");
                                            $cgStmt->execute([$group_name, $group_name]);
                                            $group_id = $db->lastInsertId();
                                        }
                                        $groupMap[$group_name] = $group_id;
                                    }
                                }
                                
                                $supplier_id = null;
                                if ($supplier_name) {
                                    if (isset($supplierMap[$supplier_name])) {
                                        $supplier_id = $supplierMap[$supplier_name];
                                    } else {
                                        $sStmt = $db->prepare("SELECT id FROM suppliers WHERE name_en = ? OR name_ar = ?");
                                        $sStmt->execute([$supplier_name, $supplier_name]);
                                        $sRes = $sStmt->fetch();
                                        if ($sRes) {
                                            $supplier_id = $sRes['id'];
                                        } else {
                                            $csStmt = $db->prepare("INSERT INTO suppliers (name_en, name_ar) VALUES (?, ?)");
                                            $csStmt->execute([$supplier_name, $supplier_name]);
                                            $supplier_id = $db->lastInsertId();
                                        }
                                        $supplierMap[$supplier_name] = $supplier_id;
                                    }
                                }

                                $stmt->execute([$name_en, $name_ar, $group_id, $price, $expiry, $supplier_id]);
                            }
                        }
                        $db->commit();
                        $_SESSION['flash_message'] = __('import_successfully');
                        $redirect = true;
                    } else {
                        $_SESSION['flash_message'] = $_SESSION['import_error'] ?? 'Failed to parse file or empty.'; unset($_SESSION['import_error']);
                        $redirect = true;
                    }
                } catch (Throwable $e) {
                    if ($db->inTransaction()) {
                        $db->rollBack();
                    }
                    error_log("Import Error: " . $e->getMessage());
                    $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
                    $redirect = true;
                }
            }
        } elseif ($_POST['action'] === 'import_tests') {
            if (isset($_FILES['csv_file'])) {
                try {
                    $rows = parse_import_file($_FILES['csv_file']);
                    
                    if ($rows) {
                        $db->beginTransaction();
                        $stmt = $db->prepare("INSERT INTO laboratory_tests (name_en, name_ar, group_id, price, normal_range) VALUES (?, ?, ?, ?, ?)");
                        $groupMap = [];

                        foreach ($rows as $row) {
                            $name_en = $row[0] ?? '';
                            $name_ar = $row[1] ?? '';
                            $group_name = $row[2] ?? '';
                            $price = $row[3] ?? 0; if (!is_numeric($price)) { $price = 0; }
                            $range = $row[4] ?? '';
                            
                            if ($name_en) {
                                $group_id = null;
                                if ($group_name) {
                                    if (isset($groupMap[$group_name])) {
                                        $group_id = $groupMap[$group_name];
                                    } else {
                                        $gStmt = $db->prepare("SELECT id FROM test_groups WHERE name_en = ? OR name_ar = ?");
                                        $gStmt->execute([$group_name, $group_name]);
                                        $gRes = $gStmt->fetch();
                                        if ($gRes) {
                                            $group_id = $gRes['id'];
                                        } else {
                                            $cgStmt = $db->prepare("INSERT INTO test_groups (name_en, name_ar) VALUES (?, ?)");
                                            $cgStmt->execute([$group_name, $group_name]);
                                            $group_id = $db->lastInsertId();
                                        }
                                        $groupMap[$group_name] = $group_id;
                                    }
                                }
                                $stmt->execute([$name_en, $name_ar, $group_id, $price, $range]);
                            }
                        }
                        $db->commit();
                        $_SESSION['flash_message'] = __('import_successfully');
                        $redirect = true;
                    } else {
                        $_SESSION['flash_message'] = $_SESSION['import_error'] ?? 'Failed to parse file or empty.'; unset($_SESSION['import_error']);
                        $redirect = true;
                    }
                } catch (Throwable $e) {
                    if ($db->inTransaction()) {
                        $db->rollBack();
                    }
                    error_log("Import Error: " . $e->getMessage());
                    $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
                    $redirect = true;
                }
            }
        } elseif ($_POST['action'] === 'add_queue_ad') {
            $text_en = $_POST['text_en'] ?? '';
            $text_ar = $_POST['text_ar'] ?? '';
            $active = isset($_POST['active']) ? 1 : 0;
            $requires_vitals = isset($_POST['requires_vitals']) ? 1 : 0;
            $is_vitals_room = isset($_POST['is_vitals_room']) ? 1 : 0;
            
            if ($text_en && $text_ar) {
                $stmt = $db->prepare("INSERT INTO queue_ads (text_en, text_ar, active) VALUES (?, ?, ?)");
                $stmt->execute([$text_en, $text_ar, $active]);
                $_SESSION['flash_message'] = __('add_ad') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_queue_ad') {
            $id = $_POST['id'] ?? '';
            $text_en = $_POST['text_en'] ?? '';
            $text_ar = $_POST['text_ar'] ?? '';
            $active = isset($_POST['active']) ? 1 : 0;
            $requires_vitals = isset($_POST['requires_vitals']) ? 1 : 0;
            $is_vitals_room = isset($_POST['is_vitals_room']) ? 1 : 0;
            
            if ($id && $text_en && $text_ar) {
                $stmt = $db->prepare("UPDATE queue_ads SET text_en = ?, text_ar, active = ? WHERE id = ?");
                $stmt->execute([$text_en, $text_ar, $active, $id]);
                $_SESSION['flash_message'] = __('edit_ad') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_queue_ad') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM queue_ads WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_insurance') {
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $email = $_POST['email'] ?? '';
            $phone = $_POST['phone'] ?? '';
            $discount = $_POST['discount_percentage'] ?? 0;
            
            if ($name_en && $name_ar) {
                $stmt = $db->prepare("INSERT INTO insurance_companies (name_en, name_ar, email, phone, discount_percentage) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name_en, $name_ar, $email, $phone, $discount]);
                $_SESSION['flash_message'] = __('add_insurance') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_insurance') {
            $id = $_POST['id'] ?? '';
            $name_en = $_POST['name_en'] ?? '';
            $name_ar = $_POST['name_ar'] ?? '';
            $email = $_POST['email'] ?? '';
            $phone = $_POST['phone'] ?? '';
            $discount = $_POST['discount_percentage'] ?? 0;
            
            if ($id && $name_en && $name_ar) {
                $stmt = $db->prepare("UPDATE insurance_companies SET name_en = ?, name_ar = ?, email = ?, phone = ?, discount_percentage = ? WHERE id = ?");
                $stmt->execute([$name_en, $name_ar, $email, $phone, $discount, $id]);
                $_SESSION['flash_message'] = __('edit') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_insurance') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM insurance_companies WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('delete') . ' ' . __('successfully');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_transaction') {
            $insurance_company_id = $_POST['insurance_company_id'] ?: null;
            $amount = $_POST['amount'] ?? 0;
            $date = $_POST['payment_date'] ?? date('Y-m-d');
            $ref = $_POST['reference_number'] ?? '';
            $method = $_POST['payment_method'] ?? 'Check';
            $notes = $_POST['notes'] ?? '';
            
            if ($insurance_company_id && $amount) {
                $stmt = $db->prepare("INSERT INTO insurance_payments (insurance_company_id, amount, payment_date, reference_number, payment_method, notes) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$insurance_company_id, $amount, $date, $ref, $method, $notes]);
                $_SESSION['flash_message'] = __('transaction_added_success');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'edit_transaction') {
            $id = $_POST['id'] ?? '';
            $insurance_company_id = $_POST['insurance_company_id'] ?: null;
            $amount = $_POST['amount'] ?? 0;
            $date = $_POST['payment_date'] ?? date('Y-m-d');
            $ref = $_POST['reference_number'] ?? '';
            $method = $_POST['payment_method'] ?? 'Check';
            $notes = $_POST['notes'] ?? '';
            
            if ($id && $insurance_company_id && $amount) {
                $stmt = $db->prepare("UPDATE insurance_payments SET insurance_company_id = ?, amount = ?, payment_date = ?, reference_number = ?, payment_method = ?, notes = ? WHERE id = ?");
                $stmt->execute([$insurance_company_id, $amount, $date, $ref, $method, $notes, $id]);
                $_SESSION['flash_message'] = __('transaction_updated_success');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'delete_transaction') {
            $id = $_POST['id'] ?? '';
            if ($id) {
                $stmt = $db->prepare("DELETE FROM insurance_payments WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('transaction_deleted_success');
                $redirect = true;
            }
        } elseif ($_POST['action'] === 'add_user') {
            require_role('admin');
            try {
                $name = $_POST['name'];
                $email = $_POST['email'];
                $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $role_id = $_POST['role_id'];
                $active = isset($_POST['active']) ? 1 : 0;
            $requires_vitals = isset($_POST['requires_vitals']) ? 1 : 0;
            $is_vitals_room = isset($_POST['is_vitals_room']) ? 1 : 0;

                $stmt = $db->prepare("INSERT INTO users (name, email, password, role_id, active) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name, $email, $password, $role_id, $active]);
                $_SESSION['flash_message'] = __('user_created');
            } catch (Exception $e) {
                $_SESSION['flash_message'] = "Error: " . $e->getMessage();
            }
            $redirect = true;
        } elseif ($_POST['action'] === 'edit_user') {
            require_role('admin');
            try {
                $id = $_POST['id'];
                $name = $_POST['name'];
                $email = $_POST['email'];
                $role_id = $_POST['role_id'];
                $active = isset($_POST['active']) ? 1 : 0;
            $requires_vitals = isset($_POST['requires_vitals']) ? 1 : 0;
            $is_vitals_room = isset($_POST['is_vitals_room']) ? 1 : 0;

                $sql = "UPDATE users SET name = ?, email = ?, role_id = ?, active = ? WHERE id = ?";
                $params = [$name, $email, $role_id, $active, $id];

                if (!empty($_POST['password'])) {
                    $sql = "UPDATE users SET name = ?, email = ?, role_id = ?, active = ?, password = ? WHERE id = ?";
                    $params = [$name, $email, $role_id, $active, password_hash($_POST['password'], PASSWORD_DEFAULT), $id];
                }

                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                $_SESSION['flash_message'] = __('user_updated');
            } catch (Exception $e) {
                $_SESSION['flash_message'] = "Error: " . $e->getMessage();
            }
            $redirect = true;
        } elseif ($_POST['action'] === 'delete_user') {
            require_role('admin');
            try {
                $id = $_POST['id'];
                if ($id == $_SESSION['user_id']) {
                    throw new Exception("You cannot delete yourself.");
                }
                $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$id]);
                $_SESSION['flash_message'] = __('user_deleted');
            } catch (Exception $e) {
                $_SESSION['flash_message'] = "Error: " . $e->getMessage();
            }
            $redirect = true;
        }
    }

    if ($redirect) {
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit;
    }
}
