<?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: login.php');
    exit();
}

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

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

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

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

// إنشاء الجداول المطلوبة
try {
    // جدول الصيادلة
    $conn->exec("CREATE TABLE IF NOT EXISTS pharmacists (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        code VARCHAR(20),
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    
    // جدول جدول الصيادلة
    $conn->exec("CREATE TABLE IF NOT EXISTS pharmacist_schedule (
        id INT AUTO_INCREMENT PRIMARY KEY,
        pharmacist_id INT NOT NULL,
        team VARCHAR(50) NOT NULL,
        schedule_date DATE NOT NULL,
        shift_time VARCHAR(20),
        notes TEXT,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (pharmacist_id) REFERENCES pharmacists(id) ON DELETE CASCADE,
        INDEX idx_schedule_date (schedule_date),
        INDEX idx_team (team)
    )");
    
    // جدول الأعياد والإجازات الرسمية
    $conn->exec("CREATE TABLE IF NOT EXISTS holidays (
        id INT AUTO_INCREMENT PRIMARY KEY,
        holiday_name VARCHAR(200) NOT NULL,
        holiday_name_en VARCHAR(200),
        holiday_date DATE NOT NULL,
        holiday_type ENUM('national', 'religious', 'other') DEFAULT 'national',
        is_recurring BOOLEAN DEFAULT FALSE,
        color VARCHAR(20) DEFAULT '#ff6b6b',
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_holiday (holiday_name, holiday_date),
        INDEX idx_holiday_date (holiday_date)
    )");
    // إضافة UNIQUE constraint لو الجدول موجود بدونها
    try {
        $conn->exec("ALTER TABLE holidays ADD UNIQUE KEY unique_holiday (holiday_name, holiday_date)");
    } catch (PDOException $e) { /* already exists */ }
} catch (PDOException $e) {
    // تجاهل الأخطاء إذا كانت الجداول موجودة
}

$message = '';
$error = '';

// معالجة النماذج
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'add_pharmacist':
                    $stmt = $conn->prepare("INSERT INTO pharmacists (name, code) VALUES (?, ?)");
                    $stmt->execute([$_POST['name'], $_POST['code']]);
                    $message = __('pharmacist_added_successfully');
                    break;
                    
                case 'add_schedule':
                    $stmt = $conn->prepare("INSERT INTO pharmacist_schedule (pharmacist_id, team, schedule_date, shift_time, notes, created_by) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $_POST['pharmacist_id'],
                        $_POST['team'],
                        $_POST['schedule_date'],
                        $_POST['shift_time'],
                        $_POST['notes'] ?? null,
                        $_SESSION['user_id']
                    ]);
                    $message = __('schedule_added_successfully');
                    break;
                    
                case 'delete_schedule':
                    $stmt = $conn->prepare("DELETE FROM pharmacist_schedule WHERE id = ?");
                    $stmt->execute([$_POST['schedule_id']]);
                    $message = __('schedule_deleted_successfully');
                    break;
                    
                case 'add_holiday':
                    // التحقق من نوع التاريخ
                    if (isset($_POST['date_type']) && $_POST['date_type'] == 'range') {
                        // إضافة عطلة لفترة من التواريخ
                        $start_date_h = new DateTime($_POST['start_holiday_date']);
                        $end_date_h = new DateTime($_POST['end_holiday_date']);
                        $interval_h = new DateInterval('P1D');
                        $date_range = new DatePeriod($start_date_h, $interval_h, $end_date_h->modify('+1 day'));
                        
                        $stmt = $conn->prepare("INSERT IGNORE INTO holidays (holiday_name, holiday_name_en, holiday_date, holiday_type, is_recurring, color, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
                        $added_count = 0;
                        foreach ($date_range as $date) {
                            $stmt->execute([
                                $_POST['holiday_name'],
                                $_POST['holiday_name_en'] ?? null,
                                $date->format('Y-m-d'),
                                $_POST['holiday_type'],
                                isset($_POST['is_recurring']) ? 1 : 0,
                                $_POST['color'] ?? '#ff6b6b',
                                $_SESSION['user_id']
                            ]);
                            if ($stmt->rowCount() > 0) $added_count++;
                        }
                        $message = Translation::getDirection() == 'rtl' ? 
                            "تم إضافة $added_count يوم عطلة بنجاح" : 
                            "$added_count holiday days added successfully";
                    } else {
                        // التحقق من عدم وجود نفس الإجازة مسبقاً
                        $check = $conn->prepare("SELECT id FROM holidays WHERE holiday_name = ? AND holiday_date = ?");
                        $check->execute([$_POST['holiday_name'], $_POST['holiday_date']]);
                        if ($check->fetch()) {
                            $error = Translation::getDirection() == 'rtl' ? 'هذه الإجازة موجودة بالفعل في هذا التاريخ' : 'This holiday already exists on this date';
                        } else {
                            $stmt = $conn->prepare("INSERT INTO holidays (holiday_name, holiday_name_en, holiday_date, holiday_type, is_recurring, color, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
                            $stmt->execute([
                                $_POST['holiday_name'],
                                $_POST['holiday_name_en'] ?? null,
                                $_POST['holiday_date'],
                                $_POST['holiday_type'],
                                isset($_POST['is_recurring']) ? 1 : 0,
                                $_POST['color'] ?? '#ff6b6b',
                                $_SESSION['user_id']
                            ]);
                            $message = Translation::getDirection() == 'rtl' ? 'تم إضافة العطلة بنجاح' : 'Holiday added successfully';
                        }
                    }
                    break;
                    
                case 'delete_holiday':
                    $stmt = $conn->prepare("DELETE FROM holidays WHERE id = ?");
                    $stmt->execute([$_POST['holiday_id']]);
                    $message = Translation::getDirection() == 'rtl' ? 'تم حذف العطلة بنجاح' : 'Holiday deleted successfully';
                    break;
                    
                case 'edit_holiday':
                    $stmt = $conn->prepare("UPDATE holidays SET holiday_name = ?, holiday_name_en = ?, holiday_date = ?, holiday_type = ?, is_recurring = ?, color = ? WHERE id = ?");
                    $stmt->execute([
                        $_POST['holiday_name'],
                        $_POST['holiday_name_en'] ?? null,
                        $_POST['holiday_date'],
                        $_POST['holiday_type'],
                        isset($_POST['is_recurring']) ? 1 : 0,
                        $_POST['color'] ?? '#ff6b6b',
                        $_POST['holiday_id']
                    ]);
                    $message = Translation::getDirection() == 'rtl' ? 'تم تحديث العطلة بنجاح' : 'Holiday updated successfully';
                    break;
                    
                case 'remove_duplicate_holidays':
                    // حذف الإجازات المكررة - الاحتفاظ بأقدم record لكل (holiday_name, holiday_date)
                    $conn->exec("
                        DELETE h1 FROM holidays h1
                        INNER JOIN holidays h2
                        WHERE h1.id > h2.id
                          AND h1.holiday_name = h2.holiday_name
                          AND h1.holiday_date = h2.holiday_date
                    ");
                    $deleted = $conn->query("SELECT ROW_COUNT()")->fetchColumn();
                    $message = Translation::getDirection() == 'rtl' ? 
                        'تم حذف الإجازات المكررة بنجاح' : 
                        'Duplicate holidays removed successfully';
                    break;
                    
                case 'import_default_holidays':
                    // العطلات الافتراضية للسنة الحالية
                    $current_year = date('Y');
                    $default_holidays = [
                        ['name' => 'رأس السنة الميلادية', 'name_en' => 'New Year', 'date' => "$current_year-01-01", 'type' => 'national', 'color' => '#4CAF50'],
                        ['name' => 'عيد الشرطة', 'name_en' => 'Police Day', 'date' => "$current_year-01-25", 'type' => 'national', 'color' => '#2196F3'],
                        ['name' => 'عيد تحرير سيناء', 'name_en' => 'Sinai Liberation Day', 'date' => "$current_year-04-25", 'type' => 'national', 'color' => '#FF9800'],
                        ['name' => 'عيد العمال', 'name_en' => 'Labor Day', 'date' => "$current_year-05-01", 'type' => 'national', 'color' => '#F44336'],
                        ['name' => 'ثورة 30 يونيو', 'name_en' => 'June 30 Revolution', 'date' => "$current_year-06-30", 'type' => 'national', 'color' => '#9C27B0'],
                        ['name' => 'ثورة 23 يوليو', 'name_en' => 'July 23 Revolution', 'date' => "$current_year-07-23", 'type' => 'national', 'color' => '#E91E63'],
                        ['name' => 'عيد الفطر', 'name_en' => 'Eid Al-Fitr', 'date' => "$current_year-04-10", 'type' => 'religious', 'color' => '#00BCD4', 'recurring' => 1],
                        ['name' => 'عيد الأضحى', 'name_en' => 'Eid Al-Adha', 'date' => "$current_year-06-16", 'type' => 'religious', 'color' => '#009688', 'recurring' => 1],
                        ['name' => 'رأس السنة الهجرية', 'name_en' => 'Islamic New Year', 'date' => "$current_year-07-07", 'type' => 'religious', 'color' => '#795548', 'recurring' => 1],
                        ['name' => 'المولد النبوي', 'name_en' => 'Prophet\'s Birthday', 'date' => "$current_year-09-15", 'type' => 'religious', 'color' => '#607D8B', 'recurring' => 1],
                    ];
                    
                    $stmt = $conn->prepare("INSERT IGNORE INTO holidays (holiday_name, holiday_name_en, holiday_date, holiday_type, is_recurring, color, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $imported = 0;
                    foreach ($default_holidays as $holiday) {
                        // تحقق من عدم الوجود المسبق
                        $check = $conn->prepare("SELECT id FROM holidays WHERE holiday_name = ? AND holiday_date = ?");
                        $check->execute([$holiday['name'], $holiday['date']]);
                        if (!$check->fetch()) {
                            $stmt->execute([
                                $holiday['name'],
                                $holiday['name_en'],
                                $holiday['date'],
                                $holiday['type'],
                                $holiday['recurring'] ?? 0,
                                $holiday['color'],
                                $_SESSION['user_id']
                            ]);
                            if ($stmt->rowCount() > 0) $imported++;
                        }
                    }
                    $message = Translation::getDirection() == 'rtl' ? "تم استيراد $imported عطلة بنجاح" : "$imported holidays imported successfully";
                    break;
            }
        }
    } catch (PDOException $e) {
        $error = __('error_occurred') . ': ' . $e->getMessage();
    }
}

