<?php
session_start();
require_once 'config/database.php';
require_once 'includes/translation.php';
require_once 'includes/functions.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 = 'icu';

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

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

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

// معالجة إرسال النموذج
if ($_POST && isset($_POST['save_report'])) {
    try {
        // التحقق من وجود تقرير مسبق لنفس التاريخ والصيدلي
        $check_stmt = $conn->prepare("
            SELECT id FROM icu_daily_reports 
            WHERE report_date = ? AND pharmacist_shift = ?
        ");
        $check_stmt->execute([$_POST['report_date'], $_POST['pharmacist_shift']]);
        $existing_report = $check_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existing_report && !isset($_POST['confirm_duplicate'])) {
            $warning_message = __('duplicate_report_warning');
            $show_confirm = true;
        } else {
            $stmt = $conn->prepare("
                INSERT INTO icu_daily_reports (
                    report_date, pharmacist_shift, pharmacists_count, no_of_pt, total_patients, 
                    total_discharged, icu_cases, cardiac_care_cases, critical_cases, dialysis_cases,
                    narcotic_cases, narcotic_disposal_reports, patients_data, patients_isolation, notes, 
                    created_by, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $patients_data = [];
            if (isset($_POST['patient_name'])) {
                for ($i = 0; $i < count($_POST['patient_name']); $i++) {
                    if (!empty($_POST['patient_name'][$i])) {
                        $patients_data[] = [
                            'name' => $_POST['patient_name'][$i],
                            'dama' => $_POST['dama'][$i] ?? '',
                            'improved' => $_POST['improved'][$i] ?? '',
                            'discharged' => $_POST['discharged'][$i] ?? '',
                            'reason' => $_POST['reason'][$i] ?? ''
                        ];
                    }
                }
            }
            
            $isolation_notes = [];
            if (isset($_POST['isolation_patient_name'])) {
                for ($i = 0; $i < count($_POST['isolation_patient_name']); $i++) {
                    if (!empty($_POST['isolation_patient_name'][$i])) {
                        $isolation_notes[] = [
                            'name' => $_POST['isolation_patient_name'][$i],
                            'floor' => $_POST['isolation_floor'][$i] ?? ''
                        ];
                    }
                }
            }
            
            $stmt->execute([
                $_POST['report_date'],
                $_POST['pharmacist_shift'],
                $_POST['pharmacists_count'] ?? 0,
                $_POST['no_of_pt'],
                $_POST['total_patients'],
                $_POST['total_discharged'],
                $_POST['icu_cases'] ?? 0,
                $_POST['cardiac_care_cases'] ?? 0,
                $_POST['critical_cases'] ?? 0,
                $_POST['dialysis_cases'] ?? 0,
                $_POST['narcotic_cases'] ?? 0,
                $_POST['narcotic_disposal_reports'] ?? 0,
                json_encode($patients_data),
                json_encode($isolation_notes),
                $_POST['notes'] ?? '',
                $_SESSION['user_id']
            ]);
            
            $success_message = __('report_saved_successfully');
        }
        
    } catch (Exception $e) {
        $error_message = __('error_saving_report') . ": " . $e->getMessage();
    }
}

// معالجة البحث والفلترة للعرض
$search_date = $_GET['search_date'] ?? '';
$search_pharmacist = $_GET['search_pharmacist'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// بناء استعلام البحث
$where_conditions = [];
$params = [];

if (!empty($search_date)) {
    $where_conditions[] = "report_date = ?";
    $params[] = $search_date;
}

if (!empty($search_pharmacist)) {
    $where_conditions[] = "pharmacist_shift LIKE ?";
    $params[] = "%$search_pharmacist%";
}

$where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// استعلام العد الإجمالي
$count_sql = "SELECT COUNT(*) as total FROM icu_daily_reports $where_clause";
$count_stmt = $conn->prepare($count_sql);
$count_stmt->execute($params);
$total_records = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];
$total_pages = ceil($total_records / $limit);

// استعلام البيانات
$sql = "
    SELECT 
        idr.*,
        u.full_name as created_by_name
    FROM icu_daily_reports idr
    LEFT JOIN users u ON idr.created_by = u.id
    $where_clause
    ORDER BY idr.report_date DESC, idr.created_at DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $conn->prepare($sql);
$stmt->execute($params);
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
?>


<style>
.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);
}

