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

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

// Set page title
$page_title = __('pharmacy_reports_management_page') . ' - ' . __('system_name');

// إعداد الاتصال بقاعدة البيانات
require_once 'config/database.php';
try {
    $db = new Database();
    $pdo = $db->getConnection();
    
    // الحصول على بيانات المستخدم
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    
} catch (PDOException $e) {
    $error_message = __('database_error') . ': ' . $e->getMessage();
}

// إنشاء جدول نماذج تسليم الصيدلة إذا لم يكن موجوداً
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS pharmacy_handover_forms (
        id INT AUTO_INCREMENT PRIMARY KEY,
        form_date DATE NOT NULL,
        shift_type VARCHAR(50),
        checkboxes TEXT,
        items TEXT,
        yes_no_selections TEXT,
        reasons TEXT,
        narcotic_patients TEXT,
        disposal_records TEXT,
        notes TEXT,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (created_by) REFERENCES users(id)
    )");
} catch (PDOException $e) {
    // تجاهل الأخطاء إذا كان الجدول موجود
}

// إنشاء جدول التقارير الداخلية إذا لم يكن موجوداً
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS internal_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_date DATE NOT NULL,
        time_from TIME,
        time_to TIME,
        total_cases INT DEFAULT 0,
        discharges INT DEFAULT 0,
        fourth_floor_cases INT DEFAULT 0,
        fifth_floor_cases INT DEFAULT 0,
        sixth_floor_cases INT DEFAULT 0,
        intermediate_care_cases INT DEFAULT 0,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (created_by) REFERENCES users(id)
    )");
    
    // إضافة العمود الجديد إذا لم يكن موجوداً
    try {
        $pdo->exec("ALTER TABLE internal_reports ADD COLUMN fifth_floor_cases INT DEFAULT 0");
    } catch (PDOException $e) {
        // تجاهل الخطأ إذا كان العمود موجود بالفعل
    }
    
} catch (PDOException $e) {
    // تجاهل الأخطاء إذا كان الجدول موجود
}

// معالجة إرسال النموذج الشامل
if ($_POST && isset($_POST['save_comprehensive_form'])) {
    try {
        // حفظ بيانات نموذج الصيدلة
        $checkboxes = [];
        $items = [];
        $yes_no_selections = [];
        $reasons = [];
        
        for ($i = 1; $i <= 15; $i++) {
            $checkboxes[$i] = isset($_POST["checkbox_$i"]) ? 1 : 0;
            $items[$i] = $_POST["item_$i"] ?? '';
            
            if (isset($_POST["yes_$i"])) {
                $yes_no_selections[$i] = 'yes';
            } elseif (isset($_POST["no_$i"])) {
                $yes_no_selections[$i] = 'no';
            } else {
                $yes_no_selections[$i] = '';
            }
            
            $reasons[$i] = $_POST["reason_$i"] ?? '';
        }
        
        // Narcotic patients data
        $narcotic_patients = [];
        for ($i = 1; $i <= 6; $i++) {
            $narcotic_patients[$i] = [
                'name' => $_POST["narcotic_patient_name_$i"] ?? '',
                'floor' => $_POST["narcotic_patient_floor_$i"] ?? ''
            ];
        }
        
        // Disposal records data
        $disposal_records = [
            'narcotic_disposal' => [],
            'expired_disposal' => [],
            'breakage_records' => []
        ];
        
        for ($i = 1; $i <= 3; $i++) {
            $disposal_records['narcotic_disposal'][$i] = $_POST["narcotic_disposal_$i"] ?? '';
            $disposal_records['expired_disposal'][$i] = $_POST["expired_disposal_$i"] ?? '';
            $disposal_records['breakage_records'][$i] = $_POST["breakage_record_$i"] ?? '';
        }
        
        // حفظ نموذج الصيدلة
        $stmt = $pdo->prepare("INSERT INTO pharmacy_handover_forms (
            form_date, shift_type, checkboxes, items, yes_no_selections, reasons, 
            narcotic_patients, disposal_records, notes, created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $_POST['comprehensive_form_date'] ?? date('Y-m-d'),
            $_POST['comprehensive_shift_type'] ?? '',
            json_encode($checkboxes),
            json_encode($items),
            json_encode($yes_no_selections),
            json_encode($reasons),
            json_encode($narcotic_patients),
            json_encode($disposal_records),
            $_POST['comprehensive_notes'] ?? '',
            $_SESSION['user_id']
        ]);
        
        // حفظ التقرير الداخلي
        $stmt = $pdo->prepare("INSERT INTO internal_reports (
            report_date, time_from, time_to, total_cases, discharges,
            fourth_floor_cases, fifth_floor_cases, sixth_floor_cases, intermediate_care_cases, created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $_POST['comprehensive_form_date'] ?? date('Y-m-d'),
            $_POST['time_from'],
            $_POST['time_to'],
            $_POST['total_cases'] ?? 0,
            $_POST['discharges'] ?? 0,
            $_POST['fourth_floor_cases'] ?? 0,
            $_POST['fifth_floor_cases'] ?? 0,
            $_POST['sixth_floor_cases'] ?? 0,
            $_POST['intermediate_care_cases'] ?? 0,
            $_SESSION['user_id']
        ]);
        
        $success_message = __('form_saved_successfully');
    } catch (PDOException $e) {
        $error_message = __('error_saving_form') . ': ' . $e->getMessage();
    }
}