// جلب البيانات
try {
    // جلب الصيادلة
    $pharmacists_stmt = $conn->query("SELECT * FROM pharmacists WHERE is_active = 1 ORDER BY name");
    $pharmacists = $pharmacists_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب الجدول الحالي
    // إذا كان المستخدم اختار تواريخ محددة
    if (isset($_GET['start_date']) && isset($_GET['end_date'])) {
        $start_date = $_GET['start_date'];
        $end_date = $_GET['end_date'];
    } else {
        // الافتراضي: الشهر يبدأ من 21 الشهر السابق وينتهي 20 الشهر الحالي
        $schedule_filter = isset($_GET['month']) ? $_GET['month'] : date('Y-m');
        list($year, $month) = explode('-', $schedule_filter);
        
        // حساب الشهر السابق
        $prev_month_date = date('Y-m', strtotime("$year-$month-01 -1 month"));
        list($prev_year, $prev_month) = explode('-', $prev_month_date);
        
        $start_date = "$prev_year-$prev_month-21";
        $end_date = "$year-$month-20";
    }
    
    // حساب عدد الأيام
    $start_date_obj = new DateTime($start_date);
    $end_date_obj = new DateTime($end_date);
    $interval = $start_date_obj->diff($end_date_obj);
    $total_days = $interval->days + 1;
    
    $schedule_stmt = $conn->prepare("
        SELECT ps.*, p.name as pharmacist_name, p.code as pharmacist_code
        FROM pharmacist_schedule ps
        JOIN pharmacists p ON ps.pharmacist_id = p.id
        WHERE ps.schedule_date >= ? AND ps.schedule_date <= ?
        ORDER BY ps.team, p.name, ps.schedule_date
    ");
    $schedule_stmt->execute([$start_date, $end_date]);
    $schedules = $schedule_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب الأعياد والإجازات الرسمية
    $holidays_stmt = $conn->prepare("
        SELECT * FROM holidays 
        WHERE holiday_date >= ? AND holiday_date <= ?
        ORDER BY holiday_date
    ");
    $holidays_stmt->execute([$start_date, $end_date]);
    $holidays = $holidays_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // تحويل الأعياد إلى مصفوفة للوصول السريع
    $holidays_by_date = [];
    foreach ($holidays as $holiday) {
        $holidays_by_date[$holiday['holiday_date']] = $holiday;
    }
    
} catch (PDOException $e) {
    $error = __('error_fetching_data') . ': ' . $e->getMessage();
    $pharmacists = [];
    $schedules = [];
    $holidays = [];
    $holidays_by_date = [];
}

include 'includes/header.php';
?>

<style>
.schedule-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    background: white;
}

.schedule-table th, 
.schedule-table td {
    border: 1px solid #e0e0e0;
    padding: 8px 5px;
    text-align: center;
}

.schedule-table thead th {
    position: sticky;
    z-index: 20;
    background-color: #5e35b1 !important;
    color: white !important;
    font-weight: 600;
    white-space: nowrap;
    border: 1px solid rgba(255,255,255,0.1) !important;
}

/* Ensure ALL header background is solid to prevent clashing */
.schedule-table thead tr {
    background-color: #5e35b1 !important;
}

.schedule-table thead tr:first-child {
    background-color: #4c2c92 !important;
}

.schedule-table thead tr th {
    background-color: inherit !important;
}

/* Row-specific sticky tops */
.schedule-table thead tr:nth-child(1) th { top: 0; z-index: 26; }
.schedule-table thead tr:nth-child(2) th { top: 40px; z-index: 25; }
.schedule-table thead tr:nth-child(3) th { top: 75px; z-index: 24; }
.schedule-table thead tr:nth-child(4) th { top: 110px; z-index: 23; }

/* Sticky Name and Code on the Right (RTL) */
[dir="rtl"] .schedule-table .sticky-col-name {
    position: sticky;
    right: 0;
    z-index: 40;
    background-color: white !important;
    min-width: 150px;
    max-width: 150px;
    box-shadow: -2px 0 5px rgba(0,0,0,0.1);
}

[dir="rtl"] .schedule-table .sticky-col-code {
    position: sticky;
    right: 150px;
    z-index: 40;
    background-color: white !important;
    min-width: 80px;
    max-width: 80px;
    box-shadow: -2px 0 5px rgba(0,0,0,0.1);
}

/* Specific background for header sticky cells */
[dir="rtl"] .schedule-table thead th.sticky-col-name,
[dir="rtl"] .schedule-table thead th.sticky-col-code {
    background-color: #5e35b1 !important;
    background-image: none !important;
    z-index: 50 !important;
    color: white !important;
}

[dir="rtl"] .schedule-table tbody td.sticky-col-name,
[dir="rtl"] .schedule-table tbody td.sticky-col-code {
    background-color: #f8f9fa !important;
    border-left: 1px solid #dee2e6;
}

/* LTR support */
[dir="ltr"] .schedule-table .sticky-col-name {
    position: sticky;
    left: 0;
    z-index: 40;
    background-color: white !important;
    min-width: 150px;
    max-width: 150px;
    box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}

[dir="ltr"] .schedule-table .sticky-col-code {
    position: sticky;
    left: 150px;
    z-index: 40;
    background-color: white !important;
    min-width: 80px;
    max-width: 80px;
    box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}

[dir="ltr"] .schedule-table thead th.sticky-col-name,
[dir="ltr"] .schedule-table thead th.sticky-col-code {
    background-color: #5e35b1 !important;
    z-index: 50 !important;
    color: white !important;
}

/* Schedule table wrapper - scoped to this page only */
.schedule-table-wrapper {
    width: 100%;
    /* overflow-x only on mobile — keeps position:sticky working */
    overflow-x: auto;
    overflow-y: visible;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.05);
    -webkit-overflow-scrolling: touch;
}