.isolation-card {
    transition: all 0.3s ease;
    animation: slideIn 0.3s ease;
}

.isolation-card:hover {
    box-shadow: 0 5px 20px rgba(255, 193, 7, 0.3);
    transform: translateY(-2px);
}

@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.remove-isolation {
    transition: all 0.2s ease;
}

.remove-isolation:hover {
    transform: scale(1.1);
    box-shadow: 0 3px 10px rgba(220, 53, 69, 0.3);
}

@media print {
    .no-print { display: none; }
    .isolation-card {
        page-break-inside: avoid;
        border: 1px solid #ffc107 !important;
        box-shadow: none !important;
    }
}
</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-hospital me-2"></i>
                <?php echo __('icu_management_title'); ?>
            </h1>
            <p class="text-muted mb-0"><?php echo __('icu_management_subtitle'); ?></p>
        </div>
        <div>
            <?php if (PagePermissions::hasPermission($currentPage, 'print_icu')): ?>
            <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_icu_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_icu_record')): ?>
        <button class="toggle-btn active" onclick="showSection('create')">
            <i class="fas fa-plus me-2"></i>
            <?php echo __('new_icu_report'); ?>
        </button>
        <?php endif; ?>
        
        <?php if (PagePermissions::hasPermission($currentPage, 'view_icu')): ?>
        <button class="toggle-btn" onclick="showSection('view')">
            <i class="fas fa-eye me-2"></i>
            <?php echo __('saved_icu_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-primary text-white text-center">
                <h3 class="mb-0"><?php echo __('icu_report'); ?></h3>
                <small><?php echo __('clinical_pharmacy_title'); ?></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($warning_message) && isset($show_confirm)): ?>
                    <div class="alert alert-warning no-print">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?php echo $warning_message; ?>
                        <div class="mt-3">
                            <form method="POST" style="display: inline;">
                                <?php foreach ($_POST as $key => $value): ?>
                                    <?php if (is_array($value)): ?>
                                        <?php foreach ($value as $index => $item): ?>
                                            <input type="hidden" name="<?php echo $key; ?>[]" value="<?php echo htmlspecialchars($item); ?>">
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <input type="hidden" name="<?php echo $key; ?>" value="<?php echo htmlspecialchars($value); ?>">
                                    <?php endif; ?>
                                <?php endforeach; ?>
                                <input type="hidden" name="confirm_duplicate" value="1">
                                <button type="submit" class="btn btn-warning me-2">
                                    <i class="fas fa-check me-1"></i><?php echo __('yes_create_additional_report'); ?>
                                </button>
                            </form>
                            <button type="button" class="btn btn-secondary" onclick="window.location.reload()">
                                <i class="fas fa-times me-1"></i><?php echo __('cancel'); ?>
                            </button>
                        </div>
                    </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 <?php echo (isset($show_confirm) ? 'style="display:none;"' : ''); ?>>
                    <!-- معلومات التقرير الأساسية -->
                    <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_shift" class="form-control" 
                                   placeholder="<?php echo __('pharmacist_name'); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('pharmacists_count'); ?>:</label>
                            <input type="number" name="pharmacists_count" class="form-control" 
                                   min="0" value="0" placeholder="<?php echo __('pharmacists_count'); ?>" required>
                        </div>
                    </div>
                    
                    <!-- إحصائيات المرضى -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('patients_count'); ?>:</label>
                            <input type="number" name="no_of_pt" class="form-control" 
                                   min="0" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('total_patients'); ?>:</label>
                            <input type="number" name="total_patients" class="form-control" 
                                   min="0" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo __('discharged_patients'); ?>:</label>
                            <input type="number" name="total_discharged" class="form-control" 
                                   min="0" required>
                        </div>
                    </div>
                    
                    <!-- إحصائيات الحالات المختلفة -->
                    <div class="card mb-4">
                        <div class="card-header bg-info text-white">
                            <h6 class="mb-0"><?php echo __('statistics'); ?></h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('icu_cases'); ?>:</label>
                                    <input type="number" name="icu_cases" class="form-control" 
                                           min="0" value="0" placeholder="<?php echo __('icu_cases'); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('ccu_cases'); ?>:</label>
                                    <input type="number" name="cardiac_care_cases" class="form-control" 
                                           min="0" value="0" placeholder="<?php echo __('ccu_cases'); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('critical_cases'); ?>:</label>
                                    <input type="number" name="critical_cases" class="form-control" 
                                           min="0" value="0" placeholder="<?php echo __('critical_cases'); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('dialysis_cases'); ?>:</label>
                                    <input type="number" name="dialysis_cases" class="form-control" 
                                           min="0" value="0" placeholder="<?php echo __('dialysis_cases'); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('narcotic_cases'); ?>:</label>
                                    <input type="number" name="narcotic_cases" class="form-control" 
                                           min="0" value="0" placeholder="<?php echo __('narcotic_cases'); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('narcotic_disposal_reports'); ?>:</label>
                                    <input type="number" name="narcotic_disposal_reports" class="form-control" 
                                           min="0" value="0" placeholder="<?php echo __('narcotic_disposal_reports'); ?>">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- جدول المرضى -->
                    <div class="mb-4">
                        <h5 class="mb-3"><?php echo __('patients_data'); ?></h5>
                        <div class="table-responsive">
                            <table class="table table-bordered" id="patientsTable">
                                <thead class="table-primary">
                                    <tr>
                                        <th width="25%"><?php echo __('patient_name'); ?><br><small>Patient's name</small></th>
                                        <th width="15%">DAMA</th>
                                        <th width="15%"><?php echo __('improved'); ?><br><small>Improved</small></th>
                                        <th width="20%"><?php echo __('discharged'); ?><br><small>Discharged medication (not Approved/Disapproved)</small></th>
                                        <th width="20%"><?php echo __('reason'); ?><br><small>Reason</small></th>
                                        <th width="5%"><?php echo __('delete'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php for ($i = 0; $i < 8; $i++): ?>
                                    <tr>
                                        <td data-label="<?php echo __('patient_name'); ?>">
                                            <input type="text" name="patient_name[]" 
                                                   class="form-control form-control-sm" 
                                                   placeholder="<?php echo __('patient_name'); ?>">
                                        </td>
                                        <td data-label="DAMA">
                                            <div class="form-check">
                                                <input type="checkbox" name="dama[]" 
                                                       value="1" class="form-check-input">
                                            </div>
                                        </td>
                                        <td data-label="<?php echo __('improved'); ?>">
                                            <div class="form-check">
                                                <input type="checkbox" name="improved[]" 
                                                       value="1" class="form-check-input">
                                            </div>
                                        </td>
                                        <td data-label="<?php echo __('discharged'); ?>">
                                            <select name="discharged[]" class="form-select form-select-sm">
                                                <option value=""><?php echo __('select'); ?></option>
                                                <option value="approved"><?php echo __('approved'); ?></option>
                                                <option value="disapproved"><?php echo __('disapproved'); ?></option>
                                            </select>
                                        </td>
                                        <td data-label="<?php echo __('reason'); ?>">
                                            <input type="text" name="reason[]" 
                                                   class="form-control form-control-sm" 
                                                   placeholder="<?php echo __('reason'); ?>">
                                        </td>
                                        <td data-label="">
                                            <button type="button" class="btn btn-sm btn-danger remove-row">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endfor; ?>
                                </tbody>
                            </table>
                        </div>
                        <button type="button" class="btn btn-sm btn-success" id="addPatientRow">
                            <i class="fas fa-plus me-1"></i> <?php echo __('add_patient'); ?>
                        </button>
                    </div>
                    
                    <!-- المرضى في العزل -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><?php echo __('patients_isolation'); ?>:</h5>
                            <button type="button" class="btn btn-success" id="addIsolationPatient" style="border-radius: 25px; padding: 10px 25px;">
                                <i class="fas fa-plus me-2"></i> <?php echo __('add_patient'); ?>
                            </button>
                        </div>
                        
                        <div id="isolationContainer" class="row">
                            <?php for ($i = 1; $i <= 2; $i++): ?>
                            <div class="col-md-4 mb-3">
                                <div class="isolation-card" style="background: #f8f9fa; border: 2px solid #dee2e6; border-radius: 15px; padding: 20px; position: relative; min-height: 200px;">
                                    <button type="button" class="btn btn-sm btn-danger remove-isolation" style="position: absolute; top: 10px; left: 10px; border-radius: 50%; width: 30px; height: 30px; padding: 0;">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    
                                    <div class="mb-3">
                                        <label class="form-label text-end d-block fw-bold"><?php echo __('patient_name'); ?>:</label>
                                        <input type="text" name="isolation_patient_name[]" 
                                               class="form-control text-end" 
                                               placeholder="<?php echo __('patient_name'); ?>...">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label text-end d-block fw-bold"><?php echo __('floor'); ?>:</label>
                                        <input type="text" name="isolation_floor[]" 
                                               class="form-control text-end" 
                                               placeholder="<?php echo __('floor'); ?>...">
                                    </div>
                                </div>
                            </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                    
                    <!-- الملاحظات -->
                    <div class="mb-4">
                        <label class="form-label"><?php echo __('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-primary">
                            <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>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Reports Section -->
    <div id="view-section" class="content-section">
        <div class="card shadow-sm">
            <div class="card-header bg-primary 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_icu_reports'); ?>
                </h4>
            </div>
            
            <div class="card-body">
                <!-- نموذج البحث -->
                <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="icu_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 __('pharmacists_count'); ?></th>
                                <th><?php echo __('patients_count'); ?></th>
                                <th><?php echo __('total_patients'); ?></th>
                                <th><?php echo __('discharged_patients'); ?></th>
                                <th><?php echo __('icu_cases'); ?></th>
                                <th><?php echo __('ccu_cases'); ?></th>
                                <th><?php echo __('critical_cases'); ?></th>
                                <th><?php echo __('actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($reports as $report): ?>
                            <tr>
                                <td>
                                    <strong><?php echo formatArabicDate($report['report_date']); ?></strong>
                                </td>
                                <td>
                                    <i class="fas fa-user-md text-primary me-1"></i>
                                    <?php echo htmlspecialchars($report['pharmacist_shift']); ?>
                                </td>
                                <td>
                                    <span class="badge bg-secondary"><?php echo $report['pharmacists_count'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-info"><?php echo $report['no_of_pt']; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-primary"><?php echo $report['total_patients']; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-success"><?php echo $report['total_discharged']; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-warning text-dark"><?php echo $report['icu_cases'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-danger"><?php echo $report['cardiac_care_cases'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-dark"><?php echo $report['critical_cases'] ?? 0; ?></span>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <?php if (PagePermissions::hasPermission($currentPage, 'view_icu_details')): ?>
                                        <a href="view_icu_report_details.php?id=<?php echo $report['id']; ?>" 
                                           class="btn btn-outline-primary" title="<?php echo __('view_details'); ?>">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php endif; ?>
                                        
                                        <?php if (PagePermissions::hasPermission($currentPage, 'print_icu')): ?>
                                        <a href="print_icu_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>
                                        <?php endif; ?>
                                        
                                        <?php if (PagePermissions::hasPermission($currentPage, 'edit_icu_record')): ?>
                                        <a href="edit_icu_report.php?id=<?php echo $report['id']; ?>" 
                                           class="btn btn-outline-warning" title="<?php echo __('edit'); ?>">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <?php endif; ?>
                                        
                                        <?php if (PagePermissions::hasPermission($currentPage, 'delete_icu_record')): ?>
                                        <button type="button" class="btn btn-outline-danger" 
                                                onclick="deleteReport(<?php echo $report['id']; ?>)" 
                                                title="<?php echo __('delete'); ?>">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- الترقيم -->
                <?php if ($total_pages > 1): ?>
                <nav aria-label="ترقيم الصفحات" class="no-print">
                    <ul class="pagination justify-content-center">
                        <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page-1; ?>&search_date=<?php echo $search_date; ?>&search_pharmacist=<?php echo $search_pharmacist; ?>">
                                <?php echo __('previous'); ?>
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&search_date=<?php echo $search_date; ?>&search_pharmacist=<?php echo $search_pharmacist; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page+1; ?>&search_date=<?php echo $search_date; ?>&search_pharmacist=<?php echo $search_pharmacist; ?>">
                                <?php echo __('next'); ?>
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </nav>
                <?php endif; ?>
                
                <?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_icu_reports_message'); ?></p>
                    <button class="btn btn-primary" onclick="showSection('create')">
                        <i class="fas fa-plus me-1"></i> <?php echo __('new_icu_report'); ?>
                    </button>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

<script>
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('addPatientRow').addEventListener('click', function() {
        const tbody = document.querySelector('#patientsTable tbody');
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td data-label="<?php echo __('patient_name'); ?>">
                <input type="text" name="patient_name[]" 
                       class="form-control form-control-sm" 
                       placeholder="<?php echo __('patient_name'); ?>">
            </td>
            <td data-label="DAMA">
                <div class="form-check">
                    <input type="checkbox" name="dama[]" 
                           value="1" class="form-check-input">
                </div>
            </td>
            <td data-label="<?php echo __('improved'); ?>">
                <div class="form-check">
                    <input type="checkbox" name="improved[]" 
                           value="1" class="form-check-input">
                </div>
            </td>
            <td data-label="<?php echo __('discharged'); ?>">
                <select name="discharged[]" class="form-select form-select-sm">
                    <option value=""><?php echo __('select'); ?></option>
                    <option value="approved"><?php echo __('approved'); ?></option>
                    <option value="disapproved"><?php echo __('disapproved'); ?></option>
                </select>
            </td>
            <td data-label="<?php echo __('reason'); ?>">
                <input type="text" name="reason[]" 
                       class="form-control form-control-sm" 
                       placeholder="<?php echo __('reason'); ?>">
            </td>
            <td data-label="">
                <button type="button" class="btn btn-sm btn-danger remove-row">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
    });
    
    // حذف صف
    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-row')) {
            e.target.closest('tr').remove();
        }
    });
    
    // إضافة بطاقة مريض عزل جديدة
    document.getElementById('addIsolationPatient').addEventListener('click', function() {
        const container = document.getElementById('isolationContainer');
        const newCol = document.createElement('div');
        newCol.className = 'col-md-4 mb-3';
        
        newCol.innerHTML = `
            <div class="isolation-card" style="background: #f8f9fa; border: 2px solid #dee2e6; border-radius: 15px; padding: 20px; position: relative; min-height: 200px;">
                <button type="button" class="btn btn-sm btn-danger remove-isolation" style="position: absolute; top: 10px; left: 10px; border-radius: 50%; width: 30px; height: 30px; padding: 0;">
                    <i class="fas fa-times"></i>
                </button>
                
                <div class="mb-3">
                    <label class="form-label text-end d-block fw-bold"><?php echo __('patient_name'); ?>:</label>
                    <input type="text" name="isolation_patient_name[]" 
                           class="form-control text-end" 
                           placeholder="<?php echo __('patient_name'); ?>...">
                </div>
                
                <div class="mb-3">
                    <label class="form-label text-end d-block fw-bold"><?php echo __('floor'); ?>:</label>
                    <input type="text" name="isolation_floor[]" 
                           class="form-control text-end" 
                           placeholder="<?php echo __('floor'); ?>...">
                </div>
            </div>
        `;
        
        container.appendChild(newCol);
        
        // إضافة تأثير الظهور
        newCol.style.opacity = '0';
        setTimeout(() => {
            newCol.style.transition = 'opacity 0.3s ease';
            newCol.style.opacity = '1';
        }, 10);
    });
    
    // حذف بطاقة مريض عزل
    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-isolation')) {
            const col = e.target.closest('.col-md-4');
            col.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            col.style.opacity = '0';
            col.style.transform = 'scale(0.9)';
            setTimeout(() => {
                col.remove();
            }, 300);
        }
    });
    
    // التحقق من صحة النموذج
    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);
    });
});

function deleteReport(id) {
    if (confirm('هل أنت متأكد من حذف هذا التقرير؟ لا يمكن التراجع عن هذا الإجراء!')) {
        window.location.href = 'delete.php?type=icu_report&id=' + id;
    }
}
</script>

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