// معالجة إرسال نموذج تسليم الصيدلة
if ($_POST && isset($_POST['save_pharmacy_form'])) {
    try {
        $checkboxes = [];
        $items = [];
        $yes_no_selections = [];
        $reasons = [];
        
        for ($i = 1; $i <= 15; $i++) {
            $checkboxes[$i] = isset($_POST["checkbox_$i"]) ? 1 : 0;
            $items[$i] = $_POST["item_$i"] ?? '';
            
            if (isset($_POST["yes_$i"])) {
                $yes_no_selections[$i] = 'yes';
            } elseif (isset($_POST["no_$i"])) {
                $yes_no_selections[$i] = 'no';
            } else {
                $yes_no_selections[$i] = '';
            }
            
            $reasons[$i] = $_POST["reason_$i"] ?? '';
        }
        
        // Narcotic patients data
        $narcotic_patients = [];
        for ($i = 1; $i <= 6; $i++) {
            $narcotic_patients[$i] = [
                'name' => $_POST["narcotic_patient_name_$i"] ?? '',
                'floor' => $_POST["narcotic_patient_floor_$i"] ?? ''
            ];
        }
        
        // Disposal records data
        $disposal_records = [
            'narcotic_disposal' => [],
            'expired_disposal' => [],
            'breakage_records' => []
        ];
        
        for ($i = 1; $i <= 3; $i++) {
            $disposal_records['narcotic_disposal'][$i] = $_POST["narcotic_disposal_$i"] ?? '';
            $disposal_records['expired_disposal'][$i] = $_POST["expired_disposal_$i"] ?? '';
            $disposal_records['breakage_records'][$i] = $_POST["breakage_record_$i"] ?? '';
        }
        
        $stmt = $pdo->prepare("INSERT INTO pharmacy_handover_forms (
            form_date, shift_type, checkboxes, items, yes_no_selections, reasons, 
            narcotic_patients, disposal_records, notes, created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $_POST['pharmacy_form_date'] ?? date('Y-m-d'),
            $_POST['pharmacy_shift_type'] ?? '',
            json_encode($checkboxes),
            json_encode($items),
            json_encode($yes_no_selections),
            json_encode($reasons),
            json_encode($narcotic_patients),
            json_encode($disposal_records),
            $_POST['pharmacy_notes'] ?? '',
            $_SESSION['user_id']
        ]);
        
        $success_message = __('save_pharmacy_form');
    } catch (PDOException $e) {
        $error_message = __('error_saving_form') . ': ' . $e->getMessage();
    }
}

// معالجة إرسال التقرير الداخلي
if ($_POST && isset($_POST['save_internal_report'])) {
    try {
        $stmt = $pdo->prepare("INSERT INTO internal_reports (
            report_date, time_from, time_to, total_cases, discharges,
            fourth_floor_cases, fifth_floor_cases, sixth_floor_cases, intermediate_care_cases, created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $_POST['internal_report_date'],
            $_POST['time_from'],
            $_POST['time_to'],
            $_POST['total_cases'] ?? 0,
            $_POST['discharges'] ?? 0,
            $_POST['fourth_floor_cases'] ?? 0,
            $_POST['fifth_floor_cases'] ?? 0,
            $_POST['sixth_floor_cases'] ?? 0,
            $_POST['intermediate_care_cases'] ?? 0,
            $_SESSION['user_id']
        ]);
        
        $success_message = __('save_internal_report');
    } catch (PDOException $e) {
        $error_message = __('error_saving_form') . ': ' . $e->getMessage();
    }
}