/* Desktop: allow vertical scroll with max-height */
@media (min-width: 993px) {
    .schedule-table-wrapper {
        max-height: 75vh;
        overflow: auto;
    }
}

.team-header {
    background-color: #a2f0a2 !important;
    color: #2c5e2c !important;
    font-weight: 800;
    text-align: center;
    padding: 12px !important;
    font-size: 1rem;
}

.no-data-row {
    background-color: white !important;
    padding: 15px !important;
    font-size: 0.9rem;
    color: #888;
}

.schedule-table tbody tr:hover td {
    background-color: #f0f4ff !important;
}

.shift-morning { background-color: #fff3cd !important; }
.shift-evening { background-color: #d1ecf1 !important; }
.shift-night { background-color: #f8d7da !important; }
.shift-off { background-color: #d4edda !important; }

.btn-action {
    border-radius: 8px;
    padding: 5px 15px;
    font-weight: 600;
    font-size: 0.8rem;
}

.schedule-header {
    background: white;
    padding: 1.25rem;
    border-radius: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 1rem;
}
</style>

    <div class="main-content-container container-fluid px-0">
        <div class="schedule-header no-print">
            <div class="row align-items-center g-3">
                <div class="col-12 d-flex justify-content-between align-items-center flex-wrap gap-3">
                    <div class="d-flex align-items-center gap-2">
                        <div class="icon-box bg-primary-light p-1 rounded-2">
                            <i class="fas fa-calendar-alt text-primary"></i>
                        </div>
                        <div>
                            <h1 class="h5 mb-0 fw-bold" style="color: var(--primary-color);">
                                <?php echo __('pharmacist_schedule'); ?>
                            </h1>
                        </div>
                    </div>
                    <div class="action-buttons-grid d-flex flex-wrap gap-2 justify-content-start justify-content-md-end">
                        <?php if (PagePermissions::hasPermission($currentPage, 'add_schedule')): ?>
                        <a href="pharmacist_schedule_bulk.php" class="btn btn-success btn-action py-1 px-3">
                            <i class="fas fa-calendar-plus"></i> <?php echo __('bulk_entry'); ?>
                        </a>
                        <button type="button" class="btn btn-primary btn-action py-1 px-3" data-bs-toggle="modal" data-bs-target="#addPharmacistModal">
                            <i class="fas fa-user-plus"></i> <?php echo __('add_pharmacist'); ?>
                        </button>
                        <button type="button" class="btn btn-info btn-action py-1 px-3" data-bs-toggle="modal" data-bs-target="#addScheduleModal">
                            <i class="fas fa-plus"></i> <?php echo __('add_schedule'); ?>
                        </button>
                        <button type="button" class="btn btn-warning btn-action py-1 px-3" data-bs-toggle="modal" data-bs-target="#addHolidayModal">
                            <i class="fas fa-calendar-day"></i> <?php echo __('add_holiday'); ?>
                        </button>
                        <button type="button" class="btn btn-outline-warning btn-action py-1 px-3" data-bs-toggle="modal" data-bs-target="#manageHolidaysModal">
                            <i class="fas fa-cog"></i> <?php echo __('manage_holidays'); ?>
                        </button>
                        <?php endif; ?>
                        
                        <?php if (PagePermissions::hasPermission($currentPage, 'export_schedule_excel')): ?>
                        <a href="export/pharmacist_schedule_excel.php?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>" class="btn btn-outline-success btn-action py-1 px-3">
                            <i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>
                        </a>
                        <?php endif; ?>
                        
                        <?php if (PagePermissions::hasPermission($currentPage, 'view_schedule')): ?>
                        <button type="button" class="btn btn-outline-primary btn-action py-1 px-3" onclick="window.print()">
                            <i class="fas fa-print"></i> <?php echo __('print'); ?>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

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

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

    <!-- Date Range Filter -->
    <div class="card form-card no-print mb-4 shadow-sm border-0" style="border-radius: 15px;">
        <div class="card-body p-3">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label for="start_date" class="form-label small mb-1 fw-bold text-primary"><?php echo __('from_date'); ?></label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text bg-white border-end-0"><i class="fas fa-calendar-alt text-muted"></i></span>
                        <input type="date" class="form-control border-start-0" id="start_date" name="start_date" value="<?php echo isset($_GET['start_date']) ? $_GET['start_date'] : $start_date; ?>" required>
                    </div>
                </div>
                <div class="col-md-3">
                    <label for="end_date" class="form-label small mb-1 fw-bold text-primary"><?php echo __('to_date'); ?></label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text bg-white border-end-0"><i class="fas fa-calendar-alt text-muted"></i></span>
                        <input type="date" class="form-control border-start-0" id="end_date" name="end_date" value="<?php echo isset($_GET['end_date']) ? $_GET['end_date'] : $end_date; ?>" required>
                    </div>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary btn-sm w-100 py-2 shadow-sm">
                        <i class="fas fa-filter me-1"></i> <?php echo __('view'); ?>
                    </button>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-outline-secondary btn-sm w-100 py-2" onclick="setDefaultDates()">
                        <i class="fas fa-undo me-1"></i> <?php echo __('reset'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Schedule Table -->
    <div class="card form-card shadow-sm border-0" style="border-radius: 15px;">
        <div class="card-body p-0" style="overflow: visible;">
            <!-- Mobile scroll hint -->
            <div class="d-md-none px-3 pt-2 pb-1 text-muted small no-print" style="font-size:0.75rem;">
                <i class="fas fa-arrows-alt-h me-1"></i>
                <?php echo Translation::getDirection() == 'rtl' ? 'اسحب يساراً لرؤية باقي الجدول' : 'Swipe left to see more'; ?>
            </div>
            <div class="table-responsive schedule-table-wrapper">
                <table class="schedule-table">
                    <thead>
                        <tr>
                            <th rowspan="4" class="sticky-col-name" style="vertical-align: middle; text-align: center;"><?php echo __('name'); ?></th>
                            <th rowspan="4" class="sticky-col-code" style="vertical-align: middle; text-align: center;"><?php echo __('code'); ?></th>
                            <th colspan="<?php echo $total_days; ?>" style="background: #311b92; letter-spacing: 2px; text-align: center; vertical-align: middle;"><?php echo __('days'); ?></th>
                            <th colspan="5" style="background: #006064; text-align: center; vertical-align: middle;"><?php echo __('statistics'); ?></th>
                            <th colspan="3" style="background: #1b5e20; text-align: center; vertical-align: middle;"><?php echo __('hours'); ?></th>
                        </tr>
                        <tr>
                            <?php 
                            // عرض أسماء الأيام
                            $current_date = clone $start_date_obj;
                            for ($d = 1; $d <= $total_days; $d++): 
                                $day_name = $current_date->format('D'); // Mon, Tue, Wed...
                            ?>
                                <th style="font-size: 0.8rem;"><?php echo $day_name; ?></th>
                            <?php 
                                $current_date->modify('+1 day');
                            endfor; 
                            ?>
                            <!-- أعمدة الإحصائيات -->
                            <th>L</th>
                            <th>N</th>
                            <th>A</th>
                            <th>E</th>
                            <th>C</th>
                            <!-- أعمدة الساعات -->
                            <th><?php echo __('official_vacation'); ?></th>
                            <th><?php echo __('total_hours'); ?></th>
                            <th><?php echo __('over_time'); ?></th>
                        </tr>
                        <tr>
                            <?php 
                            // عرض التواريخ (رقم اليوم فقط)
                            $current_date = clone $start_date_obj;
                            for ($d = 1; $d <= $total_days; $d++): 
                                $day_number = $current_date->format('j'); // رقم اليوم بدون صفر في البداية
                            ?>
                                <th style="font-size: 0.85rem; font-weight: bold;"><?php echo $day_number; ?></th>
                            <?php 
                                $current_date->modify('+1 day');
                            endfor; 
                            ?>
                            <!-- أعمدة الإحصائيات - فاضية -->
                            <th></th><th></th><th></th><th></th><th></th>
                            <!-- أعمدة الساعات - فاضية -->
                            <th></th><th></th><th></th>
                        </tr>
                        <tr>
                            <?php 
                            // عرض التاريخ الكامل (يوم-شهر)
                            $current_date = clone $start_date_obj;
                            for ($d = 1; $d <= $total_days; $d++): 
                                $date_full = $current_date->format('d-M'); // 21-Jan, 22-Jan...
                            ?>
                                <th style="font-size: 0.7rem;"><?php echo $date_full; ?></th>
                            <?php 
                                $current_date->modify('+1 day');
                            endfor; 
                            ?>
                            <!-- أعمدة الإحصائيات - فاضية -->
                            <th></th><th></th><th></th><th></th><th></th>
                            <!-- أعمدة الساعات - فاضية -->
                            <th></th><th></th><th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // تجميع البيانات حسب الفريق
                        $teams = ['OR Team', 'Ward Team', 'ICU Team', 'NICU Team'];
                        
                        foreach ($teams as $team):
                            // عرض رأس الفريق
                            $total_cols = $total_days + 10; // الأيام + 2 (name, code) + 5 (stats) + 3 (hours)
                            echo "<tr><td colspan='$total_cols' class='team-header'>$team</td></tr>";
                            
                            // جلب الصيادلة في هذا الفريق
                            $team_schedules = array_filter($schedules, function($s) use ($team) {
                                return $s['team'] == $team;
                            });
                            
                            // تجميع حسب الصيدلي
                            $pharmacist_data = [];
                            foreach ($team_schedules as $schedule) {
                                $pharmacist_id = $schedule['pharmacist_id'];
                                if (!isset($pharmacist_data[$pharmacist_id])) {
                                    $pharmacist_data[$pharmacist_id] = [
                                        'name' => $schedule['pharmacist_name'],
                                        'code' => $schedule['pharmacist_code'],
                                        'days' => []
                                    ];
                                }
                                
                                // حساب رقم اليوم من 1 إلى total_days
                                $schedule_date = new DateTime($schedule['schedule_date']);
                                $start_date_calc = new DateTime($start_date);
                                $diff = $start_date_calc->diff($schedule_date);
                                $day_number = $diff->days + 1;
                                
                                if ($day_number >= 1 && $day_number <= $total_days) {
                                    $pharmacist_data[$pharmacist_id]['days'][$day_number] = $schedule['shift_time'];
                                }
                            }
                            
                            // عرض صف لكل صيدلي
                            if (empty($pharmacist_data)) {
                                $total_cols = $total_days + 10;
                                echo "<tr><td colspan='$total_cols' class='text-center text-muted no-data-row'>" . __('no_data_found') . "</td></tr>";
                            } else {
                                foreach ($pharmacist_data as $pharmacist_id => $data):
                                    // حساب الإحصائيات
                                    $stats = [
                                        'L' => 0, 'N' => 0, 'A' => 0, 'E' => 0, 'C' => 0
                                    ];
                                    foreach ($data['days'] as $shift) {
                                        if (isset($stats[$shift])) {
                                            $stats[$shift]++;
                                        }
                                    }
                                    
                                    // حساب الساعات
                                    // L و N = 12 ساعة لكل وردية
                                    // A و E = 8 ساعات لكل وردية
                                    // C = 7 ساعات
                                    $hours_12 = ($stats['L'] + $stats['N']) * 12;
                                    $hours_8 = ($stats['A'] + $stats['E']) * 8;
                                    $hours_7 = $stats['C'] * 7;
                                    $total_hours = $hours_12 + $hours_8 + $hours_7;
                                    $official_vacation = 0; // لا يوجد Off في الرموز
                                    
                                    // الساعات الإضافية = إجمالي الساعات - 160 ساعة (المعيار الشهري)
                                    $overtime = $total_hours - 160;
                        ?>
                        <tr>
                            <td class="sticky-col-name"><?php echo htmlspecialchars($data['name']); ?></td>
                            <td class="sticky-col-code"><?php echo htmlspecialchars($data['code']); ?></td>
                            <?php 
                            // عرض الأيام حسب العدد الفعلي
                            for ($day = 1; $day <= $total_days; $day++): 
                                $shift = $data['days'][$day] ?? '';
                                
                                // حساب التاريخ الفعلي لهذا اليوم
                                $current_day_date = clone $start_date_obj;
                                $current_day_date->modify('+' . ($day - 1) . ' days');
                                $date_str = $current_day_date->format('Y-m-d');
                                
                                // التحقق من وجود عطلة في هذا اليوم
                                $holiday_style = '';
                                $holiday_title = '';
                                if (isset($holidays_by_date[$date_str])) {
                                    $holiday_color = $holidays_by_date[$date_str]['color'];
                                    $holiday_name = $holidays_by_date[$date_str]['holiday_name'];
                                    $holiday_style = "background: linear-gradient(135deg, $holiday_color 0%, " . $holiday_color . "dd 100%) !important; font-weight: bold; color: white !important; text-shadow: 1px 1px 2px rgba(0,0,0,0.3);";
                                    $holiday_title = "title='$holiday_name'";
                                }
                                
                                $class = '';
                                if ($shift == 'L') $class = 'shift-morning';
                                elseif ($shift == 'N') $class = 'shift-night';
                                elseif ($shift == 'A') $class = 'shift-morning';
                                elseif ($shift == 'E') $class = 'shift-evening';
                                elseif ($shift == 'M') $class = 'shift-morning';
                                elseif ($shift == 'O') $class = 'shift-off';
                            ?>
                                <td class="<?php echo $class; ?>" style="<?php echo $holiday_style; ?>" <?php echo $holiday_title; ?>><?php echo $shift; ?></td>
                            <?php endfor; ?>
                            <td><?php echo $stats['L']; ?></td>
                            <td><?php echo $stats['N']; ?></td>
                            <td><?php echo $stats['A']; ?></td>
                            <td><?php echo $stats['E']; ?></td>
                            <td><?php echo $stats['C']; ?></td>
                            <td><?php echo $official_vacation; ?></td>
                            <td><?php echo $total_hours; ?></td>
                            <td><?php echo $overtime; ?></td>
                        </tr>
                        <?php
                                endforeach;
                            }
                        endforeach;
                        ?>
                    </tbody>
                </table>
            </div>
            
            <div class="mt-4 p-3" style="background-color: #f8f9fa; border-radius: 8px;">
                <p class="mb-2"><strong><?php echo __('legend'); ?>:</strong></p>
                <div class="row">
                    <div class="col-md-12">
                        <p class="mb-1"><span class="badge" style="background-color: #fff3cd; color: #000;">L</span> = <?php echo __('long_day'); ?> (8am-8pm) - 12 <?php echo __('hours'); ?></p>
                        <p class="mb-1"><span class="badge" style="background-color: #f8d7da; color: #000;">N</span> = <?php echo __('night'); ?> (8pm-8am) - 12 <?php echo __('hours'); ?></p>
                        <p class="mb-1"><span class="badge" style="background-color: #fff3cd; color: #000;">A</span> = <?php echo __('morning'); ?> (8am-4pm) - 8 <?php echo __('hours'); ?></p>
                        <p class="mb-1"><span class="badge" style="background-color: #d1ecf1; color: #000;">E</span> = <?php echo __('evening'); ?> (4pm-12am) - 8 <?php echo __('hours'); ?></p>
                        <p class="mb-1"><span class="badge" style="background-color: #fff3cd; color: #000;">C</span> = <?php echo __('coverage'); ?> (8am-3pm) - 7 <?php echo __('hours'); ?></p>
                    </div>
                </div>
            </div>
            
            <!-- Holidays List -->
            <?php if (!empty($holidays)): ?>
            <div class="mt-4 p-4" style="background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%); border-radius: 12px; border: 2px solid #ff9800; box-shadow: 0 4px 15px rgba(255, 152, 0, 0.2);">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0"><i class="fas fa-calendar-day me-2" style="color: #ff9800;"></i><?php echo __('holiday_legend'); ?></h5>
                    <span class="badge bg-warning text-dark"><?php echo count($holidays); ?> <?php echo Translation::getDirection() == 'rtl' ? 'عطلة' : 'holidays'; ?></span>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover table-bordered bg-white" style="border-radius: 8px; overflow: hidden;">
                        <thead style="background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%); color: white;">
                            <tr>
                                <th style="width: 15%;"><?php echo __('holiday_date'); ?></th>
                                <th style="width: 35%;"><?php echo __('holiday_name'); ?></th>
                                <th style="width: 20%;"><?php echo __('holiday_type'); ?></th>
                                <th style="width: 15%;" class="text-center"><?php echo __('holiday_color'); ?></th>
                                <th style="width: 15%;" class="text-center"><?php echo __('actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($holidays as $holiday): ?>
                            <tr>
                                <td>
                                    <span class="badge" style="background-color: <?php echo $holiday['color']; ?>; color: #fff; font-size: 0.9rem; padding: 8px 12px;">
                                        <i class="fas fa-calendar me-1"></i>
                                        <?php echo date('d M Y', strtotime($holiday['holiday_date'])); ?>
                                    </span>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($holiday['holiday_name']); ?></strong>
                                    <?php if ($holiday['is_recurring']): ?>
                                        <span class="badge bg-info ms-2" title="<?php echo __('is_recurring'); ?>">
                                            <i class="fas fa-sync-alt"></i> <?php echo Translation::getDirection() == 'rtl' ? 'متكررة' : 'Recurring'; ?>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php 
                                    $type_icon = '';
                                    $type_class = '';
                                    if ($holiday['holiday_type'] == 'national') {
                                        echo '<span class="badge bg-primary"><i class="fas fa-flag me-1"></i>' . __('national_holiday') . '</span>';
                                    } elseif ($holiday['holiday_type'] == 'religious') {
                                        echo '<span class="badge bg-success"><i class="fas fa-mosque me-1"></i>' . __('religious_holiday') . '</span>';
                                    } else {
                                        echo '<span class="badge bg-secondary"><i class="fas fa-star me-1"></i>' . __('other_holiday') . '</span>';
                                    }
                                    ?>
                                </td>
                                <td class="text-center">
                                    <div style="width: 40px; height: 40px; background-color: <?php echo $holiday['color']; ?>; border-radius: 8px; margin: 0 auto; border: 2px solid #ddd; box-shadow: 0 2px 5px rgba(0,0,0,0.1);"></div>
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-sm btn-info me-1" onclick="editHoliday(<?php echo htmlspecialchars(json_encode($holiday)); ?>)" title="<?php echo __('edit'); ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('<?php echo __('confirm_delete_holiday'); ?>');">
                                        <input type="hidden" name="action" value="delete_holiday">
                                        <input type="hidden" name="holiday_id" value="<?php echo $holiday['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-danger" title="<?php echo __('delete'); ?>">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="text-center mt-4">
                <p><strong><?php echo __('signature'); ?></strong></p>
                <p>_______________________</p>
            </div>
        </div>
    </div>

<!-- Add Pharmacist Modal -->
<div class="modal fade" id="addPharmacistModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('add_new_pharmacist'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_pharmacist">
                    <div class="mb-3">
                        <label for="pharmacist_name" class="form-label"><?php echo __('pharmacist_name'); ?></label>
                        <input type="text" class="form-control" id="pharmacist_name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="pharmacist_code" class="form-label"><?php echo __('code'); ?></label>
                        <input type="text" class="form-control" id="pharmacist_code" name="code">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Schedule Modal -->
<div class="modal fade" id="addScheduleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('add_work_schedule'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_schedule">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="schedule_pharmacist" class="form-label"><?php echo __('pharmacist'); ?></label>
                            <select class="form-select" id="schedule_pharmacist" name="pharmacist_id" required>
                                <option value=""><?php echo __('select_pharmacist'); ?></option>
                                <?php foreach ($pharmacists as $pharmacist): ?>
                                    <option value="<?php echo $pharmacist['id']; ?>">
                                        <?php echo htmlspecialchars($pharmacist['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="schedule_team" class="form-label"><?php echo __('team'); ?></label>
                            <select class="form-select" id="schedule_team" name="team" required>
                                <option value=""><?php echo __('select_team'); ?></option>
                                <option value="OR Team">OR Team</option>
                                <option value="Ward Team">Ward Team</option>
                                <option value="ICU Team">ICU Team</option>
                                <option value="NICU Team">NICU Team</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="schedule_date" class="form-label"><?php echo __('date'); ?></label>
                            <input type="date" class="form-control" id="schedule_date" name="schedule_date" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="shift_time" class="form-label"><?php echo __('shift'); ?></label>
                            <select class="form-select" id="shift_time" name="shift_time" required>
                                <option value=""><?php echo __('select_shift'); ?></option>
                                <option value="L">L - <?php echo __('long_day'); ?> (8am-8pm) - 12 <?php echo __('hours'); ?></option>
                                <option value="N">N - <?php echo __('night'); ?> (8pm-8am) - 12 <?php echo __('hours'); ?></option>
                                <option value="A">A - <?php echo __('morning'); ?> (8am-4pm) - 8 <?php echo __('hours'); ?></option>
                                <option value="E">E - <?php echo __('evening'); ?> (4pm-12am) - 8 <?php echo __('hours'); ?></option>
                                <option value="M">M - <?php echo __('morning_shift'); ?> - 8 <?php echo __('hours'); ?></option>
                                <option value="O">O - Off</option>
                                <option value="V">V - Vacation</option>
                                <option value="B">B - Business Trip</option>
                                <option value="C">C - Conference</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="schedule_notes" class="form-label"><?php echo __('notes'); ?></label>
                        <textarea class="form-control" id="schedule_notes" name="notes" rows="3" style="min-height: 90px;"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-success"><?php echo __('save_schedule'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Holiday Modal -->
<div class="modal fade" id="addHolidayModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%); color: white;">
                <h5 class="modal-title"><i class="fas fa-calendar-plus me-2"></i><?php echo __('add_holiday'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_holiday">
                    <div class="mb-3">
                        <label for="holiday_name" class="form-label"><i class="fas fa-language me-1"></i><?php echo __('holiday_name'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="holiday_name" name="holiday_name" required placeholder="<?php echo Translation::getDirection() == 'rtl' ? 'عيد الفطر' : 'Eid Al-Fitr'; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><i class="fas fa-calendar me-1"></i><?php echo Translation::getDirection() == 'rtl' ? 'نوع التاريخ' : 'Date Type'; ?></label>
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="date_type" id="single_date" value="single" checked onclick="toggleDateType()">
                            <label class="btn btn-outline-primary" for="single_date">
                                <i class="fas fa-calendar-day me-1"></i><?php echo Translation::getDirection() == 'rtl' ? 'يوم واحد' : 'Single Day'; ?>
                            </label>
                            
                            <input type="radio" class="btn-check" name="date_type" id="date_range" value="range" onclick="toggleDateType()">
                            <label class="btn btn-outline-primary" for="date_range">
                                <i class="fas fa-calendar-week me-1"></i><?php echo Translation::getDirection() == 'rtl' ? 'فترة' : 'Date Range'; ?>
                            </label>
                        </div>
                    </div>
                    
                    <div id="single_date_section">
                        <div class="mb-3">
                            <label for="holiday_date" class="form-label"><i class="fas fa-calendar me-1"></i><?php echo __('holiday_date'); ?> <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="holiday_date" name="holiday_date">
                        </div>
                    </div>
                    
                    <div id="date_range_section" style="display: none;">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="start_holiday_date" class="form-label"><i class="fas fa-calendar-alt me-1"></i><?php echo __('from_date'); ?> <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="start_holiday_date" name="start_holiday_date">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="end_holiday_date" class="form-label"><i class="fas fa-calendar-alt me-1"></i><?php echo __('to_date'); ?> <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="end_holiday_date" name="end_holiday_date">
                            </div>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <?php echo Translation::getDirection() == 'rtl' ? 
                                'سيتم إضافة العطلة لجميع الأيام في الفترة المحددة' : 
                                'Holiday will be added for all days in the selected range'; ?>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="holiday_type" class="form-label"><i class="fas fa-tag me-1"></i><?php echo __('holiday_type'); ?> <span class="text-danger">*</span></label>
                        <select class="form-select" id="holiday_type" name="holiday_type" required>
                            <option value="national"><i class="fas fa-flag"></i> <?php echo __('national_holiday'); ?></option>
                            <option value="religious"><i class="fas fa-mosque"></i> <?php echo __('religious_holiday'); ?></option>
                            <option value="other"><i class="fas fa-star"></i> <?php echo __('other_holiday'); ?></option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="color" class="form-label"><i class="fas fa-palette me-1"></i><?php echo __('holiday_color'); ?></label>
                        <div class="d-flex align-items-center gap-2">
                            <input type="color" class="form-control form-control-color" id="color" name="color" value="#ff6b6b" style="width: 60px; height: 40px;">
                            <small class="text-muted"><?php echo Translation::getDirection() == 'rtl' ? 'اختر لون مميز للعطلة' : 'Choose a distinctive color for the holiday'; ?></small>
                        </div>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="is_recurring" name="is_recurring" value="1">
                        <label class="form-check-label" for="is_recurring">
                            <i class="fas fa-sync-alt me-1"></i><?php echo __('is_recurring'); ?>
                            <small class="text-muted d-block"><?php echo Translation::getDirection() == 'rtl' ? 'للعطلات التي تتكرر كل عام (مثل الأعياد الدينية)' : 'For holidays that repeat annually (like religious holidays)'; ?></small>
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times me-1"></i><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-warning"><i class="fas fa-save me-1"></i><?php echo __('save'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Holiday Modal -->
<div class="modal fade" id="editHolidayModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%); color: white;">
                <h5 class="modal-title"><i class="fas fa-edit me-2"></i><?php echo __('edit_holiday'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit_holiday">
                    <input type="hidden" name="holiday_id" id="edit_holiday_id">
                    <div class="mb-3">
                        <label for="edit_holiday_name" class="form-label"><i class="fas fa-language me-1"></i><?php echo __('holiday_name'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_holiday_name" name="holiday_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_holiday_date" class="form-label"><i class="fas fa-calendar me-1"></i><?php echo __('holiday_date'); ?> <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" id="edit_holiday_date" name="holiday_date" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_holiday_type" class="form-label"><i class="fas fa-tag me-1"></i><?php echo __('holiday_type'); ?> <span class="text-danger">*</span></label>
                        <select class="form-select" id="edit_holiday_type" name="holiday_type" required>
                            <option value="national"><?php echo __('national_holiday'); ?></option>
                            <option value="religious"><?php echo __('religious_holiday'); ?></option>
                            <option value="other"><?php echo __('other_holiday'); ?></option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="edit_color" class="form-label"><i class="fas fa-palette me-1"></i><?php echo __('holiday_color'); ?></label>
                        <input type="color" class="form-control form-control-color" id="edit_color" name="color" style="width: 60px; height: 40px;">
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="edit_is_recurring" name="is_recurring" value="1">
                        <label class="form-check-label" for="edit_is_recurring">
                            <i class="fas fa-sync-alt me-1"></i><?php echo __('is_recurring'); ?>
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times me-1"></i><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i><?php echo __('update'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Manage Holidays Modal -->
<div class="modal fade" id="manageHolidaysModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%); color: white;">
                <h5 class="modal-title"><i class="fas fa-cog me-2"></i><?php echo __('manage_holidays'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    <?php echo Translation::getDirection() == 'rtl' ? 
                        'يمكنك استيراد العطلات الرسمية المصرية الافتراضية للسنة الحالية' : 
                        'You can import default Egyptian official holidays for the current year'; ?>
                </div>
                
                <h6 class="mb-3"><i class="fas fa-list me-2"></i><?php echo Translation::getDirection() == 'rtl' ? 'العطلات التي سيتم استيرادها:' : 'Holidays to be imported:'; ?></h6>
                
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary"><i class="fas fa-flag me-1"></i><?php echo __('national_holiday'); ?></h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'رأس السنة الميلادية (1 يناير)' : 'New Year (Jan 1)'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'عيد الشرطة (25 يناير)' : 'Police Day (Jan 25)'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'عيد تحرير سيناء (25 أبريل)' : 'Sinai Liberation Day (Apr 25)'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'عيد العمال (1 مايو)' : 'Labor Day (May 1)'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'ثورة 30 يونيو (30 يونيو)' : 'June 30 Revolution (Jun 30)'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'ثورة 23 يوليو (23 يوليو)' : 'July 23 Revolution (Jul 23)'; ?></li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-success"><i class="fas fa-mosque me-1"></i><?php echo __('religious_holiday'); ?></h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'عيد الفطر' : 'Eid Al-Fitr'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'عيد الأضحى' : 'Eid Al-Adha'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'رأس السنة الهجرية' : 'Islamic New Year'; ?></li>
                            <li><i class="fas fa-check-circle text-success me-1"></i> <?php echo Translation::getDirection() == 'rtl' ? 'المولد النبوي' : 'Prophet\'s Birthday'; ?></li>
                        </ul>
                    </div>
                </div>
                
                <div class="alert alert-warning mt-3">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <?php echo Translation::getDirection() == 'rtl' ? 
                        'ملاحظة: تواريخ الأعياد الدينية تقريبية وقد تحتاج للتعديل حسب الرؤية الشرعية' : 
                        'Note: Religious holiday dates are approximate and may need adjustment based on moon sighting'; ?>
                </div>
                
                <form method="POST">
                    <input type="hidden" name="action" value="import_default_holidays">
                    <button type="submit" class="btn btn-success w-100 mt-3">
                        <i class="fas fa-download me-2"></i>
                        <?php echo Translation::getDirection() == 'rtl' ? 'استيراد العطلات الافتراضية' : 'Import Default Holidays'; ?>
                    </button>
                </form>
                
                <hr>
                <form method="POST" onsubmit="return confirm('<?php echo Translation::getDirection() == 'rtl' ? 'هل تريد حذف الإجازات المكررة؟' : 'Remove duplicate holidays?'; ?>')">
                    <input type="hidden" name="action" value="remove_duplicate_holidays">
                    <button type="submit" class="btn btn-outline-danger w-100 mt-2">
                        <i class="fas fa-broom me-2"></i>
                        <?php echo Translation::getDirection() == 'rtl' ? 'حذف الإجازات المكررة' : 'Remove Duplicate Holidays'; ?>
                    </button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times me-1"></i><?php echo __('close'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>
function toggleDateType() {
    const singleDateSection = document.getElementById('single_date_section');
    const dateRangeSection = document.getElementById('date_range_section');
    const singleDateRadio = document.getElementById('single_date');
    const holidayDate = document.getElementById('holiday_date');
    const startHolidayDate = document.getElementById('start_holiday_date');
    const endHolidayDate = document.getElementById('end_holiday_date');
    
    if (singleDateRadio.checked) {
        singleDateSection.style.display = 'block';
        dateRangeSection.style.display = 'none';
        holidayDate.required = true;
        startHolidayDate.required = false;
        endHolidayDate.required = false;
    } else {
        singleDateSection.style.display = 'none';
        dateRangeSection.style.display = 'block';
        holidayDate.required = false;
        startHolidayDate.required = true;
        endHolidayDate.required = true;
    }
}

function editHoliday(holiday) {
    document.getElementById('edit_holiday_id').value = holiday.id;
    document.getElementById('edit_holiday_name').value = holiday.holiday_name;
    document.getElementById('edit_holiday_date').value = holiday.holiday_date;
    document.getElementById('edit_holiday_type').value = holiday.holiday_type;
    document.getElementById('edit_color').value = holiday.color;
    document.getElementById('edit_is_recurring').checked = holiday.is_recurring == 1;
    
    var editModal = new bootstrap.Modal(document.getElementById('editHolidayModal'));
    editModal.show();
}
</script>

<script>
function setDefaultDates() {
    // حساب التاريخ الافتراضي (من 21 الشهر الماضي إلى 20 الشهر الحالي)
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth() + 1; // 0-indexed
    
    // الشهر السابق
    let prevMonth = currentMonth - 1;
    let prevYear = currentYear;
    if (prevMonth === 0) {
        prevMonth = 12;
        prevYear = currentYear - 1;
    }
    
    // تنسيق التواريخ
    const startDate = `${prevYear}-${String(prevMonth).padStart(2, '0')}-21`;
    const endDate = `${currentYear}-${String(currentMonth).padStart(2, '0')}-20`;
    
    document.getElementById('start_date').value = startDate;
    document.getElementById('end_date').value = endDate;
}
</script>

    </div><!-- end main-content-container -->
<?php include 'includes/footer.php'; ?>
