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

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

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

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

// إضافة جداول جديدة لمحاضر الكسر وإعدام الأدوية إذا لم تكن موجودة
try {
    // جدول محاضر الكسر (موجود بالفعل في قاعدة البيانات)
    $pdo->exec("CREATE TABLE IF NOT EXISTS breakage_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_date DATE NOT NULL,
        item_name VARCHAR(255) NOT NULL,
        quantity INT NOT NULL,
        reason TEXT,
        reported_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (reported_by) REFERENCES users(id)
    )");
    
    // جدول محاضر إعدام الأدوية المخدرة
    $pdo->exec("CREATE TABLE IF NOT EXISTS narcotic_disposal_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_date DATE NOT NULL,
        drug_name VARCHAR(255) NOT NULL,
        quantity INT NOT NULL,
        disposal_reason ENUM('expired', 'damaged', 'other') DEFAULT 'expired',
        reported_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (reported_by) REFERENCES users(id)
    )");
    
    // جدول محاضر إعدام الأدوية منتهية الصلاحية (موجود بالفعل في قاعدة البيانات)
    $pdo->exec("CREATE TABLE IF NOT EXISTS expired_drugs_disposal (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_date DATE NOT NULL,
        drug_name VARCHAR(255) NOT NULL,
        quantity INT NOT NULL,
        expiry_date DATE,
        batch_number VARCHAR(100),
        notes TEXT,
        reported_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (reported_by) REFERENCES users(id)
    )");
    
} catch (PDOException $e) {
    // تجاهل الأخطاء إذا كانت الجداول موجودة بالفعل
}

// الحصول على التاريخ والوقت الحالي
$current_date = date('Y-m-d');
$arabic_date = date('d/m/Y');
$current_time = date('H:i:s');
$arabic_time = date('h:i A');

// تحديد الشيفت حسب الوقت
$hour = date('H');
if ($hour >= 6 && $hour < 14) {
    $shift = __('morning_shift');
    $shift_time = __('morning_shift_time');
} elseif ($hour >= 14 && $hour < 22) {
    $shift = __('evening_shift');
    $shift_time = __('evening_shift_time');
} else {
    $shift = __('night_shift');
    $shift_time = __('night_shift_time');
}

// معالجة الفلاتر
$view_type = $_GET['view_type'] ?? 'daily';
$filter_date = $_GET['filter_date'] ?? $current_date;
$filter_month = $_GET['filter_month'] ?? date('Y-m');
$filter_year = $_GET['filter_year'] ?? date('Y');
$filter_user = $_GET['filter_user'] ?? '';

// بناء شروط الاستعلام حسب نوع العرض
$date_condition = "";
$date_params = [];

switch ($view_type) {
    case 'daily':
        $date_condition = "DATE(created_at) = ?";
        $date_params[] = $filter_date;
        break;
    case 'monthly':
        $date_condition = "DATE_FORMAT(created_at, '%Y-%m') = ?";
        $date_params[] = $filter_month;
        break;
    case 'yearly':
        $date_condition = "YEAR(created_at) = ?";
        $date_params[] = $filter_year;
        break;
}

// إضافة فلتر المستخدم إذا تم تحديده
$user_condition = "";
$user_params = [];
if (!empty($filter_user)) {
    $user_condition = " AND reporting_pharmacist_id = ?";
    $user_params[] = $filter_user;
}

// الحصول على قائمة المستخدمين للفلتر
try {
    $stmt = $pdo->query("SELECT id, full_name FROM users ORDER BY full_name");
    $users = $stmt->fetchAll();
} catch (PDOException $e) {
    $users = [];
}