// الحصول على نماذج تسليم الصيدلة
$pharmacy_forms = [];
try {
    $stmt = $pdo->query("
        SELECT 
            phf.*,
            u.full_name as created_by_name
        FROM pharmacy_handover_forms phf
        LEFT JOIN users u ON phf.created_by = u.id
        ORDER BY phf.created_at DESC
    ");
    $pharmacy_forms = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = __('data_retrieval_error') . ': ' . $e->getMessage();
}

// الحصول على التقارير الداخلية
$internal_reports = [];
try {
    $stmt = $pdo->query("
        SELECT 
            ir.*,
            u.full_name as created_by_name
        FROM internal_reports ir
        LEFT JOIN users u ON ir.created_by = u.id
        ORDER BY ir.created_at DESC
    ");
    $internal_reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = __('data_retrieval_error') . ': ' . $e->getMessage();
}

// إحصائيات الأقسام للتقرير الداخلي
$fourth_floor_cases = 0;
$fifth_floor_cases = 0;
$sixth_floor_cases = 0;
$intermediate_care_cases = 0;

// يمكن إضافة استعلامات لحساب الحالات الفعلية من قاعدة البيانات هنا إذا لزم الأمر
try {
    // عدد الحالات في الرابع
    $stmt = $pdo->prepare("SELECT COUNT(*) as fourth_floor_cases FROM antibiotic_reports ar JOIN units u ON ar.unit_id = u.id WHERE DATE(ar.created_at) = ? AND u.name LIKE '%الرابع%'");
    $stmt->execute([date('Y-m-d')]);
    $result = $stmt->fetch();
    $fourth_floor_cases = $result ? $result['fourth_floor_cases'] : 0;

    // عدد الحالات في الخامس
    $stmt = $pdo->prepare("SELECT COUNT(*) as fifth_floor_cases FROM antibiotic_reports ar JOIN units u ON ar.unit_id = u.id WHERE DATE(ar.created_at) = ? AND u.name LIKE '%الخامس%'");
    $stmt->execute([date('Y-m-d')]);
    $result = $stmt->fetch();
    $fifth_floor_cases = $result ? $result['fifth_floor_cases'] : 0;

    // عدد الحالات في السادس
    $stmt = $pdo->prepare("SELECT COUNT(*) as sixth_floor_cases FROM antibiotic_reports ar JOIN units u ON ar.unit_id = u.id WHERE DATE(ar.created_at) = ? AND u.name LIKE '%السادس%'");
    $stmt->execute([date('Y-m-d')]);
    $result = $stmt->fetch();
    $sixth_floor_cases = $result ? $result['sixth_floor_cases'] : 0;

    // عدد الحالات في الرعاية المتوسطة
    $stmt = $pdo->prepare("SELECT COUNT(*) as intermediate_care_cases FROM antibiotic_reports ar JOIN units u ON ar.unit_id = u.id WHERE DATE(ar.created_at) = ? AND u.name LIKE '%الرعاية المتوسطة%'");
    $stmt->execute([date('Y-m-d')]);
    $result = $stmt->fetch();
    $intermediate_care_cases = $result ? $result['intermediate_care_cases'] : 0;

} catch (PDOException $e) {
    // تعيين قيم افتراضية في حالة الخطأ
    $fourth_floor_cases = 0;
    $fifth_floor_cases = 0;
    $sixth_floor_cases = 0;
    $intermediate_care_cases = 0;
}

include 'includes/header.php';
?>
<style>
/* Shared Styles */
.toggle-buttons {
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
    gap: 15px;
    flex-wrap: wrap;
}

.toggle-btn {
    background: #ffffff;
    border: 2px solid #e9ecef;
    color: #6c757d;
    padding: 12px 24px;
    border-radius: 20px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 14px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.toggle-btn.active {
    background: #e3f2fd;
    color: #1976d2;
    border-color: #90caf9;
    box-shadow: 0 2px 8px rgba(25, 118, 210, 0.15);
}

.toggle-btn:hover {
    background: #f8f9fa;
    border-color: #90caf9;
    color: #1976d2;
}

.content-section {
    display: none;
}

.content-section.active {
    display: block;
}

.form-container {
    background: #ffffff;
    border-radius: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    overflow: hidden;
    margin-bottom: 25px;
    max-width: 1200px;
    margin: 0 auto 25px;
    border: 1px solid #e9ecef;
}

.form-paper {
    background: #ffffff;
    padding: 30px;
    margin: 0;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.form-header {
    text-align: center;
    margin-bottom: 25px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 10px;
    color: #495057;
    border: 1px solid #e9ecef;
}

.hospital-logo {
    width: 60px;
    height: 60px;
    background: #ffffff;
    border-radius: 50%;
    margin: 0 auto 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: #6c757d;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    border: 2px solid #e9ecef;
}

.form-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 6px;
    color: #343a40;
}

.form-subtitle {
    font-size: 14px;
    color: #6c757d;
    font-weight: 400;
}

.form-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding: 15px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
}

.date-section, .shift-section {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 500;
    color: #495057;
}

.shift-section label {
    margin: 0 6px;
    padding: 4px 12px;
    background: #ffffff;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid #dee2e6;
    font-size: 13px;
    color: #6c757d;
}

.shift-section label:hover {
    background: #e3f2fd;
    border-color: #90caf9;
}

.shift-section input[type="radio"]:checked + label {
    background: #e3f2fd;
    color: #1976d2;
    border-color: #90caf9;
}

.checkbox-list {
    margin: 20px 0;
    background: #ffffff;
    border-radius: 10px;
    padding: 20px;
    border: 1px solid #e9ecef;
}

.checkbox-row {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 8px;
    transition: all 0.3s ease;
    border: 1px solid #f1f3f4;
}

.checkbox-row:hover {
    background: #e3f2fd;
    border-color: #90caf9;
}

.checkbox-number {
    width: 28px;
    height: 28px;
    background: #e3f2fd;
    color: #1976d2;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    margin-right: 12px;
    font-size: 13px;
    border: 1px solid #90caf9;
}

.checkbox-input {
    margin: 0 12px;
    transform: scale(1.1);
    accent-color: #1976d2;
}

.checkbox-label {
    flex: 1;
    font-size: 14px;
    color: #495057;
    padding: 8px;
    background: #ffffff;
    border-radius: 6px;
    margin-right: 12px;
    border: 1px solid #e9ecef;
}

.checkbox-label input {
    border: none;
    background: transparent;
    font-size: 14px;
    color: #495057;
    width: 100%;
    padding: 2px 0;
}

.checkbox-label input:focus {
    outline: none;
    border-bottom: 1px solid #90caf9;
}

.yes-no-section {
    display: flex;
    gap: 8px;
}

.yes-no-option {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    background: #ffffff;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid #e9ecef;
    font-size: 12px;
    color: #6c757d;
}

.yes-no-option:hover {
    background: #e8f5e8;
    border-color: #a5d6a7;
}

.btn-add {
    background: #e8f5e8;
    color: #2e7d32;
    border: 1px solid #a5d6a7;
    padding: 6px 12px;
    border-radius: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 12px;
    box-shadow: 0 1px 3px rgba(46, 125, 50, 0.1);
}

.btn-add:hover {
    background: #c8e6c8;
    box-shadow: 0 2px 6px rgba(46, 125, 50, 0.15);
}

.btn-remove {
    background: #ffeaea;
    color: #c62828;
    border: 1px solid #ef9a9a;
    padding: 3px 6px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 10px;
    box-shadow: 0 1px 3px rgba(198, 40, 40, 0.1);
}

.btn-remove:hover {
    background: #ffcdd2;
    box-shadow: 0 2px 6px rgba(198, 40, 40, 0.15);
}

.btn-save {
    background: linear-gradient(135deg, #90caf9 0%, #81c784 100%);
    color: white;
    border: none;
    padding: 16px 40px;
    border-radius: 25px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 16px;
    margin: 15px;
    display: inline-block;
    position: relative;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(144, 202, 249, 0.2);
}

.btn-save:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(144, 202, 249, 0.25);
}

.special-section {
    margin: 30px 0;
    padding: 25px;
    border: 1px solid #e9ecef;
    border-radius: 10px;
    background: #ffffff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.special-section h4 {
    text-align: center;
    margin-bottom: 20px;
    color: #495057;
    font-size: 18px;
    font-weight: 600;
    padding-bottom: 10px;
    border-bottom: 2px solid #e9ecef;
}

.grid-container {
    display: grid;
    gap: 15px;
    margin-bottom: 20px;
}

.grid-2 { grid-template-columns: 1fr 1fr; }
.grid-3 { grid-template-columns: 1fr 1fr 1fr; }

.grid-item {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    padding: 15px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.grid-item:hover {
    background: #e3f2fd;
    border-color: #90caf9;
}

.grid-item label {
    font-weight: 500;
    font-size: 13px;
    color: #6c757d;
    margin-bottom: 8px;
    display: block;
}

.grid-item input {
    width: 100%;
    border: none;
    border-bottom: 1px solid #dee2e6;
    padding: 8px 0;
    margin-top: 6px;
    background: transparent;
    font-size: 14px;
    color: #495057;
    transition: all 0.3s ease;
}

.grid-item input:focus {
    outline: none;
    border-bottom-color: #90caf9;
    background: rgba(144, 202, 249, 0.05);
}

.alert {
    padding: 12px 16px;
    margin-bottom: 20px;
    border-radius: 8px;
    border: none;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.alert-success {
    background: #e8f5e8;
    color: #2e7d32;
    border-left: 4px solid #4caf50;
}

.alert-danger {
    background: #ffeaea;
    color: #c62828;
    border-left: 4px solid #f44336;
}

/* Internal Reports Specific Styles */
.form-section {
    margin-bottom: 25px;
    padding: 20px;
    border: 1px solid #e9ecef;
    border-radius: 10px;
    background: #f8f9fa;
}

.section-title {
    font-weight: bold;
    color: #1976d2;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid #1976d2;
    font-size: 1.1rem;
}

.form-row {
    display: flex;
    gap: 15px;
    margin-bottom: 15px;
    align-items: center;
}

.form-group {
    flex: 1;
}

.form-label {
    font-weight: 500;
    margin-bottom: 5px;
    color: #495057;
}

.form-control {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #ced4da;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
    border-color: #1976d2;
    outline: 0;
    box-shadow: 0 0 0 0.2rem rgba(25, 118, 210, 0.25);
}

.blue-text {
    color: #1976d2 !important;
    font-weight: bold;
}

.cases-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin-bottom: 20px;
}

.case-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: white;
    border-radius: 8px;
    border: 1px solid #e9ecef;
    transition: all 0.3s ease;
}

.case-item:hover {
    border-color: #1976d2;
    box-shadow: 0 2px 10px rgba(25, 118, 210, 0.1);
}

.case-label {
    font-weight: 500;
}

.case-input {
    width: 80px;
    text-align: center;
    padding: 8px;
    border: 1px solid #ced4da;
    border-radius: 5px;
    font-weight: bold;
    color: #1976d2;
}

.case-input:focus {
    border-color: #1976d2;
    box-shadow: 0 0 0 0.2rem rgba(25, 118, 210, 0.25);
}

.critical-cases-table .table {
    border: 2px solid #1976d2;
    margin-bottom: 0;
    border-radius: 8px;
    overflow: hidden;
}

.critical-cases-table .table th {
    background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%);
    color: white;
    font-weight: bold;
    text-align: center;
    padding: 15px 10px;
    border: none;
}

.critical-cases-table .table td {
    padding: 15px 10px;
    border: 1px solid #e9ecef;
    vertical-align: middle;
}

.checkbox-grid {
    display: flex;
    gap: 10px;
    justify-content: center;
    flex-wrap: wrap;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 5px;
    margin: 2px 0;
    cursor: pointer;
    font-size: 14px;
    position: relative;
}

.checkbox-label input[type="checkbox"] {
    margin-right: 5px;
    transform: scale(1.2);
    accent-color: #1976d2;
}

@media (max-width: 768px) {
    .form-paper {
        padding: 20px;
    }
    
    .toggle-buttons {
        flex-direction: column;
        align-items: center;
    }
    
    .toggle-btn {
        width: 100%;
        max-width: 250px;
    }
    
    .grid-2, .grid-3 {
        grid-template-columns: 1fr;
    }
    
    .cases-grid {
        grid-template-columns: 1fr;
    }
    
    .form-row {
        flex-direction: column;
        gap: 10px;
    }
}
</style>


    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <div>
            <h1 class="h3 mb-0" style="color: #1976d2;">
                <i class="fas fa-pills me-2"></i>
                <?php echo __('pharmacy_forms_reports_management'); ?>
            </h1>
            <p class="text-muted mb-0"><?php echo __('integrated_form'); ?></p>
        </div>
        <div>
            <button type="button" class="btn btn-outline-primary" onclick="window.print()">
                <i class="fas fa-print me-2"></i> <?php echo __('print'); ?>
            </button>
            <a href="index.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?> me-2"></i> <?php echo __('back'); ?>
            </a>
        </div>
    </div>

    <!-- Messages -->
    <?php if (isset($success_message)): ?>
        <div class="alert alert-success alert-dismissible fade show no-print">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo $success_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show no-print">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <?php echo $error_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Toggle Buttons -->
    <div class="toggle-buttons no-print">
        <button class="toggle-btn active" onclick="showSection('comprehensive-form')">
            <i class="fas fa-file-medical me-2"></i>
            <?php echo __('integrated_form'); ?>
        </button>
        <button class="toggle-btn" onclick="showSection('pharmacy-view')">
            <i class="fas fa-list me-2"></i>
            <?php echo __('view_pharmacy_forms'); ?>
        </button>
        <button class="toggle-btn" onclick="showSection('internal-view')">
            <i class="fas fa-chart-line me-2"></i>
            <?php echo __('view_internal_reports'); ?>
        </button>
    </div>
    <!-- Comprehensive Form Section -->
    <div id="comprehensive-form-section" class="content-section active" style="display: block;">
        <div class="form-container">
            <div class="form-paper">
                <form method="POST" action="">
                    <!-- Header -->
                    <div class="form-header">
                        <div class="hospital-logo">
                            <i class="fas fa-hospital"></i>
                        </div>
                        <div class="form-title"><?php echo __('pharmacy_handover_form'); ?></div>
                        <div class="form-subtitle"><?php echo __('clinical_pharmacy_internal_report'); ?></div>
                    </div>

                    <!-- Form Info -->
                    <div class="form-info">
                        <div class="date-section">
                            <strong><?php echo __('date'); ?>:</strong>
                            <input type="date" name="comprehensive_form_date" value="<?php echo date('Y-m-d'); ?>" 
                                   style="border: none; border-bottom: 1px solid #333; background: transparent; padding: 5px;">
                        </div>
                        <div class="shift-section">
                            <strong><?php echo __('shift'); ?>:</strong>
                            <input type="radio" name="comprehensive_shift_type" value="morning" id="comp_morning">
                            <label for="comp_morning"><?php echo __('morning'); ?></label>
                            <input type="radio" name="comprehensive_shift_type" value="evening" id="comp_evening">
                            <label for="comp_evening"><?php echo __('evening'); ?></label>
                            <input type="radio" name="comprehensive_shift_type" value="night" id="comp_night">
                            <label for="comp_night"><?php echo __('night'); ?></label>
                        </div>
                    </div>

                    <!-- General Information Section -->
                    <div class="form-section">
                        <div class="section-title"><?php echo __('general_information'); ?></div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label"><?php echo __('time_from'); ?>:</label>
                                <input type="time" name="time_from" class="form-control">
                            </div>
                            <div class="form-group">
                                <label class="form-label"><?php echo __('time_to'); ?>:</label>
                                <input type="time" name="time_to" class="form-control">
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label"><?php echo __('total_cases'); ?>:</label>
                                <input type="number" name="total_cases" class="form-control" min="0">
                            </div>
                            <div class="form-group">
                                <label class="form-label"><?php echo __('discharges'); ?>:</label>
                                <input type="number" name="discharges" class="form-control" min="0">
                            </div>
                        </div>

                        <!-- Blue Text Section - Updated departments -->
                        <div style="margin-top: 20px; padding: 15px; background: #f0f8ff; border-radius: 5px;">
                            <div class="cases-grid">
                                <div class="case-item">
                                    <span class="case-label blue-text"><?php echo __('fourth_floor'); ?>:</span>
                                    <input type="number" name="fourth_floor_cases" class="case-input" min="0" value="<?php echo $fourth_floor_cases; ?>">
                                </div>
                                <div class="case-item">
                                    <span class="case-label blue-text"><?php echo __('fifth_floor'); ?>:</span>
                                    <input type="number" name="fifth_floor_cases" class="case-input" min="0" value="<?php echo $fifth_floor_cases; ?>">
                                </div>
                                <div class="case-item">
                                    <span class="case-label blue-text"><?php echo __('sixth_floor'); ?>:</span>
                                    <input type="number" name="sixth_floor_cases" class="case-input" min="0" value="<?php echo $sixth_floor_cases; ?>">
                                </div>
                                <div class="case-item">
                                    <span class="case-label blue-text"><?php echo __('intermediate_care'); ?>:</span>
                                    <input type="number" name="intermediate_care_cases" class="case-input" min="0" value="<?php echo $intermediate_care_cases; ?>">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Critical Follow-up Cases Section -->
                    <div class="form-section">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                            <div class="section-title" style="margin: 0; border: none; padding: 0;"><?php echo __('critical_follow_up_cases'); ?></div>
                            <button type="button" onclick="addCriticalCase()" class="btn-add">
                                <i class="fas fa-plus me-2"></i> <?php echo __('add_critical_case'); ?>
                            </button>
                        </div>
                        <h6 style="margin: 0 0 15px 0; color: #495057; text-align: center;"><?php echo __('critical_follow_up_cases'); ?></h6>
                        
                        <div class="critical-cases-table">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th style="width: 40%;"><?php echo __('patient_name'); ?></th>
                                        <th style="width: 20%;"><?php echo __('room_number'); ?></th>
                                        <th style="width: 30%;"><?php echo __('critical_status'); ?></th>
                                        <th style="width: 10%;"><?php echo __('actions'); ?></th>
                                    </tr>
                                </thead>
                                <tbody id="critical-cases-container">
                                    <tr id="critical-case-1">
                                        <td><input type="text" name="patient_name_1" class="form-control" placeholder="<?php echo __('write_patient_name'); ?>"></td>
                                        <td><input type="text" name="room_no_1" class="form-control" placeholder="<?php echo __('room_number'); ?>"></td>
                                        <td>
                                            <div class="checkbox-grid">
                                                <label class="checkbox-label"><input type="checkbox" name="critical_case_1[]" value="1"> □</label>
                                                <label class="checkbox-label"><input type="checkbox" name="critical_case_1[]" value="2"> □</label>
                                                <label class="checkbox-label"><input type="checkbox" name="critical_case_1[]" value="3"> □</label>
                                                <label class="checkbox-label"><input type="checkbox" name="critical_case_1[]" value="4"> □</label>
                                            </div>
                                        </td>
                                        <td></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Checkbox List Section -->
                    <div class="checkbox-list">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                            <h5 style="color: #1976d2; margin: 0; font-size: 18px; font-weight: bold;"><?php echo __('items_list'); ?></h5>
                            <button type="button" onclick="addCheckboxItem()" class="btn-add">
                                <i class="fas fa-plus me-2"></i> <?php echo __('add_new_item'); ?>
                            </button>
                        </div>
                        
                        <div id="checkbox-container">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                            <div class="checkbox-row" id="checkbox-row-<?php echo $i; ?>">
                                <div class="checkbox-number"><?php echo $i; ?></div>
                                <input type="checkbox" name="checkbox_<?php echo $i; ?>" class="checkbox-input">
                                <div class="checkbox-label">
                                    <input type="text" name="item_<?php echo $i; ?>" placeholder="<?php echo __('write_here'); ?>">
                                </div>
                                <div class="yes-no-section">
                                    <div class="yes-no-option">
                                        <span><?php echo __('yes'); ?></span>
                                        <input type="checkbox" name="yes_<?php echo $i; ?>" onchange="toggleReasonField(<?php echo $i; ?>, 'yes')">
                                    </div>
                                    <div class="yes-no-option">
                                        <span><?php echo __('no'); ?></span>
                                        <input type="checkbox" name="no_<?php echo $i; ?>" onchange="toggleReasonField(<?php echo $i; ?>, 'no')">
                                    </div>
                                </div>
                                <?php if ($i > 3): ?>
                                <button type="button" onclick="removeCheckboxItem(<?php echo $i; ?>)" class="btn-remove">
                                    <i class="fas fa-times"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                            <!-- Reason field (initially hidden) -->
                            <div id="reason_<?php echo $i; ?>" class="reason-field" style="display: none; margin-left: 45px; margin-bottom: 10px; background: #fff8e1; border: 1px solid #ffcc02; border-radius: 8px; padding: 12px;">
                                <label style="font-size: 12px; color: #f57f17; margin-bottom: 5px; display: block;"><?php echo __('reason'); ?>:</label>
                                <textarea name="reason_<?php echo $i; ?>" rows="2" 
                                          style="width: 80%; border: 1px solid #ffcc02; border-radius: 3px; padding: 5px; font-size: 12px; resize: vertical;" 
                                          placeholder="<?php echo __('write_reason_here'); ?>"></textarea>
                            </div>
                            <?php endfor; ?>
                        </div>
                    </div>

                    <!-- Narcotic Drugs Patients Section -->
                    <div class="special-section">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                            <h4 style="margin: 0;">
                                <?php echo __('narcotic_drugs_patients'); ?>
                                <br>
                                <span style="font-size: 16px; font-weight: normal; color: #6c757d;"><?php echo __('narcotic_drugs_patients'); ?></span>
                            </h4>
                            <button type="button" onclick="addNarcoticPatient()" class="btn-add">
                                <i class="fas fa-plus me-2"></i> <?php echo __('add_patient'); ?>
                            </button>
                        </div>
                        
                        <div class="grid-container grid-2" id="narcotic-patients-container">
                            <?php for ($i = 1; $i <= 3; $i++): ?>
                            <div class="grid-item" id="narcotic-patient-<?php echo $i; ?>">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                    <label><?php echo __('patient_name'); ?> / <?php echo __('patient_name'); ?>:</label>
                                    <?php if ($i > 2): ?>
                                    <button type="button" onclick="removeNarcoticPatient(<?php echo $i; ?>)" class="btn-remove">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                                <input type="text" name="narcotic_patient_name_<?php echo $i; ?>" placeholder="<?php echo __('write_patient_name'); ?>">
                                <div style="margin-top: 15px;">
                                    <label><?php echo __('floor'); ?> / <?php echo __('floor'); ?>:</label>
                                    <input type="text" name="narcotic_patient_floor_<?php echo $i; ?>" placeholder="<?php echo __('floor_number'); ?>">
                                </div>
                            </div>
                            <?php endfor; ?>
                        </div>
                    </div>

                    <!-- Disposal Records Section -->
                    <div class="special-section">
                        <h4>
                            <?php echo __('disposal_records'); ?>
                            <br>
                            <span style="font-size: 16px; font-weight: normal; color: #6c757d;"><?php echo __('disposal_records'); ?></span>
                        </h4>
                        
                        <div class="grid-container grid-3">
                            <!-- Narcotic Drugs Disposal -->
                            <div class="grid-item" style="background: #fff8f8; border-color: #f8d7da;">
                                <h5 style="color: #d63384; font-size: 16px; margin-bottom: 20px; text-align: center; font-weight: bold;">
                                    <?php echo __('narcotic_disposal'); ?>
                                    <br>
                                    <span style="font-size: 13px; font-weight: normal;"><?php echo __('narcotic_disposal'); ?></span>
                                </h5>
                                <?php for ($i = 1; $i <= 3; $i++): ?>
                                <div style="margin-bottom: 15px;">
                                    <input type="text" name="narcotic_disposal_<?php echo $i; ?>" 
                                           style="border-bottom-color: #d63384;" placeholder="<?php echo __('drug_name'); ?>">
                                </div>
                                <?php endfor; ?>
                            </div>

                            <!-- Expired Drugs Disposal -->
                            <div class="grid-item" style="background: #fff8f0; border-color: #ffeaa7;">
                                <h5 style="color: #fd7e14; font-size: 16px; margin-bottom: 20px; text-align: center; font-weight: bold;">
                                    <?php echo __('expired_disposal'); ?>
                                    <br>
                                    <span style="font-size: 13px; font-weight: normal;"><?php echo __('expired_disposal'); ?></span>
                                </h5>
                                <?php for ($i = 1; $i <= 3; $i++): ?>
                                <div style="margin-bottom: 15px;">
                                    <input type="text" name="expired_disposal_<?php echo $i; ?>" 
                                           style="border-bottom-color: #fd7e14;" placeholder="<?php echo __('drug_name'); ?>">
                                </div>
                                <?php endfor; ?>
                            </div>

                            <!-- Breakage Records -->
                            <div class="grid-item" style="background: #f8f9ff; border-color: #e3d9ff;">
                                <h5 style="color: #6f42c1; font-size: 16px; margin-bottom: 20px; text-align: center; font-weight: bold;">
                                    <?php echo __('breakage_reports'); ?>
                                    <br>
                                    <span style="font-size: 13px; font-weight: normal;"><?php echo __('breakage_reports'); ?></span>
                                </h5>
                                <?php for ($i = 1; $i <= 3; $i++): ?>
                                <div style="margin-bottom: 15px;">
                                    <input type="text" name="breakage_record_<?php echo $i; ?>" 
                                           style="border-bottom-color: #6f42c1;" placeholder="<?php echo __('item_name'); ?>">
                                </div>
                                <?php endfor; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Inpatient Summary Report Section -->
                    <div class="special-section">
                        <div class="section-title" style="text-align: center; font-size: 18px; color: #1976d2; font-weight: bold; margin: 0; border: none; padding: 0;"><?php echo __('inpatient_summary_report'); ?></div>
                        <div style="text-align: center; margin: 10px 0; font-size: 14px; color: #6c757d;"><?php echo __('inpatient_summary_report'); ?></div>
                        <div style="min-height: 120px; border: 2px dashed #d1ecf1; border-radius: 15px; background: #ffffff; padding: 25px; margin-top: 20px;">
                            <textarea name="comprehensive_notes" rows="4" style="width: 100%; border: none; background: transparent; resize: vertical;" 
                                      placeholder="<?php echo __('write_report_summary'); ?>"></textarea>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div style="text-align: center; margin-top: 30px;">
                        <button type="submit" name="save_comprehensive_form" class="btn-save no-print">
                            <i class="fas fa-save me-2"></i> <?php echo __('save_comprehensive_form'); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- Pharmacy Forms View Section -->
    <div id="pharmacy-view-section" class="content-section" style="display: none;">
        <div class="row">
            <div class="col-12">
                <?php if (empty($pharmacy_forms)): ?>
                    <div class="form-container">
                        <div class="form-paper">
                            <div style="text-align: center; padding: 60px 20px; color: #6c757d;">
                                <i class="fas fa-clipboard-list" style="font-size: 4rem; color: #1976d2; margin-bottom: 20px;"></i>
                                <h4 style="color: #1976d2; margin-bottom: 15px;"><?php echo __('no_pharmacy_forms_saved'); ?></h4>
                                <p style="color: #6c757d; margin-bottom: 30px;"><?php echo __('no_forms_message'); ?></p>
                                <button class="btn-save" onclick="showSection('comprehensive-form')">
                                    <i class="fas fa-plus me-2"></i> <?php echo __('create_new_pharmacy_form'); ?>
                                </button>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($pharmacy_forms as $form): ?>
                        <div class="form-container" style="margin-bottom: 30px;">
                            <div class="form-paper">
                                <div class="form-header">
                                    <div class="form-title"><?php echo __('pharmacy_handover_form'); ?> - <?php echo date('d/m/Y', strtotime($form['form_date'])); ?></div>
                                    <div class="form-subtitle">
                                        <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($form['created_by_name'] ?? __('not_specified')); ?>
                                        | <i class="fas fa-clock me-1"></i> <?php echo date('d/m/Y H:i', strtotime($form['created_at'])); ?>
                                    </div>
                                </div>
                                <p><?php echo __('form_saved_successfully'); ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Internal Reports View Section -->
    <div id="internal-view-section" class="content-section" style="display: none;">
        <div class="row">
            <div class="col-12">
                <?php if (empty($internal_reports)): ?>
                    <div class="form-container">
                        <div class="form-paper">
                            <div style="text-align: center; padding: 60px 20px; color: #6c757d;">
                                <i class="fas fa-chart-bar" style="font-size: 4rem; color: #1976d2; margin-bottom: 20px;"></i>
                                <h4 style="color: #1976d2; margin-bottom: 15px;"><?php echo __('no_internal_reports_saved'); ?></h4>
                                <p style="color: #6c757d; margin-bottom: 30px;"><?php echo __('no_forms_message'); ?></p>
                                <button class="btn-save" onclick="showSection('comprehensive-form')">
                                    <i class="fas fa-plus me-2"></i> <?php echo __('create_new_internal_report'); ?>
                                </button>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($internal_reports as $report): ?>
                        <div class="form-container" style="margin-bottom: 30px;">
                            <div class="form-paper">
                                <div class="form-header">
                                    <div class="form-title"><?php echo __('internal_report_title'); ?> - <?php echo date('d/m/Y', strtotime($report['report_date'])); ?></div>
                                    <div class="form-subtitle">
                                        <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($report['created_by_name'] ?? __('not_specified')); ?>
                                        | <i class="fas fa-clock me-1"></i> <?php echo date('d/m/Y H:i', strtotime($report['created_at'])); ?>
                                        <?php if ($report['time_from'] && $report['time_to']): ?>
                                        | <i class="fas fa-clock me-1"></i> <?php echo __('from'); ?> <?php echo $report['time_from']; ?> <?php echo __('to'); ?> <?php echo $report['time_to']; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <!-- الإحصائيات العامة -->
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 20px 0;">
                                    <div style="padding: 15px; background: #f0f8ff; border-radius: 8px; border-left: 4px solid #1976d2;">
                                        <div style="font-size: 2rem; font-weight: bold; color: #1976d2; text-align: center;"><?php echo $report['total_cases'] ?? 0; ?></div>
                                        <div style="text-align: center; color: #495057; font-weight: 500;"><?php echo __('total_cases'); ?></div>
                                    </div>
                                    <div style="padding: 15px; background: #f0fff4; border-radius: 8px; border-left: 4px solid #28a745;">
                                        <div style="font-size: 2rem; font-weight: bold; color: #28a745; text-align: center;"><?php echo $report['discharges'] ?? 0; ?></div>
                                        <div style="text-align: center; color: #495057; font-weight: 500;"><?php echo __('discharges'); ?></div>
                                    </div>
                                </div>

                                <!-- إحصائيات الأقسام -->
                                <div style="margin: 20px 0;">
                                    <h6 style="color: #1976d2; font-weight: 600; margin-bottom: 15px; text-align: center;"><?php echo __('department_statistics'); ?>:</h6>
                                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                                        <div style="padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #1976d2; text-align: center;">
                                            <div style="font-size: 1.5rem; font-weight: bold; color: #1976d2;"><?php echo $report['fourth_floor_cases'] ?? 0; ?></div>
                                            <div style="color: #6c757d; font-size: 0.9rem;"><?php echo __('fourth_floor'); ?></div>
                                        </div>
                                        <div style="padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #1976d2; text-align: center;">
                                            <div style="font-size: 1.5rem; font-weight: bold; color: #1976d2;"><?php echo $report['fifth_floor_cases'] ?? 0; ?></div>
                                            <div style="color: #6c757d; font-size: 0.9rem;"><?php echo __('fifth_floor'); ?></div>
                                        </div>
                                        <div style="padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #1976d2; text-align: center;">
                                            <div style="font-size: 1.5rem; font-weight: bold; color: #1976d2;"><?php echo $report['sixth_floor_cases'] ?? 0; ?></div>
                                            <div style="color: #6c757d; font-size: 0.9rem;"><?php echo __('sixth_floor'); ?></div>
                                        </div>
                                        <div style="padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #1976d2; text-align: center;">
                                            <div style="font-size: 1.5rem; font-weight: bold; color: #1976d2;"><?php echo $report['intermediate_care_cases'] ?? 0; ?></div>
                                            <div style="color: #6c757d; font-size: 0.9rem;"><?php echo __('intermediate_care'); ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
// Toggle between sections
function showSection(sectionName) {
    // Hide all sections
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => {
        section.classList.remove('active');
        section.style.display = 'none';
    });
    
    // Remove active class from all buttons
    const buttons = document.querySelectorAll('.toggle-btn');
    buttons.forEach(btn => {
        btn.classList.remove('active');
    });
    
    // Show selected section
    const targetSection = document.getElementById(sectionName + '-section');
    if (targetSection) {
        targetSection.classList.add('active');
        targetSection.style.display = 'block';
    }
    
    // Add active class to clicked button
    if (event && event.target) {
        event.target.classList.add('active');
    }
}

