<?php
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';
require_once 'includes/page_permissions_helper.php';

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "login.php");
    exit();
}

// Set current page for permissions
$currentPage = 'nursery';

// Check page access permission
PagePermissions::requirePageAccess($currentPage);

$database = new Database();
$conn = $database->getConnection();

$page_title = __('nursery_management_title') . ' - ' . __('system_name');

// معالجة إرسال النموذج
if ($_POST && isset($_POST['save_report'])) {
    try {
        $stmt = $conn->prepare("
            INSERT INTO nursery_pediatric_reports (
                report_date, pharmacist_name, shift_type, 
                intermediate_care_count, intermediate_care_patients,
                internal_care_count, internal_care_patients,
                nursery_count, nursery_patients,
                pediatric_care_count, pediatric_care_patients,
                intermediate_narcotic_cases, internal_narcotic_cases,
                nursery_narcotic_cases, pediatric_narcotic_cases,
                disposal_reports_cases,
                notes, created_by, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        // معالجة بيانات المرضى للرعاية المتوسطة
        $intermediate_patients = [];
        if (isset($_POST['intermediate_patient_name'])) {
            for ($i = 0; $i < count($_POST['intermediate_patient_name']); $i++) {
                if (!empty($_POST['intermediate_patient_name'][$i])) {
                    $intermediate_patients[] = [
                        'name' => $_POST['intermediate_patient_name'][$i],
                        'medication_dispensed' => $_POST['intermediate_medication_dispensed'][$i] ?? '',
                        'reason' => $_POST['intermediate_reason'][$i] ?? ''
                    ];
                }
            }
        }
        
        // معالجة بيانات المرضى للداخلي
        $internal_patients = [];
        if (isset($_POST['internal_patient_name'])) {
            for ($i = 0; $i < count($_POST['internal_patient_name']); $i++) {
                if (!empty($_POST['internal_patient_name'][$i])) {
                    $internal_patients[] = [
                        'name' => $_POST['internal_patient_name'][$i],
                        'medication_dispensed' => $_POST['internal_medication_dispensed'][$i] ?? '',
                        'reason' => $_POST['internal_reason'][$i] ?? ''
                    ];
                }
            }
        }
        
        // معالجة بيانات المرضى للحضانة
        $nursery_patients = [];
        if (isset($_POST['nursery_patient_name'])) {
            for ($i = 0; $i < count($_POST['nursery_patient_name']); $i++) {
                if (!empty($_POST['nursery_patient_name'][$i])) {
                    $nursery_patients[] = [
                        'name' => $_POST['nursery_patient_name'][$i],
                        'medication_dispensed' => $_POST['nursery_medication_dispensed'][$i] ?? '',
                        'reason' => $_POST['nursery_reason'][$i] ?? ''
                    ];
                }
            }
        }
        
        // معالجة بيانات المرضى لرعاية الأطفال
        $pediatric_patients = [];
        if (isset($_POST['pediatric_patient_name'])) {
            for ($i = 0; $i < count($_POST['pediatric_patient_name']); $i++) {
                if (!empty($_POST['pediatric_patient_name'][$i])) {
                    $pediatric_patients[] = [
                        'name' => $_POST['pediatric_patient_name'][$i],
                        'medication_dispensed' => $_POST['pediatric_medication_dispensed'][$i] ?? '',
                        'reason' => $_POST['pediatric_reason'][$i] ?? ''
                    ];
                }
            }
        }
        
        // معالجة بيانات الأدوية المخدرة
        $intermediate_narcotic_cases = [];
        if (isset($_POST['intermediate_narcotic_cases'])) {
            foreach ($_POST['intermediate_narcotic_cases'] as $case) {
                if (!empty(trim($case))) {
                    $intermediate_narcotic_cases[] = trim($case);
                }
            }
        }
        
        $internal_narcotic_cases = [];
        if (isset($_POST['internal_narcotic_cases'])) {
            foreach ($_POST['internal_narcotic_cases'] as $case) {
                if (!empty(trim($case))) {
                    $internal_narcotic_cases[] = trim($case);
                }
            }
        }
        
        $nursery_narcotic_cases = [];
        if (isset($_POST['nursery_narcotic_cases'])) {
            foreach ($_POST['nursery_narcotic_cases'] as $case) {
                if (!empty(trim($case))) {
                    $nursery_narcotic_cases[] = trim($case);
                }
            }
        }
        
        $pediatric_narcotic_cases = [];
        if (isset($_POST['pediatric_narcotic_cases'])) {
            foreach ($_POST['pediatric_narcotic_cases'] as $case) {
                if (!empty(trim($case))) {
                    $pediatric_narcotic_cases[] = trim($case);
                }
            }
        }
        
        $disposal_reports_cases = [];
        if (isset($_POST['disposal_reports_cases'])) {
            foreach ($_POST['disposal_reports_cases'] as $case) {
                if (!empty(trim($case))) {
                    $disposal_reports_cases[] = trim($case);
                }
            }
        }
        
        $stmt->execute([
            $_POST['report_date'],
            $_POST['pharmacist_name'],
            $_POST['shift_type'],
            $_POST['intermediate_care_count'] ?? 0,
            json_encode($intermediate_patients),
            $_POST['internal_care_count'] ?? 0,
            json_encode($internal_patients),
            $_POST['nursery_count'] ?? 0,
            json_encode($nursery_patients),
            $_POST['pediatric_care_count'] ?? 0,
            json_encode($pediatric_patients),
            json_encode($intermediate_narcotic_cases),
            json_encode($internal_narcotic_cases),
            json_encode($nursery_narcotic_cases),
            json_encode($pediatric_narcotic_cases),
            json_encode($disposal_reports_cases),
            $_POST['notes'] ?? '',
            $_SESSION['user_id'],
            date('Y-m-d H:i:s')
        ]);
        
        $success_message = __('report_saved_successfully');
        
    } catch (Exception $e) {
        $error_message = __('error_saving_report') . ": " . $e->getMessage();
    }
}

// معالجة الحذف
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    try {
        $stmt = $conn->prepare("DELETE FROM nursery_pediatric_reports WHERE id = ?");
        $stmt->execute([$_GET['delete']]);
        $success_message = __('report_deleted_success');
    } catch (Exception $e) {
        $error_message = __('report_delete_error') . ': ' . $e->getMessage();
    }
}

// جلب التقارير للعرض
$search_date = $_GET['search_date'] ?? '';
$search_pharmacist = $_GET['search_pharmacist'] ?? '';

$query = "SELECT r.*, u.username as created_by_name 
          FROM nursery_pediatric_reports r 
          LEFT JOIN users u ON r.created_by = u.id 
          WHERE 1=1";
$params = [];

if (!empty($search_date)) {
    $query .= " AND DATE(r.created_at) = ?";
    $params[] = $search_date;
}

if (!empty($search_pharmacist)) {
    $query .= " AND u.username LIKE ?";
    $params[] = "%$search_pharmacist%";
}

$query .= " ORDER BY r.created_at DESC";

try {
    $stmt = $conn->prepare($query);
    $stmt->execute($params);
    $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error_message = __('reports_fetch_error') . ': ' . $e->getMessage();
    $reports = [];
}

include 'includes/header.php';
?>

<style>
.toggle-buttons {
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
    gap: 10px;
}

.toggle-btn {
    background: #f8f9fa;
    border: 2px solid #dee2e6;
    color: #495057;
    padding: 15px 30px;
    border-radius: 25px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 16px;
}

.toggle-btn.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.toggle-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.content-section {
    display: none;
}

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

.card {
    border: none;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

.card-header {
    border-radius: 15px 15px 0 0 !important;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}

.action-btn {
    border-radius: 25px;
    padding: 12px 30px;
    font-weight: 600;
    margin: 5px;
    transition: all 0.3s ease;
    border: none;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.section-card {
    border: 1px solid #e3e6f0;
    border-radius: 10px;
    margin-bottom: 20px;
}

.section-header {
    background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
    color: white;
    padding: 15px 20px;
    border-radius: 10px 10px 0 0;
    font-weight: 600;
}

.patient-row {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
}

@media print {
    .no-print { display: none; }
}
</style>


    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <div>
            <h1 class="h3 mb-0" style="color: #667eea;">
                <i class="fas fa-baby me-2"></i>
                <?php echo __('nursery_management_title'); ?>
            </h1>
            <p class="text-muted mb-0"><?php echo __('nursery_management_subtitle'); ?></p>
        </div>
        <div>
            <?php if (PagePermissions::hasPermission($currentPage, 'print_nursery')): ?>
            <button type="button" class="btn btn-outline-primary action-btn" onclick="window.print()">
                <i class="fas fa-print me-2"></i> <?php echo __('print'); ?>
            </button>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'export_nursery_excel')): ?>
            <button type="button" class="btn btn-outline-success action-btn" onclick="exportToExcel()">
                <i class="fas fa-file-excel me-2"></i> <?php echo __('export_excel'); ?>
            </button>
            <?php endif; ?>
            
            <a href="index.php" class="btn btn-outline-secondary action-btn">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?> me-2"></i> <?php echo __('back'); ?>
            </a>
        </div>
    </div>

    <!-- Toggle Buttons -->
    <div class="toggle-buttons no-print">
        <?php if (PagePermissions::hasPermission($currentPage, 'add_nursery_record')): ?>
        <button class="toggle-btn active" onclick="showSection('create')">
            <i class="fas fa-plus me-2"></i>
            <?php echo __('new_nursery_report'); ?>
        </button>
        <?php endif; ?>
        
        <?php if (PagePermissions::hasPermission($currentPage, 'view_nursery')): ?>
        <button class="toggle-btn" onclick="showSection('view')">
            <i class="fas fa-eye me-2"></i>
            <?php echo __('saved_nursery_reports'); ?>
        </button>
        <?php endif; ?>
    </div>

    <!-- Create Report Section -->
    <div id="create-section" class="content-section active">
        <div class="card shadow-sm">
            <div class="card-header bg-success text-white text-center">
                <h3 class="mb-0"><?php echo __('nursery_report_title'); ?></h3>
                <small><?php echo __('nursery_report_subtitle'); ?></small>
            </div>
            
            <div class="card-body">
                <?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-circle me-2"></i>
                        <?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <form method="POST" class="needs-validation" novalidate>
                    <!-- معلومات التقرير الأساسية -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('date'); ?>:</label>
                            <input type="date" name="report_date" class="form-control" 
                                   value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('pharmacist_name'); ?>:</label>
                            <input type="text" name="pharmacist_name" class="form-control" 
                                   placeholder="<?php echo __('pharmacist_name'); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('shift_type'); ?>:</label>
                            <select name="shift_type" class="form-select" required>
                                <option value=""><?php echo __('select_shift_type'); ?></option>
                                <option value="صباحي"><?php echo __('morning_shift'); ?></option>
                                <option value="مسائي"><?php echo __('evening_shift'); ?></option>
                                <option value="ليلي"><?php echo __('night_shift'); ?></option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- الرعاية المتوسطة -->
                    <div class="card mb-4">
                        <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                            <h6 class="mb-0"><?php echo __('intermediate_care'); ?></h6>
                            <div class="bg-white text-info px-3 py-1 rounded">
                                <strong><?php echo __('intermediate_care_count_label'); ?>: <span id="intermediate_count_display">0</span></strong>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label"><?php echo __('intermediate_care_count_label'); ?>:</label>
                                    <input type="number" name="intermediate_care_count" id="intermediate_care_count" 
                                           class="form-control" min="0" value="0" placeholder="<?php echo __('cases_count'); ?>"
                                           onchange="updateCountDisplay('intermediate')">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label"><?php echo __('patients_data'); ?>:</label>
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="intermediate_patients_table">
                                        <thead class="table-primary">
                                            <tr>
                                                <th width="40%"><?php echo __('patient_name'); ?></th>
                                                <th width="25%"><?php echo __('medication_dispensed'); ?></th>
                                                <th width="30%"><?php echo __('reason'); ?></th>
                                                <th width="5%"><?php echo __('delete'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>
                                                    <input type="text" name="intermediate_patient_name[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="<?php echo __('patient_name'); ?>">
                                                </td>
                                                <td>
                                                    <select name="intermediate_medication_dispensed[]" 
                                                            class="form-select form-select-sm">
                                                        <option value=""><?php echo __('select'); ?></option>
                                                        <option value="نعم"><?php echo __('yes'); ?></option>
                                                        <option value="لا"><?php echo __('no'); ?></option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="text" name="intermediate_reason[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="<?php echo __('reason'); ?>">
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <button type="button" class="btn btn-sm btn-success" id="add_intermediate_patient">
                                    <i class="fas fa-plus me-1"></i> <?php echo __('add_patient'); ?>
                                </button>
                            </div>
                            
                            <!-- أسماء حالات الخروج -->
                            <div class="mb-3">
                                <label class="form-label"><?php echo __('discharge_cases_names'); ?>:</label>
                                <div id="intermediate_discharges">
                                    <div class="input-group mb-2">
                                        <input type="text" name="intermediate_discharge_name[]" 
                                               class="form-control" placeholder="<?php echo __('discharge_case_name'); ?>">
                                        <button type="button" class="btn btn-danger remove-discharge">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-sm btn-info" id="add_intermediate_discharge">
                                    <i class="fas fa-plus me-1"></i> <?php echo __('add_discharge_case'); ?>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- الداخلي -->
                    <div class="card mb-4">
                        <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
                            <h6 class="mb-0"><?php echo __('internal_care'); ?></h6>
                            <div class="bg-white text-warning px-3 py-1 rounded">
                                <strong><?php echo __('internal_care_count_label'); ?>: <span id="internal_count_display">0</span></strong>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label"><?php echo __('internal_care_count_label'); ?>:</label>
                                    <input type="number" name="internal_care_count" id="internal_care_count" 
                                           class="form-control" min="0" value="0" placeholder="<?php echo __('cases_count'); ?>"
                                           onchange="updateCountDisplay('internal')">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">بيانات المرضى:</label>
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="internal_patients_table">
                                        <thead class="table-primary">
                                            <tr>
                                                <th width="40%">اسم المريض</th>
                                                <th width="25%">هل تم صرف العلاج؟</th>
                                                <th width="30%">السبب</th>
                                                <th width="5%">حذف</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>
                                                    <input type="text" name="internal_patient_name[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="اسم المريض">
                                                </td>
                                                <td>
                                                    <select name="internal_medication_dispensed[]" 
                                                            class="form-select form-select-sm">
                                                        <option value="">اختر</option>
                                                        <option value="نعم">نعم</option>
                                                        <option value="لا">لا</option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="text" name="internal_reason[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="السبب">
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <button type="button" class="btn btn-sm btn-success" id="add_internal_patient">
                                    <i class="fas fa-plus me-1"></i> إضافة مريض
                                </button>
                            </div>
                            
                            <!-- أسماء حالات الخروج -->
                            <div class="mb-3">
                                <label class="form-label">أسماء حالات الخروج:</label>
                                <div id="internal_discharges">
                                    <div class="input-group mb-2">
                                        <input type="text" name="internal_discharge_name[]" 
                                               class="form-control" placeholder="اسم حالة الخروج">
                                        <button type="button" class="btn btn-danger remove-discharge">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-sm btn-info" id="add_internal_discharge">
                                    <i class="fas fa-plus me-1"></i> إضافة حالة خروج
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- الحضانة -->
                    <div class="card mb-4">
                        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                            <h6 class="mb-0"><?php echo __('nursery'); ?></h6>
                            <div class="bg-white text-primary px-3 py-1 rounded">
                                <strong><?php echo __('nursery_cases_count_label'); ?>: <span id="nursery_count_display">0</span></strong>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label"><?php echo __('nursery_cases_count_label'); ?>:</label>
                                    <input type="number" name="nursery_count" id="nursery_count" 
                                           class="form-control" min="0" value="0" placeholder="<?php echo __('cases_count'); ?>"
                                           onchange="updateCountDisplay('nursery')">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">بيانات المرضى:</label>
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="nursery_patients_table">
                                        <thead class="table-primary">
                                            <tr>
                                                <th width="40%">اسم المريض</th>
                                                <th width="25%">هل تم صرف العلاج؟</th>
                                                <th width="30%">السبب</th>
                                                <th width="5%">حذف</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>
                                                    <input type="text" name="nursery_patient_name[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="اسم المريض">
                                                </td>
                                                <td>
                                                    <select name="nursery_medication_dispensed[]" 
                                                            class="form-select form-select-sm">
                                                        <option value="">اختر</option>
                                                        <option value="نعم">نعم</option>
                                                        <option value="لا">لا</option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="text" name="nursery_reason[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="السبب">
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <button type="button" class="btn btn-sm btn-success" id="add_nursery_patient">
                                    <i class="fas fa-plus me-1"></i> إضافة مريض
                                </button>
                            </div>
                            
                            <!-- أسماء حالات الخروج -->
                            <div class="mb-3">
                                <label class="form-label">أسماء حالات الخروج:</label>
                                <div id="nursery_discharges">
                                    <div class="input-group mb-2">
                                        <input type="text" name="nursery_discharge_name[]" 
                                               class="form-control" placeholder="اسم حالة الخروج">
                                        <button type="button" class="btn btn-danger remove-discharge">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-sm btn-info" id="add_nursery_discharge">
                                    <i class="fas fa-plus me-1"></i> إضافة حالة خروج
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- رعاية الأطفال -->
                    <div class="card mb-4">
                        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                            <h6 class="mb-0"><?php echo __('pediatric'); ?></h6>
                            <div class="bg-white text-success px-3 py-1 rounded">
                                <strong><?php echo __('pediatric_care_count'); ?>: <span id="pediatric_count_display">0</span></strong>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label"><?php echo __('pediatric_care_count'); ?>:</label>
                                    <input type="number" name="pediatric_care_count" id="pediatric_care_count" 
                                           class="form-control" min="0" value="0" placeholder="<?php echo __('cases_count'); ?>"
                                           onchange="updateCountDisplay('pediatric')">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">بيانات المرضى:</label>
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="pediatric_patients_table">
                                        <thead class="table-primary">
                                            <tr>
                                                <th width="40%">اسم المريض</th>
                                                <th width="25%">هل تم صرف العلاج؟</th>
                                                <th width="30%">السبب</th>
                                                <th width="5%">حذف</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>
                                                    <input type="text" name="pediatric_patient_name[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="اسم المريض">
                                                </td>
                                                <td>
                                                    <select name="pediatric_medication_dispensed[]" 
                                                            class="form-select form-select-sm">
                                                        <option value="">اختر</option>
                                                        <option value="نعم">نعم</option>
                                                        <option value="لا">لا</option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="text" name="pediatric_reason[]" 
                                                           class="form-control form-control-sm" 
                                                           placeholder="السبب">
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <button type="button" class="btn btn-sm btn-success" id="add_pediatric_patient">
                                    <i class="fas fa-plus me-1"></i> إضافة مريض
                                </button>
                            </div>
                            
                            <!-- أسماء حالات الخروج -->
                            <div class="mb-3">
                                <label class="form-label">أسماء حالات الخروج:</label>
                                <div id="pediatric_discharges">
                                    <div class="input-group mb-2">
                                        <input type="text" name="pediatric_discharge_name[]" 
                                               class="form-control" placeholder="اسم حالة الخروج">
                                        <button type="button" class="btn btn-danger remove-discharge">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-sm btn-info" id="add_pediatric_discharge">
                                    <i class="fas fa-plus me-1"></i> إضافة حالة خروج
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- قسم الأدوية المخدرة -->
                    <div class="card mb-4">
                        <div class="card-header bg-danger text-white">
                            <h6 class="mb-0"><?php echo __('narcotic_drugs'); ?></h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <!-- أسماء حالات على أدوية مخدرة - الرعاية المتوسطة -->
                                <div class="col-md-6 mb-4">
                                    <h6 class="text-info">أسماء حالات على أدوية مخدرة - الرعاية المتوسطة:</h6>
                                    <div id="intermediate_narcotic_list">
                                        <div class="input-group mb-2">
                                            <input type="text" name="intermediate_narcotic_cases[]" 
                                                   class="form-control form-control-sm" 
                                                   placeholder="اسم المريض على أدوية مخدرة">
                                            <button type="button" class="btn btn-sm btn-danger remove-narcotic-item">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-warning add-narcotic-btn" 
                                            data-target="intermediate_narcotic_list" data-name="intermediate_narcotic_cases[]">
                                        <i class="fas fa-plus me-1"></i> إضافة حالة
                                    </button>
                                </div>
                                
                                <!-- أسماء حالات على أدوية مخدرة - الداخلي -->
                                <div class="col-md-6 mb-4">
                                    <h6 class="text-warning">أسماء حالات على أدوية مخدرة - الداخلي:</h6>
                                    <div id="internal_narcotic_list">
                                        <div class="input-group mb-2">
                                            <input type="text" name="internal_narcotic_cases[]" 
                                                   class="form-control form-control-sm" 
                                                   placeholder="اسم المريض على أدوية مخدرة">
                                            <button type="button" class="btn btn-sm btn-danger remove-narcotic-item">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-warning add-narcotic-btn" 
                                            data-target="internal_narcotic_list" data-name="internal_narcotic_cases[]">
                                        <i class="fas fa-plus me-1"></i> إضافة حالة
                                    </button>
                                </div>
                                
                                <!-- أسماء حالات على أدوية مخدرة - الحضانة -->
                                <div class="col-md-6 mb-4">
                                    <h6 class="text-primary">أسماء حالات على أدوية مخدرة - الحضانة:</h6>
                                    <div id="nursery_narcotic_list">
                                        <div class="input-group mb-2">
                                            <input type="text" name="nursery_narcotic_cases[]" 
                                                   class="form-control form-control-sm" 
                                                   placeholder="اسم المريض على أدوية مخدرة">
                                            <button type="button" class="btn btn-sm btn-danger remove-narcotic-item">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-warning add-narcotic-btn" 
                                            data-target="nursery_narcotic_list" data-name="nursery_narcotic_cases[]">
                                        <i class="fas fa-plus me-1"></i> إضافة حالة
                                    </button>
                                </div>
                                
                                <!-- أسماء حالات على أدوية مخدرة - رعاية الأطفال -->
                                <div class="col-md-6 mb-4">
                                    <h6 class="text-success">أسماء حالات على أدوية مخدرة - رعاية الأطفال:</h6>
                                    <div id="pediatric_narcotic_list">
                                        <div class="input-group mb-2">
                                            <input type="text" name="pediatric_narcotic_cases[]" 
                                                   class="form-control form-control-sm" 
                                                   placeholder="اسم المريض على أدوية مخدرة">
                                            <button type="button" class="btn btn-sm btn-danger remove-narcotic-item">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-warning add-narcotic-btn" 
                                            data-target="pediatric_narcotic_list" data-name="pediatric_narcotic_cases[]">
                                        <i class="fas fa-plus me-1"></i> إضافة حالة
                                    </button>
                                </div>
                            </div>
                            
                            <hr class="my-4">
                            
                            <!-- محاضر إعدام الأدوية المخدرة -->
                            <h5 class="text-danger mb-3">أسماء حالات تم عمل محاضر إعدام للأدوية المخدرة لهم:</h5>
                            <div class="row">
                                <div class="col-12">
                                    <div id="disposal_reports_list">
                                        <div class="input-group mb-2">
                                            <input type="text" name="disposal_reports_cases[]" 
                                                   class="form-control" 
                                                   placeholder="اسم المريض الذي تم عمل محضر إعدام أدوية مخدرة له">
                                            <button type="button" class="btn btn-danger remove-disposal-item">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-danger add-disposal-btn" 
                                            data-target="disposal_reports_list" data-name="disposal_reports_cases[]">
                                        <i class="fas fa-plus me-1"></i> إضافة محضر إعدام
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- الملاحظات -->
                    <div class="mb-4">
                        <label class="form-label"><?php echo __('additional_notes'); ?>:</label>
                        <textarea name="notes" class="form-control" rows="4" 
                                  placeholder="<?php echo __('additional_notes'); ?>..."></textarea>
                    </div>
                    
                    <!-- أزرار الحفظ والطباعة -->
                    <div class="d-flex gap-2 justify-content-end no-print">
                        <button type="submit" name="save_report" class="btn btn-success">
                            <i class="fas fa-save me-1"></i> <?php echo __('save_report'); ?>
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="window.print()">
                            <i class="fas fa-print me-1"></i> <?php echo __('print'); ?>
                        </button>
                        <a href="view_nursery_reports_v2.php" class="btn btn-info">
                            <i class="fas fa-list me-1"></i> <?php echo __('view_reports'); ?>
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Reports Section -->
    <div id="view-section" class="content-section">
        <div class="card">
            <div class="card-header text-white d-flex justify-content-between align-items-center">
                <h4 class="mb-0">
                    <i class="fas fa-clipboard-list me-2"></i>
                    <?php echo __('saved_nursery_reports'); ?>
                </h4>
            </div>
            
            <div class="card-body">
                <?php if (isset($success_message) && isset($_GET['delete'])): ?>
                    <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; ?>
                
                <!-- نموذج البحث -->
                <form method="GET" class="mb-4 no-print">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('search_by_date'); ?>:</label>
                            <input type="date" name="search_date" class="form-control" 
                                   value="<?php echo htmlspecialchars($search_date); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('search_by_pharmacist'); ?>:</label>
                            <input type="text" name="search_pharmacist" class="form-control" 
                                   placeholder="<?php echo __('pharmacist_name'); ?>" 
                                   value="<?php echo htmlspecialchars($search_pharmacist); ?>">
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="fas fa-search me-1"></i> <?php echo __('search'); ?>
                            </button>
                            <a href="nursery_management.php" class="btn btn-secondary">
                                <i class="fas fa-refresh me-1"></i> <?php echo __('reset'); ?>
                            </a>
                        </div>
                    </div>
                </form>
                
                <!-- جدول التقارير -->
                <?php if (count($reports) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th><?php echo __('date'); ?></th>
                                <th><?php echo __('pharmacist'); ?></th>
                                <th><?php echo __('shift_type'); ?></th>
                                <th><?php echo __('intermediate_care'); ?></th>
                                <th><?php echo __('internal_care'); ?></th>
                                <th><?php echo __('nursery'); ?></th>
                                <th><?php echo __('pediatric'); ?></th>
                                <th><?php echo __('disposal_records'); ?></th>
                                <th><?php echo __('actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($reports as $report): ?>
                            <tr>
                                <td>
                                    <strong><?php echo date('d/m/Y', strtotime($report['report_date'])); ?></strong>
                                </td>
                                <td>
                                    <i class="fas fa-user-md text-primary me-1"></i>
                                    <?php echo htmlspecialchars($report['pharmacist_name']); ?>
                                </td>
                                <td>
                                    <span class="badge bg-info"><?php echo ucfirst($report['shift_type']); ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-primary"><?php echo $report['intermediate_care_count'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-success"><?php echo $report['internal_care_count'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-warning text-dark"><?php echo $report['nursery_count'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-danger"><?php echo $report['pediatric_care_count'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-dark"><?php 
                                        $disposal_count = 0;
                                        if (!empty($report['disposal_reports_cases'])) {
                                            $disposal_data = json_decode($report['disposal_reports_cases'], true);
                                            $disposal_count = is_array($disposal_data) ? count($disposal_data) : 0;
                                        }
                                        echo $disposal_count; 
                                    ?></span>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="print_nursery_report.php?id=<?php echo $report['id']; ?>" 
                                           class="btn btn-outline-secondary" title="<?php echo __('print'); ?>" target="_blank">
                                            <i class="fas fa-print"></i>
                                        </a>
                                        <a href="nursery_management.php?delete=<?php echo $report['id']; ?>" 
                                           class="btn btn-outline-danger" title="<?php echo __('delete'); ?>"
                                           onclick="return confirm('<?php echo __('confirm_delete_report'); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php else: ?>
                <div class="text-center py-5">
                    <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted"><?php echo __('no_saved_reports'); ?></h5>
                    <p class="text-muted"><?php echo __('no_nursery_reports_message'); ?></p>
                    <button class="btn btn-primary" onclick="showSection('create')">
                        <i class="fas fa-plus me-1"></i> <?php echo __('new_nursery_report'); ?>
                    </button>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

<script>
// دالة لتحديث عرض العدد في الهيدر
function updateCountDisplay(section) {
    const input = document.getElementById(section + '_care_count') || document.getElementById(section + '_count');
    const display = document.getElementById(section + '_count_display');
    if (input && display) {
        display.textContent = input.value || '0';
    }
}

function showSection(section) {
    // Hide all sections
    document.querySelectorAll('.content-section').forEach(function(el) {
        el.classList.remove('active');
    });
    
    // Remove active class from all buttons
    document.querySelectorAll('.toggle-btn').forEach(function(btn) {
        btn.classList.remove('active');
    });
    
    // Show selected section
    document.getElementById(section + '-section').classList.add('active');
    
    // Add active class to clicked button
    event.target.classList.add('active');
}

document.addEventListener('DOMContentLoaded', function() {
    // إضافة مريض للرعاية المتوسطة
    document.getElementById('add_intermediate_patient').addEventListener('click', function() {
        const tbody = document.querySelector('#intermediate_patients_table tbody');
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td>
                <input type="text" name="intermediate_patient_name[]" 
                       class="form-control form-control-sm" 
                       placeholder="اسم المريض">
            </td>
            <td>
                <select name="intermediate_medication_dispensed[]" 
                        class="form-select form-select-sm">
                    <option value="">اختر</option>
                    <option value="نعم">نعم</option>
                    <option value="لا">لا</option>
                </select>
            </td>
            <td>
                <input type="text" name="intermediate_reason[]" 
                       class="form-control form-control-sm" 
                       placeholder="السبب">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
    });
    
    // إضافة مريض للداخلي
    document.getElementById('add_internal_patient').addEventListener('click', function() {
        const tbody = document.querySelector('#internal_patients_table tbody');
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td>
                <input type="text" name="internal_patient_name[]" 
                       class="form-control form-control-sm" 
                       placeholder="اسم المريض">
            </td>
            <td>
                <select name="internal_medication_dispensed[]" 
                        class="form-select form-select-sm">
                    <option value="">اختر</option>
                    <option value="نعم">نعم</option>
                    <option value="لا">لا</option>
                </select>
            </td>
            <td>
                <input type="text" name="internal_reason[]" 
                       class="form-control form-control-sm" 
                       placeholder="السبب">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
    });
    
    // إضافة مريض للحضانة
    document.getElementById('add_nursery_patient').addEventListener('click', function() {
        const tbody = document.querySelector('#nursery_patients_table tbody');
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td>
                <input type="text" name="nursery_patient_name[]" 
                       class="form-control form-control-sm" 
                       placeholder="اسم المريض">
            </td>
            <td>
                <select name="nursery_medication_dispensed[]" 
                        class="form-select form-select-sm">
                    <option value="">اختر</option>
                    <option value="نعم">نعم</option>
                    <option value="لا">لا</option>
                </select>
            </td>
            <td>
                <input type="text" name="nursery_reason[]" 
                       class="form-control form-control-sm" 
                       placeholder="السبب">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
    });
    
    // إضافة مريض لرعاية الأطفال
    document.getElementById('add_pediatric_patient').addEventListener('click', function() {
        const tbody = document.querySelector('#pediatric_patients_table tbody');
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td>
                <input type="text" name="pediatric_patient_name[]" 
                       class="form-control form-control-sm" 
                       placeholder="اسم المريض">
            </td>
            <td>
                <select name="pediatric_medication_dispensed[]" 
                        class="form-select form-select-sm">
                    <option value="">اختر</option>
                    <option value="نعم">نعم</option>
                    <option value="لا">لا</option>
                </select>
            </td>
            <td>
                <input type="text" name="pediatric_reason[]" 
                       class="form-control form-control-sm" 
                       placeholder="السبب">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger remove-patient-row">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
    });
    
    // حذف صف مريض
    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-patient-row')) {
            const row = e.target.closest('tr');
            const tbody = row.parentElement;
            if (tbody.children.length > 1) {
                row.remove();
            }
        }
    });
    
    // إضافة حالة أدوية مخدرة
    document.addEventListener('click', function(e) {
        if (e.target.closest('.add-narcotic-btn')) {
            const button = e.target.closest('.add-narcotic-btn');
            const targetId = button.getAttribute('data-target');
            const inputName = button.getAttribute('data-name');
            const container = document.getElementById(targetId);
            
            const newItem = document.createElement('div');
            newItem.className = 'input-group mb-2';
            newItem.innerHTML = `
                <input type="text" name="${inputName}" 
                       class="form-control form-control-sm" 
                       placeholder="اسم المريض على أدوية مخدرة">
                <button type="button" class="btn btn-sm btn-danger remove-narcotic-item">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            container.appendChild(newItem);
        }
    });
    
    // حذف حالة أدوية مخدرة
    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-narcotic-item')) {
            const item = e.target.closest('.input-group');
            const container = item.parentElement;
            if (container.children.length > 1) {
                item.remove();
            }
        }
    });
    
    // إضافة محضر إعدام
    document.addEventListener('click', function(e) {
        if (e.target.closest('.add-disposal-btn')) {
            const button = e.target.closest('.add-disposal-btn');
            const targetId = button.getAttribute('data-target');
            const inputName = button.getAttribute('data-name');
            const container = document.getElementById(targetId);
            
            const newItem = document.createElement('div');
            newItem.className = 'input-group mb-2';
            newItem.innerHTML = `
                <input type="text" name="${inputName}" 
                       class="form-control" 
                       placeholder="اسم المريض الذي تم عمل محضر إعدام أدوية مخدرة له">
                <button type="button" class="btn btn-danger remove-disposal-item">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            container.appendChild(newItem);
        }
    });
    
    // حذف محضر إعدام
    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-disposal-item')) {
            const item = e.target.closest('.input-group');
            const container = item.parentElement;
            if (container.children.length > 1) {
                item.remove();
            }
        }
    });
    
    // إضافة حالة خروج
    document.addEventListener('click', function(e) {
        if (e.target.id === 'add_intermediate_discharge') {
            const container = document.getElementById('intermediate_discharges');
            const newItem = document.createElement('div');
            newItem.className = 'input-group mb-2';
            newItem.innerHTML = `
                <input type="text" name="intermediate_discharge_name[]" 
                       class="form-control" placeholder="اسم حالة الخروج">
                <button type="button" class="btn btn-danger remove-discharge">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            container.appendChild(newItem);
        }
        
        if (e.target.id === 'add_internal_discharge') {
            const container = document.getElementById('internal_discharges');
            const newItem = document.createElement('div');
            newItem.className = 'input-group mb-2';
            newItem.innerHTML = `
                <input type="text" name="internal_discharge_name[]" 
                       class="form-control" placeholder="اسم حالة الخروج">
                <button type="button" class="btn btn-danger remove-discharge">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            container.appendChild(newItem);
        }
        
        if (e.target.id === 'add_nursery_discharge') {
            const container = document.getElementById('nursery_discharges');
            const newItem = document.createElement('div');
            newItem.className = 'input-group mb-2';
            newItem.innerHTML = `
                <input type="text" name="nursery_discharge_name[]" 
                       class="form-control" placeholder="اسم حالة الخروج">
                <button type="button" class="btn btn-danger remove-discharge">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            container.appendChild(newItem);
        }
        
        if (e.target.id === 'add_pediatric_discharge') {
            const container = document.getElementById('pediatric_discharges');
            const newItem = document.createElement('div');
            newItem.className = 'input-group mb-2';
            newItem.innerHTML = `
                <input type="text" name="pediatric_discharge_name[]" 
                       class="form-control" placeholder="اسم حالة الخروج">
                <button type="button" class="btn btn-danger remove-discharge">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            container.appendChild(newItem);
        }
    });
    
    // حذف حالة خروج
    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-discharge')) {
            const item = e.target.closest('.input-group');
            const container = item.parentElement;
            if (container.children.length > 1) {
                item.remove();
            }
        }
    });
    
    // التحقق من صحة النموذج
    const forms = document.querySelectorAll('.needs-validation');
    Array.prototype.slice.call(forms).forEach(function(form) {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
});
</script>

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