// استعلامات الإحصائيات
try {
    // عدد العمليات
    $stmt = $pdo->prepare("SELECT COUNT(*) as total_operations FROM antibiotic_reports WHERE $date_condition $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $total_operations = $stmt->fetch()['total_operations'];

    // حالة الاحتياج هل تم تجهيز مطلبة
    $stmt = $pdo->prepare("SELECT COUNT(*) as completed FROM antibiotic_reports WHERE $date_condition AND status = 'completed' $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $completed_requests = $stmt->fetch()['completed'];

    // تقرير المجز والبريادة كل 3 أيام
    if ($view_type == 'daily') {
        $three_days_ago = date('Y-m-d', strtotime($filter_date . ' -3 days'));
        $stmt = $pdo->prepare("SELECT COUNT(*) as reports_3days FROM antibiotic_reports WHERE DATE(created_at) >= ? $user_condition");
        $stmt->execute(array_merge([$three_days_ago], $user_params));
    } else {
        $stmt = $pdo->prepare("SELECT COUNT(*) as reports_3days FROM antibiotic_reports WHERE $date_condition $user_condition");
        $stmt->execute(array_merge($date_params, $user_params));
    }
    $reports_3days = $stmt->fetch()['reports_3days'];

    // عدد الحالات التي تم متابعتها
    $stmt = $pdo->prepare("SELECT COUNT(*) as followed_cases FROM antibiotic_reports WHERE $date_condition AND status != 'pending' $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $followed_cases = $stmt->fetch()['followed_cases'];

    // عدد الحالات التي لم تتابق
    $stmt = $pdo->prepare("SELECT COUNT(*) as unfollowed_cases FROM antibiotic_reports WHERE $date_condition AND status = 'pending' $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $unfollowed_cases = $stmt->fetch()['unfollowed_cases'];

    // عدد الغرف المشغولة
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT unit_id) as occupied_rooms FROM antibiotic_reports WHERE $date_condition $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $occupied_rooms = $stmt->fetch()['occupied_rooms'];

    // عدد حالات القسطرة إن وجد - تحسين الاستعلام
    $stmt = $pdo->prepare("SELECT COUNT(*) as catheter_cases FROM antibiotic_reports WHERE $date_condition AND (
        intervention_choice LIKE '%catheter%' OR 
        intervention_choice = 'catheter' OR
        intervention_choice LIKE '%قسطرة%' OR
        JSON_CONTAINS(intervention_choice, '\"catheter\"') OR
        JSON_CONTAINS(intervention_choice, '\"قسطرة\"')
    ) $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $catheter_cases = $stmt->fetch()['catheter_cases'];

    // عدد حالات الأسنان إن وجد - تحسين الاستعلام
    $stmt = $pdo->prepare("SELECT COUNT(*) as dental_cases FROM antibiotic_reports WHERE $date_condition AND (
        intervention_choice LIKE '%dental%' OR 
        intervention_choice = 'dental' OR
        intervention_choice LIKE '%أسنان%' OR
        intervention_choice LIKE '%سن%' OR
        JSON_CONTAINS(intervention_choice, '\"dental\"') OR
        JSON_CONTAINS(intervention_choice, '\"أسنان\"')
    ) $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $dental_cases = $stmt->fetch()['dental_cases'];

    // المعدل اليومي لاستهلاك الأبرة - تحسين الاستعلام
    $stmt = $pdo->prepare("SELECT COUNT(*) as injection_usage FROM antibiotic_reports WHERE $date_condition AND (
        intervention_choice LIKE '%injection%' OR 
        intervention_choice = 'injection' OR
        intervention_choice LIKE '%حقن%' OR
        intervention_choice LIKE '%أبرة%' OR
        JSON_CONTAINS(intervention_choice, '\"injection\"') OR
        JSON_CONTAINS(intervention_choice, '\"حقن\"')
    ) $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $injection_usage = $stmt->fetch()['injection_usage'];

    // المعدل اليومي لاستهلاك السيفو - تحسين الاستعلام
    $cephalosporin_date_condition = str_replace('created_at', 'ar.created_at', $date_condition);
    $cephalosporin_user_condition = !empty($filter_user) ? " AND ar.reporting_pharmacist_id = ?" : "";
    $stmt = $pdo->prepare("SELECT COUNT(*) as cephalosporin_usage FROM antibiotic_reports ar 
        JOIN antibiotics a ON ar.antibiotic_id = a.id 
        WHERE $cephalosporin_date_condition AND (
            a.category = 'Cephalosporin' OR 
            a.category LIKE '%ceph%' OR 
            a.antibiotic_name LIKE '%سيف%' OR
            a.antibiotic_name LIKE '%ceph%' OR
            a.generic_name LIKE '%ceph%'
        ) $cephalosporin_user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $cephalosporin_usage = $stmt->fetch()['cephalosporin_usage'];

    // عدد حالات التخدير الكلي - تحسين الاستعلام
    $stmt = $pdo->prepare("SELECT COUNT(*) as general_anesthesia FROM antibiotic_reports WHERE $date_condition AND (
        degree_of_damage LIKE '%general%' OR 
        degree_of_damage = 'general' OR
        degree_of_damage LIKE '%كلي%' OR
        degree_of_damage LIKE '%عام%' OR
        JSON_CONTAINS(degree_of_damage, '\"general\"') OR
        JSON_CONTAINS(degree_of_damage, '\"كلي\"')
    ) $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $general_anesthesia = $stmt->fetch()['general_anesthesia'];

    // عدد حالات التخدير النصفي - تحسين الاستعلام
    $stmt = $pdo->prepare("SELECT COUNT(*) as spinal_anesthesia FROM antibiotic_reports WHERE $date_condition AND (
        degree_of_damage LIKE '%spinal%' OR 
        degree_of_damage = 'spinal' OR
        degree_of_damage LIKE '%نصفي%' OR
        degree_of_damage LIKE '%شوكي%' OR
        JSON_CONTAINS(degree_of_damage, '\"spinal\"') OR
        JSON_CONTAINS(degree_of_damage, '\"نصفي\"')
    ) $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $spinal_anesthesia = $stmt->fetch()['spinal_anesthesia'];

    // عدد حالات التخدير الموضعي - تحسين الاستعلام
    $stmt = $pdo->prepare("SELECT COUNT(*) as local_anesthesia FROM antibiotic_reports WHERE $date_condition AND (
        degree_of_damage LIKE '%local%' OR 
        degree_of_damage = 'local' OR
        degree_of_damage LIKE '%موضعي%' OR
        JSON_CONTAINS(degree_of_damage, '\"local\"') OR
        JSON_CONTAINS(degree_of_damage, '\"موضعي\"')
    ) $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $local_anesthesia = $stmt->fetch()['local_anesthesia'];

    // تحديد شرط التاريخ لمحاضر الكسر والإعدام
    $report_date_condition = str_replace('created_at', 'report_date', $date_condition);
    $report_user_condition = !empty($filter_user) ? " AND reported_by = ?" : "";

    // عدد محاضر الكسر
    $stmt = $pdo->prepare("SELECT COUNT(*) as breakage_reports FROM breakage_reports WHERE $report_date_condition $report_user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $breakage_reports = $stmt->fetch()['breakage_reports'];

    // عدد محاضر إعدام الأدوية المخدرة
    $stmt = $pdo->prepare("SELECT COUNT(*) as narcotic_disposal FROM narcotic_disposal_reports WHERE $report_date_condition $report_user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $narcotic_disposal = $stmt->fetch()['narcotic_disposal'];

    // عدد محاضر إعدام الأدوية منتهية الصلاحية
    $stmt = $pdo->prepare("SELECT COUNT(*) as expired_disposal FROM expired_drugs_disposal WHERE $report_date_condition $report_user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $expired_disposal = $stmt->fetch()['expired_disposal'];

    // إحصائيات إضافية مفيدة
    // إجمالي كمية الأصناف المكسورة
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(quantity), 0) as total_broken_items FROM breakage_reports WHERE $report_date_condition $report_user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $total_broken_items = $stmt->fetch()['total_broken_items'];

    // إجمالي كمية الأدوية المخدرة المعدومة
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(quantity), 0) as total_narcotic_disposed FROM narcotic_disposal_reports WHERE $report_date_condition $report_user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $total_narcotic_disposed = $stmt->fetch()['total_narcotic_disposed'];

    // إجمالي كمية الأدوية منتهية الصلاحية المعدومة
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(quantity), 0) as total_expired_disposed FROM expired_drugs_disposal WHERE $report_date_condition $report_user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $total_expired_disposed = $stmt->fetch()['total_expired_disposed'];

    // عدد المرضى الفريدين
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT patient_id) as unique_patients FROM antibiotic_reports WHERE $date_condition $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $unique_patients = $stmt->fetch()['unique_patients'];

    // عدد المضادات الحيوية المختلفة المستخدمة
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT antibiotic_id) as unique_antibiotics FROM antibiotic_reports WHERE $date_condition $user_condition");
    $stmt->execute(array_merge($date_params, $user_params));
    $unique_antibiotics = $stmt->fetch()['unique_antibiotics'];

} catch (PDOException $e) {
    $error_message = "خطأ في قاعدة البيانات: " . $e->getMessage();
    // تعيين قيم افتراضية في حالة الخطأ
    $total_operations = 0;
    $completed_requests = 0;
    $reports_3days = 0;
    $followed_cases = 0;
    $unfollowed_cases = 0;
    $occupied_rooms = 0;
    $catheter_cases = 0;
    $dental_cases = 0;
    $injection_usage = 0;
    $cephalosporin_usage = 0;
    $general_anesthesia = 0;
    $spinal_anesthesia = 0;
    $local_anesthesia = 0;
    $breakage_reports = 0;
    $narcotic_disposal = 0;
    $expired_disposal = 0;
    $total_broken_items = 0;
    $total_narcotic_disposed = 0;
    $total_expired_disposed = 0;
    $unique_patients = 0;
    $unique_antibiotics = 0;
}

// معالجة تحديث الإحصائيات
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_stats'])) {
    try {
        // إنشاء جدول لحفظ الإحصائيات المخصصة إذا لم يكن موجوداً
        $pdo->exec("CREATE TABLE IF NOT EXISTS custom_stats (
            id INT AUTO_INCREMENT PRIMARY KEY,
            stat_date DATE NOT NULL,
            stat_name VARCHAR(100) NOT NULL,
            stat_value VARCHAR(50) NOT NULL,
            updated_by INT,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_stat (stat_date, stat_name),
            FOREIGN KEY (updated_by) REFERENCES users(id)
        )");
        
        // قائمة الإحصائيات المطلوب تحديثها
        $stats_to_update = [
            'breakage_reports', 'narcotic_disposal', 'expired_disposal',
            'total_operations', 'completed_requests', 'reports_3days',
            'followed_cases', 'unfollowed_cases', 'occupied_rooms',
            'catheter_cases', 'dental_cases', 'injection_usage',
            'cephalosporin_usage', 'general_anesthesia', 'spinal_anesthesia',
            'local_anesthesia', 'unique_patients', 'unique_antibiotics',
            'total_broken_items', 'total_narcotic_disposed', 'total_expired_disposed'
        ];
        
        foreach ($stats_to_update as $stat_name) {
            if (isset($_POST[$stat_name])) {
                $stmt = $pdo->prepare("INSERT INTO custom_stats (stat_date, stat_name, stat_value, updated_by) 
                                     VALUES (?, ?, ?, ?) 
                                     ON DUPLICATE KEY UPDATE stat_value = VALUES(stat_value), updated_by = VALUES(updated_by)");
                $stmt->execute([$current_date, $stat_name, $_POST[$stat_name], $_SESSION['user_id']]);
            }
        }
        
        $success_message = "تم تحديث الإحصائيات بنجاح";
        
    } catch (PDOException $e) {
        $error_message = "خطأ في تحديث الإحصائيات: " . $e->getMessage();
    }
}

// دالة للحصول على القيمة المخصصة أو القيمة الافتراضية
function getCustomStat($pdo, $date, $stat_name, $default_value) {
    try {
        $stmt = $pdo->prepare("SELECT stat_value FROM custom_stats WHERE stat_date = ? AND stat_name = ?");
        $stmt->execute([$date, $stat_name]);
        $result = $stmt->fetch();
        return $result ? $result['stat_value'] : $default_value;
    } catch (PDOException $e) {
        return $default_value;
    }
}

// تحديث القيم بالقيم المخصصة إن وجدت
$breakage_reports = getCustomStat($pdo, $current_date, 'breakage_reports', $breakage_reports);
$narcotic_disposal = getCustomStat($pdo, $current_date, 'narcotic_disposal', $narcotic_disposal);
$expired_disposal = getCustomStat($pdo, $current_date, 'expired_disposal', $expired_disposal);
$total_operations = getCustomStat($pdo, $current_date, 'total_operations', $total_operations);
$completed_requests = getCustomStat($pdo, $current_date, 'completed_requests', $completed_requests);
$reports_3days = getCustomStat($pdo, $current_date, 'reports_3days', $reports_3days);
$followed_cases = getCustomStat($pdo, $current_date, 'followed_cases', $followed_cases);
$unfollowed_cases = getCustomStat($pdo, $current_date, 'unfollowed_cases', $unfollowed_cases);
$occupied_rooms = getCustomStat($pdo, $current_date, 'occupied_rooms', $occupied_rooms);
$catheter_cases = getCustomStat($pdo, $current_date, 'catheter_cases', $catheter_cases);
$dental_cases = getCustomStat($pdo, $current_date, 'dental_cases', $dental_cases);
$injection_usage = getCustomStat($pdo, $current_date, 'injection_usage', $injection_usage);
$cephalosporin_usage = getCustomStat($pdo, $current_date, 'cephalosporin_usage', $cephalosporin_usage);
$general_anesthesia = getCustomStat($pdo, $current_date, 'general_anesthesia', $general_anesthesia);
$spinal_anesthesia = getCustomStat($pdo, $current_date, 'spinal_anesthesia', $spinal_anesthesia);
$local_anesthesia = getCustomStat($pdo, $current_date, 'local_anesthesia', $local_anesthesia);
$unique_patients = getCustomStat($pdo, $current_date, 'unique_patients', $unique_patients);
$unique_antibiotics = getCustomStat($pdo, $current_date, 'unique_antibiotics', $unique_antibiotics);
$total_broken_items = getCustomStat($pdo, $current_date, 'total_broken_items', $total_broken_items);
$total_narcotic_disposed = getCustomStat($pdo, $current_date, 'total_narcotic_disposed', $total_narcotic_disposed);
$total_expired_disposed = getCustomStat($pdo, $current_date, 'total_expired_disposed', $total_expired_disposed);

// إعادة توجيه بعد الحفظ لتجنب إعادة الإرسال
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_stats']) && isset($success_message)) {
    header("Location: " . $_SERVER['PHP_SELF'] . "?updated=1");
    exit();
}

include 'includes/header.php';
?>

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

.dashboard-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}