// Add critical case function
function addCriticalCase() {
    const container = document.getElementById('critical-cases-container');
    const currentRows = container.querySelectorAll('tr').length;
    const newRowNumber = currentRows + 1;
    
    const newRow = document.createElement('tr');
    newRow.id = `critical-case-${newRowNumber}`;
    newRow.innerHTML = `
        <td><input type="text" name="patient_name_${newRowNumber}" class="form-control" placeholder="اسم المريض"></td>
        <td><input type="text" name="room_no_${newRowNumber}" class="form-control" placeholder="رقم الغرفة"></td>
        <td>
            <div class="checkbox-grid">
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${newRowNumber}[]" value="1"> □</label>
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${newRowNumber}[]" value="2"> □</label>
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${newRowNumber}[]" value="3"> □</label>
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${newRowNumber}[]" value="4"> □</label>
            </div>
        </td>
        <td>
            <button type="button" onclick="removeCriticalCase(${newRowNumber})" class="btn-remove">
                <i class="fas fa-times"></i>
            </button>
        </td>
    `;
    
    container.appendChild(newRow);
}

// Remove critical case function
function removeCriticalCase(caseNumber) {
    const row = document.getElementById(`critical-case-${caseNumber}`);
    if (row) {
        row.remove();
    }
}

// Toggle reason field based on yes/no selection
function toggleReasonField(itemNumber, selection) {
    const reasonField = document.getElementById('reason_' + itemNumber);
    const yesCheckbox = document.querySelector(`input[name="yes_${itemNumber}"]`);
    const noCheckbox = document.querySelector(`input[name="no_${itemNumber}"]`);
    
    // Uncheck the other option
    if (selection === 'yes') {
        noCheckbox.checked = false;
    } else {
        yesCheckbox.checked = false;
    }
    
    // Show/hide reason field based on selection
    if ((selection === 'yes' && yesCheckbox.checked) || (selection === 'no' && noCheckbox.checked)) {
        reasonField.style.display = 'block';
        reasonField.querySelector('textarea').focus();
    } else {
        reasonField.style.display = 'none';
        reasonField.querySelector('textarea').value = '';
    }
}

// Dynamic checkbox items management
let checkboxCounter = 5;

function addCheckboxItem() {
    checkboxCounter++;
    const container = document.getElementById('checkbox-container');
    
    const newRow = document.createElement('div');
    newRow.className = 'checkbox-row';
    newRow.id = `checkbox-row-${checkboxCounter}`;
    
    newRow.innerHTML = `
        <div class="checkbox-number">${checkboxCounter}</div>
        <input type="checkbox" name="checkbox_${checkboxCounter}" class="checkbox-input">
        <div class="checkbox-label">
            <input type="text" name="item_${checkboxCounter}" placeholder="اكتب هنا...">
        </div>
        <div class="yes-no-section">
            <div class="yes-no-option">
                <span>Yes</span>
                <input type="checkbox" name="yes_${checkboxCounter}" onchange="toggleReasonField(${checkboxCounter}, 'yes')">
            </div>
            <div class="yes-no-option">
                <span>No</span>
                <input type="checkbox" name="no_${checkboxCounter}" onchange="toggleReasonField(${checkboxCounter}, 'no')">
            </div>
        </div>
        <button type="button" onclick="removeCheckboxItem(${checkboxCounter})" class="btn-remove">
            <i class="fas fa-times"></i>
        </button>
    `;
    
    container.appendChild(newRow);
    
    // Add reason field
    const reasonField = document.createElement('div');
    reasonField.id = `reason_${checkboxCounter}`;
    reasonField.style.display = 'none';
    reasonField.style.marginLeft = '45px';
    reasonField.style.marginBottom = '10px';
    reasonField.style.background = '#fff8e1';
    reasonField.style.border = '1px solid #ffcc02';
    reasonField.style.borderRadius = '8px';
    reasonField.style.padding = '12px';
    
    reasonField.innerHTML = `
        <label style="font-size: 12px; color: #f57f17; margin-bottom: 5px; display: block;">السبب:</label>
        <textarea name="reason_${checkboxCounter}" rows="2" 
                  style="width: 80%; border: 1px solid #ffcc02; border-radius: 3px; padding: 5px; font-size: 12px; resize: vertical;" 
                  placeholder="اكتب السبب هنا..."></textarea>
    `;
    
    container.appendChild(reasonField);
}