.stat-box {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 20px;
    position: relative;
    overflow: hidden;
}

.stat-box::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: rgba(255,255,255,0.1);
    transform: rotate(45deg);
}

.stat-box.blue { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-box.green { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
.stat-box.orange { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-box.purple { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-box.red { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.stat-box.teal { background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); }

.stat-number {
    font-size: 2.8rem;
    font-weight: bold;
    margin-bottom: 5px;
    position: relative;
    z-index: 1;
}

.stat-label {
    font-size: 1rem;
    opacity: 0.95;
    position: relative;
    z-index: 1;
}

.stat-icon {
    position: absolute;
    bottom: 10px;
    left: 10px;
    font-size: 4rem;
    opacity: 0.2;
}

.report-header-card {
    background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
    color: white;
    border-radius: 15px;
    padding: 40px;
    text-align: center;
    margin-bottom: 30px;
    position: relative;
    overflow: hidden;
}

.hospital-logo {
    width: 80px;
    height: 80px;
    background: white;
    border-radius: 50%;
    margin: 0 auto 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #2c3e50;
    border: 3px solid #ecf0f1;
}

.report-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
}

.report-subtitle {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 5px;
}

.report-date {
    font-size: 14px;
    opacity: 0.8;
}

.blue-text {
    color: #3498db !important;
    font-weight: bold;
}

.chart-container {
    position: relative;
    height: 350px;
    padding: 20px;
}

.section-title {
    font-size: 1.3rem;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 3px solid #667eea;
}

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

.edit-input {
    background: rgba(255,255,255,0.9);
    border: 2px solid #fff;
    border-radius: 8px;
    color: #2c3e50;
    font-weight: bold;
    text-align: center;
    font-size: 1.5rem;
}

.edit-input:focus {
    background: white;
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.stat-box .form-select.edit-input {
    font-size: 1.5rem;
    padding: 8px;
}

@media print {
    .no-print { display: none; }
    .dashboard-card { box-shadow: none; }
    .edit-input { display: none !important; }
    .display-value { display: inline !important; }
}
</style>


    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <div>
            <h1 class="h3 mb-0"><?php echo __('operations_team_report_title'); ?> <?php echo __('shift'); ?> <span class="live-shift"><?php echo $shift; ?></span></h1>
            <p class="text-muted mb-0"><?php echo __('comprehensive_report_operations_team'); ?> - <span class="live-date"><?php echo $arabic_date; ?></span> - <span class="live-time"><?php echo $arabic_time; ?></span> (<span class="live-shift-time"><?php echo $shift_time; ?></span>)</p>
        </div>
        <div>
            <a href="operations_management.php" class="btn btn-primary me-2">
                <i class="fas fa-cogs"></i> <?php echo __('operations_management'); ?>
            </a>
            <button type="button" class="btn btn-success me-2" onclick="exportToExcel()">
                <i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>
            </button>
            <button type="button" class="btn btn-outline-primary action-btn" onclick="window.print()">
                <i class="fas fa-print"></i> <?php echo __('print'); ?>
            </button>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4 no-print">
        <div class="card-header">
            <h5 class="card-title mb-0"><i class="fas fa-filter me-2"></i><?php echo __('report_filters'); ?></h5>
        </div>
        <div class="card-body">
            <form method="GET" id="filterForm">
                <div class="row">
                    <div class="col-md-3">
                        <label class="form-label"><?php echo __('view_type'); ?>:</label>
                        <select name="view_type" class="form-select" onchange="toggleDateFilters()">
                            <option value="daily" <?php echo $view_type == 'daily' ? 'selected' : ''; ?>><?php echo __('daily'); ?></option>
                            <option value="monthly" <?php echo $view_type == 'monthly' ? 'selected' : ''; ?>><?php echo __('monthly'); ?></option>
                            <option value="yearly" <?php echo $view_type == 'yearly' ? 'selected' : ''; ?>><?php echo __('yearly'); ?></option>
                        </select>
                    </div>
                    <div class="col-md-3" id="daily-filter" style="<?php echo $view_type != 'daily' ? 'display:none' : ''; ?>">
                        <label class="form-label"><?php echo __('date'); ?>:</label>
                        <input type="date" name="filter_date" class="form-control" value="<?php echo $filter_date; ?>">
                    </div>
                    <div class="col-md-3" id="monthly-filter" style="<?php echo $view_type != 'monthly' ? 'display:none' : ''; ?>">
                        <label class="form-label"><?php echo __('month'); ?>:</label>
                        <input type="month" name="filter_month" class="form-control" value="<?php echo $filter_month; ?>">
                    </div>
                    <div class="col-md-3" id="yearly-filter" style="<?php echo $view_type != 'yearly' ? 'display:none' : ''; ?>">
                        <label class="form-label"><?php echo __('year'); ?>:</label>
                        <input type="number" name="filter_year" class="form-control" value="<?php echo $filter_year; ?>" min="2020" max="2030">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><?php echo __('user'); ?>:</label>
                        <select name="filter_user" class="form-select">
                            <option value=""><?php echo __('all_users'); ?></option>
                            <?php foreach ($users as $user_option): ?>
                                <option value="<?php echo $user_option['id']; ?>" <?php echo $filter_user == $user_option['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user_option['full_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search me-1"></i><?php echo __('apply_filters'); ?>
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="resetFilters()">
                            <i class="fas fa-undo me-1"></i><?php echo __('reset'); ?>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- رسائل النجاح والخطأ -->
    <?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($_GET['updated']) && $_GET['updated'] == '1'): ?>
        <div class="alert alert-success alert-dismissible fade show no-print">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo __('stats_updated_success'); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

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

    <!-- معلومات التقرير -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h6 class="text-muted mb-2"><i class="fas fa-info-circle me-2"></i><?php echo __('report_information'); ?></h6>
                    <p class="mb-1"><strong><?php echo __('view_type'); ?>:</strong> 
                        <?php 
                        $view_types = [
                            'daily' => __('daily'),
                            'monthly' => __('monthly'), 
                            'yearly' => __('yearly')
                        ];
                        echo $view_types[$view_type];
                        ?>
                    </p>
                    <p class="mb-1"><strong><?php echo __('period'); ?>:</strong> 
                        <?php 
                        switch($view_type) {
                            case 'daily':
                                echo date('d/m/Y', strtotime($filter_date));
                                break;
                            case 'monthly':
                                echo date('m/Y', strtotime($filter_month . '-01'));
                                break;
                            case 'yearly':
                                echo $filter_year;
                                break;
                        }
                        ?>
                    </p>
                    <?php if (!empty($filter_user)): ?>
                    <p class="mb-1"><strong><?php echo __('user_filter'); ?>:</strong> 
                        <?php 
                        foreach($users as $u) {
                            if($u['id'] == $filter_user) {
                                echo htmlspecialchars($u['full_name']);
                                break;
                            }
                        }
                        ?>
                    </p>
                    <?php endif; ?>
                </div>
                <div class="col-md-6">
                    <h6 class="text-muted mb-2"><i class="fas fa-user me-2"></i><?php echo __('user_information'); ?></h6>
                    <p class="mb-1"><strong><?php echo __('report_created_by'); ?>:</strong> <?php echo htmlspecialchars($user['full_name'] ?? __('not_specified')); ?></p>
                    <p class="mb-1"><strong><?php echo __('role'); ?>:</strong> <?php echo htmlspecialchars($user['role'] ?? __('not_specified')); ?></p>
                    <p class="mb-1"><strong><?php echo __('creation_date'); ?>:</strong> <?php echo date('d/m/Y H:i'); ?></p>
                    <p class="mb-0"><strong><?php echo __('current_shift'); ?>:</strong> <?php echo $shift . ' (' . $shift_time . ')'; ?></p>
                </div>
            </div>
        </div>
    </div>



    <!-- محاضر الكسر والإعدام -->
    <div class="card dashboard-card mb-4">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="section-title mb-0"><?php echo __('breakage_disposal_reports'); ?></h6>
                <button class="btn btn-sm btn-outline-primary" id="edit-toggle-btn">
                    <i class="fas fa-edit me-1"></i>
                    <span id="edit-btn-text"><?php echo __('edit_numbers'); ?></span>
                </button>
            </div>
            <form id="stats-form" method="POST" style="display: none;">
                <input type="hidden" name="update_stats" value="1">
            </form>
            <div class="row">
                <div class="col-md-4 mb-3">
                    <div class="stat-box blue">
                        <div class="stat-number">
                            <span class="display-value"><?php echo $breakage_reports; ?></span>
                            <input type="number" class="form-control edit-input" name="breakage_reports" 
                                   value="<?php echo $breakage_reports; ?>" min="0" style="display: none;" form="stats-form">
                        </div>
                        <div class="stat-label"><?php echo __('breakage_reports_count'); ?></div>
                        <i class="fas fa-broken-image stat-icon"></i>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="stat-box red">
                        <div class="stat-number">
                            <span class="display-value"><?php echo $narcotic_disposal; ?></span>
                            <input type="number" class="form-control edit-input" name="narcotic_disposal" 
                                   value="<?php echo $narcotic_disposal; ?>" min="0" style="display: none;" form="stats-form">
                        </div>
                        <div class="stat-label"><?php echo __('narcotic_disposal_count'); ?></div>
                        <i class="fas fa-skull-crossbones stat-icon"></i>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="stat-box orange">
                        <div class="stat-number">
                            <span class="display-value"><?php echo $expired_disposal; ?></span>
                            <input type="number" class="form-control edit-input" name="expired_disposal" 
                                   value="<?php echo $expired_disposal; ?>" min="0" style="display: none;" form="stats-form">
                        </div>
                        <div class="stat-label"><?php echo __('expired_disposal_count'); ?></div>
                        <i class="fas fa-calendar-times stat-icon"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- الإحصائيات التفصيلية -->
    <div class="row mb-4">
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box blue">
                <div class="stat-number">
                    <span class="display-value"><?php echo $total_operations; ?></span>
                    <input type="number" class="form-control edit-input" name="total_operations" 
                           value="<?php echo $total_operations; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('operations_count'); ?></div>
                <i class="fas fa-procedures stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box green">
                <div class="stat-number">
                    <span class="display-value"><?php echo $completed_requests > 0 ? __('yes') : __('no'); ?></span>
                    <select class="form-select edit-input" name="completed_requests" style="display: none;" form="stats-form">
                        <option value="0" <?php echo $completed_requests == 0 ? 'selected' : ''; ?>><?php echo __('no'); ?></option>
                        <option value="1" <?php echo $completed_requests > 0 ? 'selected' : ''; ?>><?php echo __('yes'); ?></option>
                    </select>
                </div>
                <div class="stat-label"><?php echo __('need_status_prepared'); ?></div>
                <i class="fas fa-check-circle stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box purple">
                <div class="stat-number">
                    <span class="display-value"><?php echo $reports_3days; ?></span>
                    <input type="number" class="form-control edit-input" name="reports_3days" 
                           value="<?php echo $reports_3days; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('deficit_surplus_report_3days'); ?></div>
                <i class="fas fa-calendar-alt stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box teal">
                <div class="stat-number">
                    <span class="display-value"><?php echo $followed_cases; ?></span>
                    <input type="number" class="form-control edit-input" name="followed_cases" 
                           value="<?php echo $followed_cases; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('matched_cases_count'); ?></div>
                <i class="fas fa-eye stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box red">
                <div class="stat-number">
                    <span class="display-value"><?php echo $unfollowed_cases; ?></span>
                    <input type="number" class="form-control edit-input" name="unfollowed_cases" 
                           value="<?php echo $unfollowed_cases; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('unmatched_cases_count'); ?></div>
                <i class="fas fa-exclamation-triangle stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box orange">
                <div class="stat-number">
                    <span class="display-value"><?php echo $occupied_rooms; ?></span>
                    <input type="number" class="form-control edit-input" name="occupied_rooms" 
                           value="<?php echo $occupied_rooms; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('occupied_rooms_count'); ?></div>
                <i class="fas fa-bed stat-icon"></i>
            </div>
        </div>
    </div>

    <!-- إحصائيات إضافية -->
    <div class="row mb-4">
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box blue">
                <div class="stat-number">
                    <span class="display-value"><?php echo $catheter_cases; ?></span>
                    <input type="number" class="form-control edit-input" name="catheter_cases" 
                           value="<?php echo $catheter_cases; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('catheter_cases_count'); ?></div>
                <i class="fas fa-syringe stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box green">
                <div class="stat-number">
                    <span class="display-value"><?php echo $dental_cases; ?></span>
                    <input type="number" class="form-control edit-input" name="dental_cases" 
                           value="<?php echo $dental_cases; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('dental_cases_count'); ?></div>
                <i class="fas fa-tooth stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box purple">
                <div class="stat-number">
                    <span class="display-value"><?php echo $injection_usage; ?></span>
                    <input type="number" class="form-control edit-input" name="injection_usage" 
                           value="<?php echo $injection_usage; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('daily_iso_consumption'); ?></div>
                <i class="fas fa-syringe stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box teal">
                <div class="stat-number">
                    <span class="display-value"><?php echo $cephalosporin_usage; ?></span>
                    <input type="number" class="form-control edit-input" name="cephalosporin_usage" 
                           value="<?php echo $cephalosporin_usage; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('daily_cephalosporin_consumption'); ?></div>
                <i class="fas fa-pills stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box red">
                <div class="stat-number">
                    <span class="display-value"><?php echo $general_anesthesia; ?></span>
                    <input type="number" class="form-control edit-input" name="general_anesthesia" 
                           value="<?php echo $general_anesthesia; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('general_anesthesia_count'); ?></div>
                <i class="fas fa-user-md stat-icon"></i>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box orange">
                <div class="stat-number">
                    <span class="display-value"><?php echo $spinal_anesthesia; ?></span>
                    <input type="number" class="form-control edit-input" name="spinal_anesthesia" 
                           value="<?php echo $spinal_anesthesia; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('spinal_anesthesia_count'); ?></div>
                <i class="fas fa-user-md stat-icon"></i>
            </div>
        </div>
    </div>

    <!-- التخدير الموضعي -->
    <div class="row mb-4">
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="stat-box blue">
                <div class="stat-number">
                    <span class="display-value"><?php echo $local_anesthesia; ?></span>
                    <input type="number" class="form-control edit-input" name="local_anesthesia" 
                           value="<?php echo $local_anesthesia; ?>" min="0" style="display: none;" form="stats-form">
                </div>
                <div class="stat-label"><?php echo __('local_anesthesia_count'); ?></div>
                <i class="fas fa-user-md stat-icon"></i>
            </div>
        </div>
        

    <!-- أزرار الحفظ والإلغاء -->
    <div class="text-center mb-4" id="edit-buttons" style="display: none;">
        <button type="submit" form="stats-form" class="btn btn-success btn-lg me-3">
            <i class="fas fa-save me-2"></i><?php echo __('save_changes'); ?>
        </button>
        <button type="button" class="btn btn-secondary btn-lg" id="cancel-edit-btn">
            <i class="fas fa-times me-2"></i><?php echo __('cancel'); ?>
        </button>
    </div>

    <!-- ملخص اليوم -->
    <div class="card dashboard-card mb-4">
        <div class="card-body">
            <h6 class="section-title"><?php echo __('day_summary'); ?></h6>
            <?php if ($total_operations == 0 && $breakage_reports == 0 && $narcotic_disposal == 0 && $expired_disposal == 0): ?>
                <div class="alert alert-info text-center">
                    <i class="fas fa-info-circle fa-3x mb-3"></i>
                    <h5><?php echo __('no_data_today'); ?></h5>
                    <p><?php echo __('no_data_entered_today'); ?></p>
                    <a href="operations_management.php" class="btn btn-primary">
                        <i class="fas fa-plus me-2"></i><?php echo __('add_new_data'); ?>
                    </a>
                </div>
            <?php else: ?>
                <div class="row">
                    <div class="col-md-6">
                        <div class="alert alert-info">
                            <h6><i class="fas fa-info-circle me-2"></i><?php echo __('quick_statistics'); ?></h6>
                            <ul class="mb-0">
                                <li><?php echo __('total_operations'); ?>: <strong><?php echo $total_operations; ?></strong></li>
                                <li><?php echo __('unique_patients'); ?>: <strong><?php echo $unique_patients; ?></strong></li>
                                <li><?php echo __('different_antibiotics'); ?>: <strong><?php echo $unique_antibiotics; ?></strong></li>
                                <li><?php echo __('occupied_rooms'); ?>: <strong><?php echo $occupied_rooms; ?></strong></li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="alert alert-warning">
                            <h6><i class="fas fa-exclamation-triangle me-2"></i><?php echo __('today_reports'); ?></h6>
                            <ul class="mb-0">
                                <li><?php echo __('breakage_reports_items'); ?>: <strong><?php echo $breakage_reports; ?></strong> (<?php echo $total_broken_items; ?> <?php echo __('pieces'); ?>)</li>
                                <li><?php echo __('narcotic_disposal_units'); ?>: <strong><?php echo $narcotic_disposal; ?></strong> (<?php echo $total_narcotic_disposed; ?> <?php echo __('units'); ?>)</li>
                                <li><?php echo __('expired_disposal_units'); ?>: <strong><?php echo $expired_disposal; ?></strong> (<?php echo $total_expired_disposed; ?> <?php echo __('units'); ?>)</li>
                            </ul>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php if ($total_operations > 0 || $breakage_reports > 0 || $narcotic_disposal > 0 || $expired_disposal > 0): ?>
    <div class="card dashboard-card mb-4">
        <div class="card-body">
            <h6 class="section-title"><?php echo __('cases_distribution'); ?></h6>
            <div class="chart-container">
                <canvas id="casesChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>

    <div class="card dashboard-card mb-4">
        <div class="card-body">
            <h6 class="section-title"><?php echo __('disposal_breakage_reports'); ?></h6>
            <div class="chart-container">
                <canvas id="reportsChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>

    <div class="card dashboard-card mb-4">
        <div class="card-body">
            <h6 class="section-title"><?php echo __('antibiotics_consumption'); ?></h6>
            <div class="chart-container">
                <canvas id="antibioticsChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>

    <div class="card dashboard-card mb-4">
        <div class="card-body">
            <h6 class="section-title"><?php echo __('anesthesia_statistics'); ?></h6>
            <div class="chart-container">
                <canvas id="anesthesiaChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>

    <div class="card dashboard-card mb-4">
        <div class="card-body">
            <h6 class="section-title"><?php echo __('total_disposed_quantities'); ?></h6>
            <div class="chart-container">
                <canvas id="disposalQuantitiesChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script>
        // متغير حالة التعديل
        let isEditMode = false;
        
        // إعداد الصفحة عند التحميل
        document.addEventListener('DOMContentLoaded', function() {
            console.log('صفحة تقرير العمليات - تم تحميل الصفحة');
            
            // إعداد زر التعديل
            const editToggleBtn = document.getElementById('edit-toggle-btn');
            const cancelEditBtn = document.getElementById('cancel-edit-btn');
            
            if (editToggleBtn) {
                editToggleBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    toggleEditMode();
                });
                console.log('تم ربط زر التعديل');
            } else {
                console.error('لم يتم العثور على زر التعديل');
            }
            
            if (cancelEditBtn) {
                cancelEditBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    cancelEdit();
                });
                console.log('تم ربط زر الإلغاء');
            }
            
            // إعداد الحالة الأولية
            resetToViewMode();
            
            // إعداد تحديث القيم عند التغيير
            document.addEventListener('input', function(e) {
                if (e.target && e.target.classList.contains('edit-input')) {
                    updateDisplayValue(e.target);
                }
            });
            
            // إخفاء رسائل النجاح بعد 5 ثوان
            setTimeout(function() {
                const successAlerts = document.querySelectorAll('.alert-success');
                successAlerts.forEach(alert => {
                    if (alert) alert.style.display = 'none';
                });
            }, 5000);
            
            console.log('تم إعداد الصفحة بنجاح');
        });
        
        // دالة تبديل وضع التعديل
        function toggleEditMode() {
            console.log('تبديل وضع التعديل - الحالة الحالية:', isEditMode);
            
            isEditMode = !isEditMode;
            
            const displayValues = document.querySelectorAll('.display-value');
            const editInputs = document.querySelectorAll('.edit-input');
            const editButtons = document.getElementById('edit-buttons');
            const editBtnText = document.getElementById('edit-btn-text');
            const editToggleBtn = document.getElementById('edit-toggle-btn');
            
            console.log('العناصر الموجودة:', {
                displayValues: displayValues.length,
                editInputs: editInputs.length,
                editButtons: !!editButtons,
                editBtnText: !!editBtnText,
                editToggleBtn: !!editToggleBtn
            });
            
            if (isEditMode) {
                // تفعيل وضع التعديل
                displayValues.forEach(el => {
                    if (el) el.style.display = 'none';
                });
                editInputs.forEach(el => {
                    if (el) el.style.display = 'block';
                });
                if (editButtons) editButtons.style.display = 'block';
                if (editBtnText) editBtnText.textContent = '<?php echo __('cancel_edit'); ?>';
                if (editToggleBtn) editToggleBtn.className = 'btn btn-sm btn-outline-danger';
                
                console.log('تم تفعيل وضع التعديل');
            } else {
                // العودة لوضع العرض
                resetToViewMode();
                console.log('تم العودة لوضع العرض');
            }
        }
        
        // دالة إلغاء التعديل
        function cancelEdit() {
            console.log('إلغاء التعديل');
            
            // إعادة القيم الأصلية
            const editInputs = document.querySelectorAll('.edit-input');
            editInputs.forEach(input => {
                if (input) {
                    const originalValue = input.getAttribute('value') || input.defaultValue || '';
                    input.value = originalValue;
                    updateDisplayValue(input);
                }
            });
            
            // العودة لوضع العرض
            isEditMode = false;
            resetToViewMode();
            
            console.log('تم إلغاء التعديل');
        }
        
        // دالة إعادة تعيين وضع العرض
        function resetToViewMode() {
            const displayValues = document.querySelectorAll('.display-value');
            const editInputs = document.querySelectorAll('.edit-input');
            const editButtons = document.getElementById('edit-buttons');
            const editBtnText = document.getElementById('edit-btn-text');
            const editToggleBtn = document.getElementById('edit-toggle-btn');
            
            displayValues.forEach(el => {
                if (el) el.style.display = 'inline';
            });
            editInputs.forEach(el => {
                if (el) el.style.display = 'none';
            });
            if (editButtons) editButtons.style.display = 'none';
            if (editBtnText) editBtnText.textContent = '<?php echo __('edit_numbers'); ?>';
            if (editToggleBtn) editToggleBtn.className = 'btn btn-sm btn-outline-primary';
        }
        
        // دالة تحديث القيمة المعروضة
        function updateDisplayValue(input) {
            const displayValue = input.parentElement.querySelector('.display-value');
            if (displayValue) {
                if (input.type === 'number') {
                    displayValue.textContent = input.value || '0';
                } else if (input.tagName === 'SELECT') {
                    displayValue.textContent = input.value == '1' ? 'نعم' : 'لا';
                }
            }
        }

        <?php if ($total_operations > 0 || $breakage_reports > 0 || $narcotic_disposal > 0 || $expired_disposal > 0): ?>
        // تحديث الوقت كل ثانية
        function updateTime() {
            const now = new Date();
            const timeString = now.toLocaleTimeString('ar-EG', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: true
            });
            const dateString = now.toLocaleDateString('ar-EG');
            
            // تحديد الشيفت حسب الوقت
            const hour = now.getHours();
            let shift, shiftTime;
            if (hour >= 6 && hour < 14) {
                shift = '<?php echo __('morning_shift'); ?>';
                shiftTime = '<?php echo __('morning_shift_time'); ?>';
            } else if (hour >= 14 && hour < 22) {
                shift = '<?php echo __('evening_shift'); ?>';
                shiftTime = '<?php echo __('evening_shift_time'); ?>';
            } else {
                shift = '<?php echo __('night_shift'); ?>';
                shiftTime = '<?php echo __('night_shift_time'); ?>';
            }
            
            // تحديث العناصر في الصفحة
            const timeElements = document.querySelectorAll('.live-time');
            const dateElements = document.querySelectorAll('.live-date');
            const shiftElements = document.querySelectorAll('.live-shift');
            const shiftTimeElements = document.querySelectorAll('.live-shift-time');
            
            timeElements.forEach(el => el.textContent = timeString);
            dateElements.forEach(el => el.textContent = dateString);
            shiftElements.forEach(el => el.textContent = shift);
            shiftTimeElements.forEach(el => el.textContent = shiftTime);
        }
        
        // تحديث الوقت عند تحميل الصفحة وكل ثانية
        updateTime();
        setInterval(updateTime, 1000);

        // رسم بياني لتوزيع الحالات
        const casesCtx = document.getElementById('casesChart').getContext('2d');
        new Chart(casesCtx, {
            type: 'doughnut',
            data: {
                labels: ['<?php echo __('followed_cases'); ?>', '<?php echo __('unfollowed_cases'); ?>', '<?php echo __('completed_cases'); ?>'],
                datasets: [{
                    data: [<?php echo $followed_cases; ?>, <?php echo $unfollowed_cases; ?>, <?php echo $completed_requests; ?>],
                    backgroundColor: ['#3498db', '#e74c3c', '#2ecc71'],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // رسم بياني لمحاضر الإعدام والكسر
        const reportsCtx = document.getElementById('reportsChart').getContext('2d');
        new Chart(reportsCtx, {
            type: 'bar',
            data: {
                labels: ['<?php echo __('breakage_reports_items'); ?>', '<?php echo __('narcotic_disposal_units'); ?>', '<?php echo __('expired_disposal_units'); ?>'],
                datasets: [{
                    label: '<?php echo __('reports_count'); ?>',
                    data: [<?php echo $breakage_reports; ?>, <?php echo $narcotic_disposal; ?>, <?php echo $expired_disposal; ?>],
                    backgroundColor: ['#e74c3c', '#f39c12', '#9b59b6'],
                    borderColor: ['#c0392b', '#e67e22', '#8e44ad'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        // رسم بياني لاستهلاك المضادات الحيوية
        const antibioticsCtx = document.getElementById('antibioticsChart').getContext('2d');
        new Chart(antibioticsCtx, {
            type: 'line',
            data: {
                labels: ['<?php echo __('needles'); ?>', '<?php echo __('cephalosporin'); ?>', '<?php echo __('catheter'); ?>', '<?php echo __('dental'); ?>'],
                datasets: [{
                    label: '<?php echo __('consumption_rate'); ?>',
                    data: [<?php echo $injection_usage; ?>, <?php echo $cephalosporin_usage; ?>, <?php echo $catheter_cases; ?>, <?php echo $dental_cases; ?>],
                    borderColor: '#3498db',
                    backgroundColor: 'rgba(52, 152, 219, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        // رسم بياني لإحصائيات التخدير
        const anesthesiaCtx = document.getElementById('anesthesiaChart').getContext('2d');
        new Chart(anesthesiaCtx, {
            type: 'pie',
            data: {
                labels: ['<?php echo __('general_anesthesia'); ?>', '<?php echo __('spinal_anesthesia'); ?>', '<?php echo __('local_anesthesia'); ?>'],
                datasets: [{
                    data: [<?php echo $general_anesthesia; ?>, <?php echo $spinal_anesthesia; ?>, <?php echo $local_anesthesia; ?>],
                    backgroundColor: ['#e74c3c', '#f39c12', '#2ecc71'],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // رسم بياني لإجمالي الكميات المعدومة
        const disposalQuantitiesCtx = document.getElementById('disposalQuantitiesChart').getContext('2d');
        new Chart(disposalQuantitiesCtx, {
            type: 'bar',
            data: {
                labels: ['<?php echo __('broken_items'); ?>', '<?php echo __('disposed_narcotics'); ?>', '<?php echo __('disposed_expired'); ?>'],
                datasets: [{
                    label: '<?php echo __('quantity'); ?>',
                    data: [<?php echo $total_broken_items; ?>, <?php echo $total_narcotic_disposed; ?>, <?php echo $total_expired_disposed; ?>],
                    backgroundColor: ['#e74c3c', '#f39c12', '#9b59b6'],
                    borderColor: ['#c0392b', '#e67e22', '#8e44ad'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
        <?php endif; ?>

// دوال الفلاتر
function toggleDateFilters() {
    const viewType = document.querySelector('select[name="view_type"]').value;
    
    document.getElementById('daily-filter').style.display = viewType === 'daily' ? 'block' : 'none';
    document.getElementById('monthly-filter').style.display = viewType === 'monthly' ? 'block' : 'none';
    document.getElementById('yearly-filter').style.display = viewType === 'yearly' ? 'block' : 'none';
}

function resetFilters() {
    document.getElementById('filterForm').reset();
    window.location.href = 'operations_team_report.php';
}

function exportToExcel() {
    const params = new URLSearchParams(window.location.search);
    window.location.href = 'export/operations_team_excel.php?' + params.toString();
}
    </script>
</body>
</html>