function removeCheckboxItem(itemNumber) {
    const row = document.getElementById(`checkbox-row-${itemNumber}`);
    const reasonField = document.getElementById(`reason_${itemNumber}`);
    
    if (row) {
        row.remove();
        if (reasonField) reasonField.remove();
    }
}

// Dynamic narcotic patients management
let narcoticCounter = 3;

function addNarcoticPatient() {
    narcoticCounter++;
    const container = document.getElementById('narcotic-patients-container');
    
    const newPatient = document.createElement('div');
    newPatient.className = 'grid-item';
    newPatient.id = `narcotic-patient-${narcoticCounter}`;
    
    newPatient.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <label>اسم المريض / Patient Name:</label>
            <button type="button" onclick="removeNarcoticPatient(${narcoticCounter})" class="btn-remove">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <input type="text" name="narcotic_patient_name_${narcoticCounter}" placeholder="اكتب اسم المريض...">
        <div style="margin-top: 15px;">
            <label>الدور / Floor:</label>
            <input type="text" name="narcotic_patient_floor_${narcoticCounter}" placeholder="رقم الدور...">
        </div>
    `;
    
    container.appendChild(newPatient);
}

function removeNarcoticPatient(patientNumber) {
    const patient = document.getElementById(`narcotic-patient-${patientNumber}`);
    if (patient) {
        patient.remove();
    }
}

// Dynamic critical cases management
let criticalCaseCounter = 2;

function addCriticalCase() {
    criticalCaseCounter++;
    const container = document.getElementById('critical-cases-container');
    
    const newRow = document.createElement('tr');
    newRow.id = `critical-case-${criticalCaseCounter}`;
    
    newRow.innerHTML = `
        <td><input type="text" name="patient_name_${criticalCaseCounter}" class="form-control" placeholder="اسم المريض"></td>
        <td><input type="text" name="room_no_${criticalCaseCounter}" class="form-control" placeholder="رقم الغرفة"></td>
        <td>
            <div class="checkbox-grid">
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${criticalCaseCounter}[]" value="1"> □</label>
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${criticalCaseCounter}[]" value="2"> □</label>
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${criticalCaseCounter}[]" value="3"> □</label>
                <label class="checkbox-label"><input type="checkbox" name="critical_case_${criticalCaseCounter}[]" value="4"> □</label>
            </div>
        </td>
        <td>
            <button type="button" onclick="removeCriticalCase(${criticalCaseCounter})" class="btn-remove">
                <i class="fas fa-times"></i>
            </button>
        </td>
    `;
    
    container.appendChild(newRow);
}

function removeCriticalCase(caseNumber) {
    const row = document.getElementById(`critical-case-${caseNumber}`);
    if (row) {
        row.remove();
    }
}

// Auto-calculate total cases for internal reports
function calculateTotalCases() {
    const departmentInputs = document.querySelectorAll('input[name^="fourth_floor_cases"], input[name^="fifth_floor_cases"], input[name^="sixth_floor_cases"], input[name^="intermediate_care_cases"]');
    let total = 0;
    
    departmentInputs.forEach(input => {
        const value = parseInt(input.value) || 0;
        total += value;
    });
    
    const totalInput = document.querySelector('input[name="total_cases"]');
    if (totalInput) {
        totalInput.value = total;
    }
}

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    // Ensure default section is shown
    const defaultSection = document.getElementById('pharmacy-create-section');
    const defaultButton = document.querySelector('.toggle-btn');
    
    if (defaultSection && defaultButton) {
        document.querySelectorAll('.content-section').forEach(section => {
            section.classList.remove('active');
            section.style.display = 'none';
        });
        
        document.querySelectorAll('.toggle-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        
        defaultSection.classList.add('active');
        defaultSection.style.display = 'block';
        defaultButton.classList.add('active');
    }
    
    // Add event listeners for auto-calculation
    const departmentInputs = document.querySelectorAll('input[name^="fourth_floor_cases"], input[name^="fifth_floor_cases"], input[name^="sixth_floor_cases"], input[name^="intermediate_care_cases"]');
    departmentInputs.forEach(input => {
        input.addEventListener('input', calculateTotalCases);
    });
    
    calculateTotalCases();
});
</script>

<?php include 'includes/footer.php'; ?>
