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

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

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

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

$page_title = 'Key Performance Indicators - ' . __('system_name');

// إنشاء اتصال قاعدة البيانات
$database = new Database();
$pdo = $database->getConnection();

// التحقق من وجود الجدول وإضافة الحقول المفقودة إذا لزم الأمر
try {
    // التحقق من وجود الحقول المطلوبة
    $columns = $pdo->query("DESCRIBE patient_medication_tracking")->fetchAll(PDO::FETCH_COLUMN);
    
    // إضافة الحقول المفقودة إذا لم تكن موجودة
    if (!in_array('unit_id', $columns)) {
        $pdo->exec("ALTER TABLE patient_medication_tracking ADD COLUMN unit_id INT(11) AFTER tracking_date");
        error_log("Added unit_id column to patient_medication_tracking table");
    }
    if (!in_array('documentation_quality', $columns)) {
        $pdo->exec("ALTER TABLE patient_medication_tracking ADD COLUMN documentation_quality TINYINT DEFAULT 0");
        error_log("Added documentation_quality column to patient_medication_tracking table");
    }
    if (!in_array('drug_definition', $columns)) {
        $pdo->exec("ALTER TABLE patient_medication_tracking ADD COLUMN drug_definition TINYINT DEFAULT 0 AFTER error_documentation");
        error_log("Added drug_definition column to patient_medication_tracking table");
    }
    if (!in_array('pharmacist_name', $columns)) {
        $pdo->exec("ALTER TABLE patient_medication_tracking ADD COLUMN pharmacist_name VARCHAR(100)");
        error_log("Added pharmacist_name column to patient_medication_tracking table");
    }
    
    error_log("patient_medication_tracking table verified and updated if needed");
} catch (Exception $e) {
    error_log("Error checking patient_medication_tracking table: " . $e->getMessage());
}

// جلب الأقسام من قاعدة البيانات
$units_stmt = $pdo->query("SELECT id, unit_name FROM units WHERE is_active = 1 ORDER BY unit_name");
$units = $units_stmt->fetchAll(PDO::FETCH_ASSOC);

// --------------------------
// DASHBOARD DATA
// --------------------------
$dashboard_from_date = $_GET['dashboard_from'] ?? date('Y-m-01');
$dashboard_to_date = $_GET['dashboard_to'] ?? date('Y-m-t');
$dashboard_unit = $_GET['dashboard_unit'] ?? '';

// Build query conditions for antibiotic reports
$ar_date_condition = "ar.report_date BETWEEN :ar_from_date AND :ar_to_date";
$ar_unit_condition = $dashboard_unit ? "AND ar.unit_id = :ar_unit_id" : "";

// Build query conditions for patient medication tracking
$pmt_date_condition = "pmt.tracking_date BETWEEN :pmt_from_date AND :pmt_to_date";
$pmt_unit_condition = $dashboard_unit ? "AND pmt.unit_id = :pmt_unit_id" : "";

// --- ANTIBIOTIC REPORTS STATS ---
// Get total antibiotic reports
$total_reports_stmt = $pdo->prepare("SELECT COUNT(*) as count FROM antibiotic_reports ar WHERE $ar_date_condition $ar_unit_condition");
$total_reports_stmt->bindParam(':ar_from_date', $dashboard_from_date);
$total_reports_stmt->bindParam(':ar_to_date', $dashboard_to_date);
if ($dashboard_unit) {
    $total_reports_stmt->bindParam(':ar_unit_id', $dashboard_unit, PDO::PARAM_INT);
}
$total_reports_stmt->execute();
$total_reports = $total_reports_stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
// Pending and completed reports are calculated in the chart data section below

// --- PATIENT MEDICATION TRACKING STATS ---
// Get total patients in medication tracking
$total_patients_stmt = $pdo->prepare("SELECT COUNT(DISTINCT medical_number) as count FROM patient_medication_tracking pmt WHERE $pmt_date_condition $pmt_unit_condition");
$total_patients_stmt->bindParam(':pmt_from_date', $dashboard_from_date);
$total_patients_stmt->bindParam(':pmt_to_date', $dashboard_to_date);
if ($dashboard_unit) {
    $total_patients_stmt->bindParam(':pmt_unit_id', $dashboard_unit, PDO::PARAM_INT);
}
$total_patients_stmt->execute();
$total_patients = $total_patients_stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;

// Get total interventions (sum of all 5 intervention columns)
$total_interventions_stmt = $pdo->prepare("
    SELECT 
        SUM(drug_compatibility) as drug_compatibility,
        SUM(antibiotic_program) as antibiotic_program,
        SUM(high_risk_drugs) as high_risk_drugs,
        SUM(strict_priority) as strict_priority,
        SUM(error_documentation) as error_documentation,
        SUM(drug_definition) as drug_definition
    FROM patient_medication_tracking pmt 
    WHERE $pmt_date_condition $pmt_unit_condition
");
$total_interventions_stmt->bindParam(':pmt_from_date', $dashboard_from_date);
$total_interventions_stmt->bindParam(':pmt_to_date', $dashboard_to_date);
if ($dashboard_unit) {
    $total_interventions_stmt->bindParam(':pmt_unit_id', $dashboard_unit, PDO::PARAM_INT);
}
$total_interventions_stmt->execute();
$interventions = $total_interventions_stmt->fetch(PDO::FETCH_ASSOC);
$total_interventions = (
    ($interventions['drug_compatibility'] ?? 0) +
    ($interventions['antibiotic_program'] ?? 0) +
    ($interventions['high_risk_drugs'] ?? 0) +
    ($interventions['strict_priority'] ?? 0) +
    ($interventions['error_documentation'] ?? 0) +
    ($interventions['drug_definition'] ?? 0)
);

// --- CHARTS DATA ---
// Get status distribution for chart
$status_dist_stmt = $pdo->prepare("SELECT ar.status, COUNT(*) as count FROM antibiotic_reports ar WHERE $ar_date_condition $ar_unit_condition GROUP BY ar.status");
$status_dist_stmt->bindParam(':ar_from_date', $dashboard_from_date);
$status_dist_stmt->bindParam(':ar_to_date', $dashboard_to_date);
if ($dashboard_unit) {
    $status_dist_stmt->bindParam(':ar_unit_id', $dashboard_unit, PDO::PARAM_INT);
}
$status_dist_stmt->execute();
$status_distribution = $status_dist_stmt->fetchAll(PDO::FETCH_ASSOC);

// Debug: Log all statuses found
error_log("Status distribution found: " . print_r($status_distribution, true));

$status_labels = [];
$status_counts = [];
$pending_reports = 0;
$completed_reports = 0;

foreach ($status_distribution as $row) {
    // Handle both English and Arabic status values, and any other values
    $status_label = $row['status'];
    $status_lower = strtolower(trim($row['status']));
    
    if ($status_lower == 'pending' || $status_lower == 'معلق') {
        $status_label = 'معلق';
        $pending_reports = $row['count'];
    } elseif ($status_lower == 'completed' || $status_lower == 'مكتمل') {
        $status_label = 'مكتمل';
        $completed_reports = $row['count'];
    } elseif ($status_lower == 'cancelled' || $status_lower == 'ملغي') {
        $status_label = 'ملغي';
    }
    // For any other status, just use the original value
    
    $status_labels[] = $status_label;
    $status_counts[] = $row['count'];
}

// In case the status loop didn't find pending/completed, recalculate them separately
if ($pending_reports == 0) {
    $pending_reports_stmt = $pdo->prepare("SELECT COUNT(*) as count FROM antibiotic_reports ar WHERE $ar_date_condition AND (LOWER(ar.status) = 'pending' OR LOWER(ar.status) = 'معلق') $ar_unit_condition");
    $pending_reports_stmt->bindParam(':ar_from_date', $dashboard_from_date);
    $pending_reports_stmt->bindParam(':ar_to_date', $dashboard_to_date);
    if ($dashboard_unit) {
        $pending_reports_stmt->bindParam(':ar_unit_id', $dashboard_unit, PDO::PARAM_INT);
    }
    $pending_reports_stmt->execute();
    $pending_reports = $pending_reports_stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
}

if ($completed_reports == 0) {
    $completed_reports_stmt = $pdo->prepare("SELECT COUNT(*) as count FROM antibiotic_reports ar WHERE $ar_date_condition AND (LOWER(ar.status) = 'completed' OR LOWER(ar.status) = 'مكتمل') $ar_unit_condition");
    $completed_reports_stmt->bindParam(':ar_from_date', $dashboard_from_date);
    $completed_reports_stmt->bindParam(':ar_to_date', $dashboard_to_date);
    if ($dashboard_unit) {
        $completed_reports_stmt->bindParam(':ar_unit_id', $dashboard_unit, PDO::PARAM_INT);
    }
    $completed_reports_stmt->execute();
    $completed_reports = $completed_reports_stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
}

// Get reports per unit
$reports_per_unit_stmt = $pdo->prepare("SELECT u.unit_name, COUNT(*) as count FROM antibiotic_reports ar JOIN units u ON ar.unit_id = u.id WHERE $ar_date_condition $ar_unit_condition GROUP BY u.id, u.unit_name ORDER BY count DESC LIMIT 10");
$reports_per_unit_stmt->bindParam(':ar_from_date', $dashboard_from_date);
$reports_per_unit_stmt->bindParam(':ar_to_date', $dashboard_to_date);
if ($dashboard_unit) {
    $reports_per_unit_stmt->bindParam(':ar_unit_id', $dashboard_unit, PDO::PARAM_INT);
}
$reports_per_unit_stmt->execute();
$reports_per_unit = $reports_per_unit_stmt->fetchAll(PDO::FETCH_ASSOC);
$unit_labels = [];
$unit_counts = [];
foreach ($reports_per_unit as $row) {
    $unit_labels[] = $row['unit_name'];
    $unit_counts[] = $row['count'];
}

// Get reports over time (last 7 days/months)
$reports_over_time_stmt = $pdo->prepare("SELECT DATE(ar.report_date) as date, COUNT(*) as count FROM antibiotic_reports ar WHERE $ar_date_condition $ar_unit_condition GROUP BY DATE(ar.report_date) ORDER BY date");
$reports_over_time_stmt->bindParam(':ar_from_date', $dashboard_from_date);
$reports_over_time_stmt->bindParam(':ar_to_date', $dashboard_to_date);
if ($dashboard_unit) {
    $reports_over_time_stmt->bindParam(':ar_unit_id', $dashboard_unit, PDO::PARAM_INT);
}
$reports_over_time_stmt->execute();
$reports_over_time = $reports_over_time_stmt->fetchAll(PDO::FETCH_ASSOC);
$time_labels = [];
$time_counts = [];
foreach ($reports_over_time as $row) {
    $time_labels[] = date('d/m', strtotime($row['date']));
    $time_counts[] = $row['count'];
}

// Get interventions distribution for chart
$interv_labels = ['توافق الأدوية', 'ترشيد المضادات', 'أدوية عالية الخطورة', 'أدوية متشابهة', 'توثيق الأخطاء', 'تعريف الأدوية'];
$interv_counts = [
    $interventions['drug_compatibility'] ?? 0,
    $interventions['antibiotic_program'] ?? 0,
    $interventions['high_risk_drugs'] ?? 0,
    $interventions['strict_priority'] ?? 0,
    $interventions['error_documentation'] ?? 0,
    $interventions['drug_definition'] ?? 0
];

// معالجة حفظ البيانات
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_data'])) {
    try {
        // إدراج البيانات الجديدة
        $data = json_decode($_POST['table_data'], true);
        $unit_id = $_POST['selected_unit'] ?? null;
        
        error_log("Attempting to save data: unit_id=$unit_id, data_count=" . count($data));
        
        if ($unit_id && !empty($data)) {
            $selected_date = $_POST['selected_date'] ?? date('Y-m-d');
            
            // حذف البيانات القديمة لنفس التاريخ والقسم
            $stmt = $pdo->prepare("DELETE FROM patient_medication_tracking WHERE tracking_date = ? AND unit_id = ?");
            $delete_result = $stmt->execute([$selected_date, $unit_id]);
            error_log("Deleted old records: " . ($delete_result ? 'success' : 'failed'));
            
            $stmt = $pdo->prepare("INSERT INTO patient_medication_tracking 
                (tracking_date, unit_id, patient_name, medical_number, drug_compatibility, 
                 antibiotic_program, high_risk_drugs, strict_priority, error_documentation, 
                 drug_definition, medication_description, pharmacist_name, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            $inserted_count = 0;
            foreach ($data as $index => $row) {
                $result = $stmt->execute([
                    $selected_date,
                    $unit_id,
                    $row['patient_name'] ?? '',
                    $row['medical_number'] ?? '',
                    $row['drug_compatibility'] ?? 0,
                    $row['antibiotic_program'] ?? 0,
                    $row['high_risk_drugs'] ?? 0,
                    $row['strict_priority'] ?? 0,
                    $row['error_documentation'] ?? 0,
                    $row['drug_definition'] ?? 0,
                    $row['medication_description'] ?? '',
                    $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'غير محدد',
                    $_SESSION['user_id']
                ]);
                
                if ($result) {
                    $inserted_count++;
                    error_log("Inserted row $index successfully");
                } else {
                    error_log("Failed to insert row $index");
                }
            }
            
            if ($inserted_count > 0) {
                $success_message = "تم حفظ {$inserted_count} سجل بنجاح";
                error_log("Save operation completed: $inserted_count records saved");
            } else {
                $error_message = "لم يتم حفظ أي سجل";
                error_log("Save operation failed: no records saved");
            }
        } else {
            $error_message = "يرجى اختيار قسم وإدخال بيانات صحيحة";
            error_log("Save operation failed: missing unit_id or empty data");
        }
        
    } catch (Exception $e) {
        $error_message = "خطأ في حفظ البيانات: " . $e->getMessage();
        error_log("Save operation exception: " . $e->getMessage());
    }
}

// جلب البيانات المحفوظة للقسم المحدد والتاريخ
$saved_data = [];
if (isset($_GET['unit_id']) && !empty($_GET['unit_id'])) {
    try {
        $selected_date = $_GET['date'] ?? date('Y-m-d');
        $unit_id = $_GET['unit_id'];
        
        // التحقق من وجود الجدول أولاً
        $check_table = $pdo->query("SHOW TABLES LIKE 'patient_medication_tracking'");
        if ($check_table->rowCount() > 0) {
            $stmt = $pdo->prepare("
                SELECT p.*, u.unit_name 
                FROM patient_medication_tracking p 
                LEFT JOIN units u ON p.unit_id = u.id 
                WHERE p.unit_id = ? AND p.tracking_date = ? 
                ORDER BY p.id
            ");
            $stmt->execute([$unit_id, $selected_date]);
            $saved_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // تسجيل للتتبع
            error_log("Loading data for unit_id: $unit_id, date: $selected_date, found: " . count($saved_data) . " records");
            
            // إضافة معلومات إضافية للتتبع
            if (count($saved_data) > 0) {
                error_log("Sample record: " . json_encode($saved_data[0]));
            }
        }
    } catch (Exception $e) {
        error_log("Error loading saved data: " . $e->getMessage());
        $saved_data = [];
    }
}

include 'includes/header.php';
?>

<link rel="stylesheet" href="assets/css/medical-table.css">

<!-- Main Content -->

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <div>
            <h1 class="h2 mb-0 text-gradient">
                <i class="fas fa-chart-line text-primary me-2"></i>
                لوحة التحكم الرئيسية
            </h1>
            <p class="text-muted mb-0">
                <i class="fas fa-calendar-alt me-1"></i>
                <?php echo __('today_date'); ?>: <?php echo date('d/m/Y'); ?>
                <span class="mx-2">|</span>
                <i class="fas fa-user me-1"></i>
                <?php echo __('user'); ?>: <?php echo $_SESSION['username'] ?? 'غير محدد'; ?>
            </p>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-success fw-semibold" onclick="exportDashboardToExcel()">
                <i class="fas fa-file-excel me-2"></i>
                تصدير Excel
            </button>
        </div>
    </div>

    <!-- Dashboard Filters -->
    <div class="card mb-4 shadow-sm border-0">
        <div class="card-header bg-gradient-primary text-white py-3">
            <h5 class="mb-0">
                <i class="fas fa-sliders-h me-2"></i>
                فلاتر البيانات
            </h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row g-3 align-items-end">
                <input type="hidden" name="unit_id" value="<?php echo $_GET['unit_id'] ?? ''; ?>">
                <input type="hidden" name="date" value="<?php echo $_GET['date'] ?? ''; ?>">
                <div class="col-md-3">
                    <label for="dashboard_from" class="form-label fw-semibold">من تاريخ</label>
                    <input type="date" class="form-control" id="dashboard_from" name="dashboard_from" value="<?php echo htmlspecialchars($dashboard_from_date); ?>">
                </div>
                <div class="col-md-3">
                    <label for="dashboard_to" class="form-label fw-semibold">إلى تاريخ</label>
                    <input type="date" class="form-control" id="dashboard_to" name="dashboard_to" value="<?php echo htmlspecialchars($dashboard_to_date); ?>">
                </div>
                <div class="col-md-3">
                    <label for="dashboard_unit" class="form-label fw-semibold"><?php echo __('unit'); ?></label>
                    <select class="form-select" id="dashboard_unit" name="dashboard_unit">
                        <option value="">كل الأقسام</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?php echo $unit['id']; ?>" <?php echo $dashboard_unit == $unit['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($unit['unit_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-gradient-primary w-100 fw-semibold py-2">
                        <i class="fas fa-filter me-2"></i>
                        تطبيق الفلاتر
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Dashboard Cards -->
    <div class="row mb-4">
        <!-- Total Reports -->
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card stat-card stat-purple shadow-lg border-0 h-100 overflow-hidden">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="text-white mb-0 fw-semibold text-uppercase">إجمالي التقارير</h6>
                        <i class="fas fa-file-medical-alt fa-2x opacity-75"></i>
                    </div>
                    <h2 class="text-white fw-bold mb-0 counter"><?php echo $total_reports; ?></h2>
                    <div class="mt-2 pt-2 border-top border-white border-opacity-25">
                        <p class="text-white opacity-75 mb-0 small">تقارير الصيدلة</p>
                    </div>
                </div>
            </div>
        </div>
        <!-- Pending Reports -->
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card stat-card stat-orange shadow-lg border-0 h-100 overflow-hidden">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="text-white mb-0 fw-semibold text-uppercase">تقارير معلقة</h6>
                        <i class="fas fa-clock fa-2x opacity-75"></i>
                    </div>
                    <h2 class="text-white fw-bold mb-0 counter"><?php echo $pending_reports; ?></h2>
                    <div class="mt-2 pt-2 border-top border-white border-opacity-25">
                        <p class="text-white opacity-75 mb-0 small">في انتظار المراجعة</p>
                    </div>
                </div>
            </div>
        </div>
        <!-- Completed Reports -->
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card stat-card stat-green shadow-lg border-0 h-100 overflow-hidden">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="text-white mb-0 fw-semibold text-uppercase">تقارير مكتملة</h6>
                        <i class="fas fa-check-circle fa-2x opacity-75"></i>
                    </div>
                    <h2 class="text-white fw-bold mb-0 counter"><?php echo $completed_reports; ?></h2>
                    <div class="mt-2 pt-2 border-top border-white border-opacity-25">
                        <p class="text-white opacity-75 mb-0 small">تم تنفيذها بنجاح</p>
                    </div>
                </div>
            </div>
        </div>
        <!-- Total Patients -->
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card stat-card stat-blue shadow-lg border-0 h-100 overflow-hidden">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="text-white mb-0 fw-semibold text-uppercase">إجمالي المرضى</h6>
                        <i class="fas fa-users fa-2x opacity-75"></i>
                    </div>
                    <h2 class="text-white fw-bold mb-0 counter"><?php echo $total_patients; ?></h2>
                    <div class="mt-2 pt-2 border-top border-white border-opacity-25">
                        <p class="text-white opacity-75 mb-0 small">تمت متابعتهم</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- More Stats Cards (Interventions) -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card stat-card stat-teal shadow-lg border-0 h-100 overflow-hidden">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="text-white mb-0 fw-semibold text-uppercase">إجمالي التدخلات</h6>
                        <i class="fas fa-heartbeat fa-2x opacity-75"></i>
                    </div>
                    <h2 class="text-white fw-bold mb-0 counter"><?php echo $total_interventions; ?></h2>
                    <div class="mt-2 pt-2 border-top border-white border-opacity-25">
                        <p class="text-white opacity-75 mb-0 small">عملية تدخل صيدلي</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Dashboard Charts -->
    <div class="row mb-5">
        <!-- Status Distribution -->
        <div class="col-lg-6 mb-4">
            <div class="card dashboard-card shadow-lg border-0 h-100">
                <div class="card-header bg-gradient-primary text-white py-3">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-pie me-2"></i>
                        توزيع حالات التقارير
                    </h5>
                </div>
                <div class="card-body p-4">
                    <div class="chart-container" style="height: 400px;">
                        <canvas id="statusChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <!-- Reports Per Unit -->
        <div class="col-lg-6 mb-4">
            <div class="card dashboard-card shadow-lg border-0 h-100">
                <div class="card-header bg-gradient-green text-white py-3">
                    <h5 class="mb-0">
                        <i class="fas fa-hospital me-2"></i>
                        التقارير حسب الأقسام
                    </h5>
                </div>
                <div class="card-body p-4">
                    <div class="chart-container" style="height: 400px;">
                        <canvas id="unitChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-5">
        <!-- Reports Over Time -->
        <div class="col-lg-6 mb-4">
            <div class="card dashboard-card shadow-lg border-0 h-100">
                <div class="card-header bg-gradient-orange text-white py-3">
                    <h5 class="mb-0">
                        <i class="fas fa-calendar-check me-2"></i>
                        التقارير مع مرور الوقت
                    </h5>
                </div>
                <div class="card-body p-4">
                    <div class="chart-container" style="height: 400px;">
                        <canvas id="timeChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <!-- Interventions Distribution -->
        <div class="col-lg-6 mb-4">
            <div class="card dashboard-card shadow-lg border-0 h-100">
                <div class="card-header bg-gradient-teal text-white py-3">
                    <h5 class="mb-0">
                        <i class="fas fa-procedures me-2"></i>
                        توزيع التدخلات الصيدلية
                    </h5>
                </div>
                <div class="card-body p-4">
                    <div class="chart-container" style="height: 400px;">
                        <canvas id="intervChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <hr class="my-5">

    <!-- KPI Table Section -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="h4 mb-0">
                <i class="fas fa-table text-primary me-2"></i>
                <?php echo __('medical_event_report'); ?>
            </h2>
        </div>
    </div>

    <!-- رسائل النجاح والخطأ -->
    <?php if (isset($success_message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo $success_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <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">
            <h5 class="card-title">
                <i class="fas fa-filter me-2"></i>
                <?php echo __('search_filters'); ?>
            </h5>
            <div class="row">
                <div class="col-md-3">
                    <label for="unitSelect" class="form-label"><?php echo __('unit'); ?>:</label>
                    <select class="form-select" id="unitSelect" onchange="loadUnitData()">
                        <option value=""><?php echo __('select_unit'); ?>...</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?php echo $unit['id']; ?>" 
                                <?php echo (isset($_GET['unit_id']) && $_GET['unit_id'] == $unit['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($unit['unit_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="dateFilter" class="form-label"><?php echo __('date'); ?>:</label>
                    <input type="date" class="form-control" id="dateFilter" 
                           value="<?php echo $_GET['date'] ?? date('Y-m-d'); ?>" 
                           onchange="loadUnitData()">
                </div>
                <div class="col-md-3">
                    <label for="pharmacistFilter" class="form-label"><?php echo __('pharmacist'); ?>:</label>
                    <select class="form-select" id="pharmacistFilter" onchange="filterByPharmacist()">
                        <option value=""><?php echo __('all_pharmacists'); ?></option>
                        <option value="<?php echo $_SESSION['full_name'] ?? $_SESSION['username']; ?>" selected>
                            <?php echo $_SESSION['full_name'] ?? $_SESSION['username']; ?>
                        </option>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <?php if (PagePermissions::hasPermission($currentPage, 'view_kpi')): ?>
                    <button class="btn btn-primary me-2" onclick="loadUnitData()">
                        <i class="fas fa-sync me-1"></i><?php echo __('load'); ?>
                    </button>
                    <button class="btn btn-success me-2" onclick="addNewRow()" id="addPatientBtn" disabled>
                        <i class="fas fa-plus me-1"></i><?php echo __('add'); ?>
                    </button>
                    <button class="btn btn-warning me-2" onclick="saveData()" id="saveBtn" disabled>
                        <i class="fas fa-save me-1"></i><?php echo __('save'); ?>
                    </button>
                    <button class="btn btn-info me-2" onclick="printTable()" id="printBtn" disabled>
                        <i class="fas fa-print me-1"></i><?php echo __('print'); ?>
                    </button>
                    <?php endif; ?>
                    <?php if (PagePermissions::hasPermission($currentPage, 'export_kpi')): ?>
                    <button class="btn btn-success" onclick="exportToExcel()" id="exportBtn" disabled>
                        <i class="fas fa-file-excel me-1"></i><?php echo __('export_excel'); ?>
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- تعليمات الاستخدام المحسنة -->
    <div class="alert alert-info no-print" id="instructionsAlert" style="display: none;">
        <div class="row">
            <div class="col-md-12">
                <h6><i class="fas fa-info-circle me-2"></i>تعليمات الاستخدام:</h6>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <h6 class="text-primary"><i class="fas fa-mouse-pointer me-1"></i>التحرير والتنقل:</h6>
                <ul class="mb-0" style="font-size: 14px;">
                    <li><strong>انقر على أي خلية</strong> لتحريرها مثل Excel</li>
                    <li><strong>Enter</strong> للانتقال للصف التالي</li>
                    <li><strong>Tab</strong> للانتقال للخلية التالية</li>
                    <li><strong>Shift + Tab</strong> للانتقال للخلية السابقة</li>
                    <li><strong>الأسهم</strong> للتنقل بين الخلايا</li>
                    <li><strong>Escape</strong> لإلغاء التحرير</li>
                </ul>
            </div>
            <div class="col-md-4">
                <h6 class="text-success"><i class="fas fa-cogs me-1"></i>العمليات الأساسية:</h6>
                <ul class="mb-0" style="font-size: 14px;">
                    <li><strong>اختر القسم أولاً</strong> لبدء العمل</li>
                    <li><strong>اختر التاريخ</strong> لعرض بيانات يوم معين</li>
                    <li><strong>اضغط "تحميل"</strong> لجلب البيانات المحفوظة</li>
                    <li><strong>اضغط "إضافة"</strong> لإضافة مريض جديد</li>
                    <li><strong>اضغط "حفظ"</strong> لحفظ التغييرات</li>
                    <li><strong>اضغط "طباعة"</strong> لطباعة الجدول</li>
                </ul>
            </div>
            <div class="col-md-4">
                <h6 class="text-warning"><i class="fas fa-lightbulb me-1"></i>نصائح مفيدة:</h6>
                <ul class="mb-0" style="font-size: 14px;">
                    <li><strong>الأرقام 0 أو 1 فقط</strong> في خانات التدخل</li>
                    <li><strong>البيانات تحفظ تلقائياً</strong> حسب القسم والتاريخ</li>
                    <li><strong>الإحصائيات تتحدث فورياً</strong> مع التغييرات</li>
                    <li><strong>استخدم "بيانات تجريبية"</strong> للاختبار</li>
                    <li><strong>يمكن فلترة البيانات</strong> حسب الصيدلي</li>
                    <li><strong>الجدول يدعم الطباعة</strong> بتنسيق احترافي</li>
                </ul>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-md-12">
                <div class="alert alert-warning mb-0" style="padding: 10px;">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>مهم:</strong> تأكد من اختيار القسم والتاريخ قبل البدء في إدخال البيانات. 
                    البيانات ستحفظ للقسم والتاريخ المحددين فقط.
                </div>
            </div>
        </div>
    </div>

    <!-- Medical Table -->
    <div class="medical-table-wrapper" id="tableWrapper" style="display: none;">
        <div class="medical-table-container">
            <div class="table-header-section">
                <div class="table-main-title">
                    <?php echo __('medication_intervention_procedures'); ?>
                </div>
                <div class="table-subtitle">
                    <?php echo __('unit'); ?>: <span id="selectedUnitName"><?php echo __('not_specified'); ?></span> - <?php echo __('date'); ?>: <span id="selectedDate"><?php echo $_GET['date'] ?? date('d/m/Y'); ?></span>
                </div>
            </div>
            
            <div class="table-scroll-container">
                <table class="medical-table" id="medicalTable">
                    <thead>
                        <tr>
                            <th rowspan="3" class="header-main date-header">تاريخ الادخال</th>
                            <th rowspan="3" class="header-main">اسم المريض</th>
                            <th rowspan="3" class="header-main">الرقم الطبي</th>
                            <th colspan="6" class="header-main">إجراءات التدخل وإدارة الأخطاء المهنية فيما يتعلق بالأدوية</th>
                            <th rowspan="3" class="header-main">الوصف الصحيح للدواء</th>
                            <th rowspan="3" class="header-main">الإجراءات</th>
                        </tr>
                        <tr>
                            <th colspan="6" class="header-sub"><?php echo __('intervention_categories'); ?></th>
                        </tr>
                        <tr>
                            <th class="header-sub">توافق بين الأدوية</th>
                            <th class="header-sub">برنامج ترشيد استهلاك المضادات الحيوية</th>
                            <th class="header-sub">الأدوية عالية الخطورة</th>
                            <th class="header-sub">الأدوية المتشابهة في النطق</th>
                            <th class="header-sub">توثيق الأخطاء الدوائية</th>
                            <th class="header-sub">تعريف الأدوية</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- البيانات ستظهر هنا -->
                    </tbody>
                    <tfoot>
                        <tr class="statistics-header">
                            <td colspan="11"><strong><?php echo __('statistics_summary'); ?></strong></td>
                        </tr>
                        <tr class="statistics-row">
                            <td><strong><?php echo __('total_patients'); ?></strong></td>
                            <td><strong><?php echo __('total_interventions'); ?></strong></td>
                            <td><strong><?php echo __('completed_reports'); ?></strong></td>
                            <td><strong><?php echo __('pending_reports'); ?></strong></td>
                            <td colspan="7"><strong><?php echo __('grand_total'); ?></strong></td>
                        </tr>
                        <tr class="statistics-values">
                            <td id="footerTotalPatients">0</td>
                            <td id="footerTotalInterventions">0</td>
                            <td id="footerCompletedReports">0</td>
                            <td id="footerPendingReports">0</td>
                            <td colspan="7" id="footerOverallTotal">0</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            
            <!-- إحصائيات محسنة -->
            <div class="statistics-section mt-3">
                <div class="row">
                    <div class="col-md-3">
                        <div class="stat-card stat-purple">
                            <h6><?php echo __('total_patients'); ?></h6>
                            <span id="cardTotalPatients">0</span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card stat-green">
                            <h6><?php echo __('total_interventions'); ?></h6>
                            <span id="cardTotalInterventions">0</span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card stat-orange">
                            <h6><?php echo __('completed_reports'); ?></h6>
                            <span id="cardCompletedReports">0</span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card stat-red">
                            <h6><?php echo __('pending_reports'); ?></h6>
                            <span id="cardPendingReports">0</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Export Modal -->
    <div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exportModalLabel">
                        <i class="fas fa-file-excel me-2"></i>
                        <?php echo __('export_excel'); ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="exportForm">
                        <div class="row">
                            <div class="col-md-6">
                                <label for="exportFromDate" class="form-label"><?php echo __('from_date'); ?>:</label>
                                <input type="date" class="form-control" id="exportFromDate" required>
                            </div>
                            <div class="col-md-6">
                                <label for="exportToDate" class="form-label"><?php echo __('to_date'); ?>:</label>
                                <input type="date" class="form-control" id="exportToDate" required>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label for="exportUnit" class="form-label"><?php echo __('unit'); ?>:</label>
                                <select class="form-select" id="exportUnit">
                                    <option value=""><?php echo __('all_units'); ?></option>
                                    <?php foreach ($units as $unit): ?>
                                        <option value="<?php echo $unit['id']; ?>">
                                            <?php echo htmlspecialchars($unit['unit_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="exportPharmacist" class="form-label"><?php echo __('pharmacist'); ?>:</label>
                                <select class="form-select" id="exportPharmacist">
                                    <option value=""><?php echo __('all_pharmacists'); ?></option>
                                    <option value="<?php echo $_SESSION['full_name'] ?? $_SESSION['username']; ?>">
                                        <?php echo $_SESSION['full_name'] ?? $_SESSION['username']; ?>
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="includeStatistics" checked>
                                    <label class="form-check-label" for="includeStatistics">
                                        <?php echo __('include_statistics'); ?>
                                    </label>
                                </div>
                                <div class="form-check mt-2">
                                    <input class="form-check-input" type="checkbox" id="includeReports">
                                    <label class="form-check-label" for="includeReports">
                                        <i class="fas fa-pills me-1"></i>تضمين تقارير المضادات الحيوية
                                    </label>
                                    <small class="form-text text-muted d-block">سيتم تصدير تقرير موحد يشمل جدول المتابعة وتقارير المضادات الحيوية</small>
                                </div>
                            </div>
                        </div>
                    </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 __('cancel'); ?>
                    </button>
                    <button type="button" class="btn btn-success" onclick="performExport()">
                        <i class="fas fa-download me-1"></i><?php echo __('export'); ?>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Gradient Text & Buttons */
.text-gradient {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-weight: 700;
}

.btn-gradient-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
}

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

.bg-gradient-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.bg-gradient-green { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
.bg-gradient-orange { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.bg-gradient-teal { background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); }

/* تنسيق متناسق مع الموقع */
.card {
    border: none;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    margin-bottom: 20px;
}

.card-header {
    border-radius: 16px 16px 0 0 !important;
    border: none;
}

.btn {
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn:hover {
    transform: translateY(-2px);
}

/* Stat Cards */
.stat-card {
    color: white;
    border-radius: 16px;
    transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.stat-card:hover::before {
    opacity: 1;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

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

.stat-card h6 {
    margin-bottom: 10px;
    font-size: 14px;
    opacity: 0.9;
}

.stat-card h2 {
    font-size: 3rem;
}

/* Dashboard Chart Cards */
.dashboard-card {
    border: none;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

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

.dashboard-card .card-header {
    padding: 16px 24px;
}

.chart-container {
    width: 100%;
    position: relative;
    height: 400px !important;
    display: block;
}

canvas {
    width: 100% !important;
    height: 100% !important;
}

/* Counter Animation */
@keyframes countUp {
    from { opacity: 0; transform: scale(0.8); }
    to { opacity: 1; transform: scale(1); }
}
.counter {
    animation: countUp 0.8s ease-out;
}

/* Responsive Fixes */
@media (max-width: 768px) {
    .stat-card h2 {
        font-size: 2rem;
    }
    .chart-container {
        height: 250px !important;
    }
}

.medical-table-wrapper {
    background: white;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-top: 20px;
}

.table-header-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    text-align: center;
}

.table-main-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
}

.table-subtitle {
    font-size: 14px;
    opacity: 0.9;
}

.medical-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 11px;
    min-width: 1200px;
}

.medical-table th {
    background: #f8f9fa;
    padding: 8px 4px;
    text-align: center;
    border: 2px solid #000;
    font-weight: bold;
    font-size: 10px;
}

.medical-table .header-main {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-weight: bold;
}

.medical-table .header-sub {
    background: #e9ecef;
    color: #495057;
    font-size: 9px;
}

.medical-table .date-header {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
}

.medical-table td {
    padding: 6px 4px;
    border: 1px solid #000;
    text-align: center;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 10px;
    min-width: 80px;
}

.medical-table td:hover {
    background-color: #f8f9fa;
}

.medical-table td.editing {
    background-color: #fff3cd;
    transform: scale(1.02);
    box-shadow: 0 0 10px rgba(0, 123, 255, 0.5);
    border: 2px solid #007bff;
    z-index: 10;
    position: relative;
}

.medical-table td.active-cell {
    background-color: #e3f2fd;
    border: 1px solid #2196f3;
}

.statistics-header td {
    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
    color: white;
    font-weight: bold;
    cursor: default !important;
}

.statistics-row td {
    background: #e9ecef;
    font-weight: bold;
    cursor: default !important;
}

.statistics-values td {
    background: #f8f9fa;
    font-weight: bold;
    color: #007bff;
    cursor: default !important;
}

.table-scroll-container {
    overflow-x: auto;
    max-width: 100%;
    border: 2px solid #000;
}

.cell-input {
    width: 100%;
    border: none;
    background: transparent;
    text-align: center;
    font-size: 10px;
    padding: 4px;
    outline: none;
}

.cell-input:focus {
    outline: 2px solid #007bff;
    border-radius: 3px;
    background: white;
}

.btn-delete {
    background: #dc3545;
    color: white;
    border: none;
    padding: 4px 8px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 11px;
    transition: all 0.3s ease;
}

.btn-delete:hover {
    background: #c82333;
    transform: scale(1.05);
}

.alert {
    border-radius: 10px;
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-control, .form-select {
    border-radius: 8px;
    border: 1px solid #dee2e6;
    transition: all 0.3s ease;
}

.form-control:focus, .form-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.modal-content {
    border-radius: 15px;
    border: none;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}

.modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px 15px 0 0;
    border: none;
}

.modal-footer {
    border: none;
    border-radius: 0 0 15px 15px;
}

.form-check-input:checked {
    background-color: #667eea;
    border-color: #667eea;
}

@media print {
    .main-content { margin-right: 0; }
    .medical-table { font-size: 10px; }
    .medical-table th, .medical-table td { padding: 4px; }
    .btn, .card, .alert, .modal { display: none !important; }
}
</style>

<script>
// متغيرات عامة
let currentEditingCell = null;
let selectedUnitId = null;
let selectedUnitName = '';
let tableData = [];
let isDataChanged = false;

// إعداد الصفحة عند التحميل
document.addEventListener('DOMContentLoaded', function() {
    console.log('تم تحميل صفحة جدول المرضى والأدوية');
    
    // إذا كان هناك قسم محدد في URL، حمل البيانات
    const urlParams = new URLSearchParams(window.location.search);
    const unitId = urlParams.get('unit_id');
    if (unitId) {
        selectedUnitId = unitId;
        const unitSelect = document.getElementById('unitSelect');
        unitSelect.value = unitId;
        selectedUnitName = unitSelect.options[unitSelect.selectedIndex].text;
        loadSavedData();
        enableButtons();
        showTable();
    }
    
    setTimeout(hideAlerts, 5000);
});

// تحميل بيانات القسم
function loadUnitData() {
    const unitSelect = document.getElementById('unitSelect');
    const dateFilter = document.getElementById('dateFilter');
    const unitId = unitSelect.value;
    const selectedDate = dateFilter.value;
    
    if (!unitId) {
        showNotification('<?php echo __("please_select_unit_first"); ?>', 'warning');
        return;
    }
    
    selectedUnitId = unitId;
    selectedUnitName = unitSelect.options[unitSelect.selectedIndex].text;
    
    // إعادة توجيه لتحميل البيانات مع التاريخ
    window.location.href = `key_performance_indicators.php?unit_id=${unitId}&date=${selectedDate}`;
}

// فلترة حسب الصيدلي
function filterByPharmacist() {
    const pharmacistFilter = document.getElementById('pharmacistFilter');
    const selectedPharmacist = pharmacistFilter.value;
    const rows = document.querySelectorAll('#tableBody tr');
    
    rows.forEach(row => {
        if (selectedPharmacist === '') {
            row.style.display = '';
        } else {
            const pharmacistName = row.getAttribute('data-pharmacist') || '';
            if (pharmacistName.includes(selectedPharmacist)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        }
    });
    
    updateStatistics();
}

// تحميل البيانات المحفوظة
function loadSavedData() {
    const savedData = <?php echo json_encode($saved_data); ?>;
    const tableBody = document.getElementById('tableBody');
    
    console.log('Loading saved data:', savedData);
    
    // مسح الجدول
    tableBody.innerHTML = '';
    
    if (savedData && savedData.length > 0) {
        savedData.forEach((row, index) => {
            console.log('Loading row', index, ':', row);
            addRowWithData({
                id: row.id,
                record_date: row.tracking_date || document.getElementById('dateFilter').value,
                patient_name: row.patient_name || '',
                medical_number: row.medical_number || '',
                medication: row.medication_description || '',
                pharmacist: row.pharmacist_name || 'غير محدد',
                values: [
                    row.drug_compatibility || 0,
                    row.antibiotic_program || 0,
                    row.high_risk_drugs || 0,
                    row.strict_priority || 0,
                    row.error_documentation || 0,
                    row.drug_definition || 0
                ]
            });
        });
        showNotification(`تم تحميل ${savedData.length} سجل محفوظ للقسم: ${selectedUnitName}`, 'success');
    } else {
        // إضافة صف فارغ للبداية
        addNewRow();
        showNotification('لا توجد بيانات محفوظة لهذا القسم والتاريخ - تم إضافة صف جديد', 'info');
    }
    
    updateStatistics();
}

// إظهار الجدول
function showTable() {
    document.getElementById('tableWrapper').style.display = 'block';
    document.getElementById('selectedUnitName').textContent = selectedUnitName;
}

// تفعيل الأزرار
function enableButtons() {
    document.getElementById('addPatientBtn').disabled = false;
    document.getElementById('saveBtn').disabled = false;
    document.getElementById('printBtn').disabled = false;
    document.getElementById('exportBtn').disabled = false;
}

// إضافة صف جديد
function addNewRow() {
    if (!selectedUnitId) {
        showNotification('<?php echo __("please_select_unit_first"); ?>', 'warning');
        return;
    }
    
    const tableBody = document.getElementById('tableBody');
    const newRow = document.createElement('tr');
    newRow.setAttribute('data-pharmacist', getCurrentPharmacist());
    
    newRow.innerHTML = `
        <td class="date-cell" onclick="makeEditable(this, 'date')">${document.getElementById('dateFilter').value || new Date().toLocaleDateString('en-CA')}</td>
        <td class="editable-cell" onclick="makeEditable(this)"></td>
        <td class="editable-cell" onclick="makeEditable(this)"></td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">0</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">0</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">0</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">0</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">0</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">0</td>
        <td class="editable-cell" onclick="makeEditable(this)"></td>
        <td><button class="btn-delete" onclick="deleteRow(this)">حذف</button></td>
    `;
    
    tableBody.appendChild(newRow);
    updateStatistics();
    isDataChanged = true;
    
    // تأثير بصري
    newRow.style.opacity = '0';
    newRow.style.transform = 'translateY(-20px)';
    setTimeout(() => {
        newRow.style.transition = 'all 0.5s ease';
        newRow.style.opacity = '1';
        newRow.style.transform = 'translateY(0)';
    }, 100);
    
    showNotification('تم إضافة مريض جديد - انقر على أي خلية للتحرير', 'success');
}

// الحصول على اسم الصيدلي الحالي
function getCurrentPharmacist() {
    return '<?php echo $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'غير محدد'; ?>';
}

// إضافة صف مع بيانات
function addRowWithData(data) {
    const tableBody = document.getElementById('tableBody');
    const newRow = document.createElement('tr');
    newRow.setAttribute('data-pharmacist', data.pharmacist || 'غير محدد');
    if (data.id) {
        newRow.setAttribute('data-id', data.id);
    }
    
    newRow.innerHTML = `
        <td class="date-cell" onclick="makeEditable(this, 'date')">${data.record_date || new Date().toLocaleDateString('en-CA')}</td>
        <td class="editable-cell" onclick="makeEditable(this)">${data.patient_name}</td>
        <td class="editable-cell" onclick="makeEditable(this)">${data.medical_number}</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">${data.values[0]}</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">${data.values[1]}</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">${data.values[2]}</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">${data.values[3]}</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">${data.values[4]}</td>
        <td class="number-cell" onclick="makeEditable(this, 'number')">${data.values[5]}</td>
        <td class="editable-cell" onclick="makeEditable(this)">${data.medication}</td>
        <td><button class="btn-delete" onclick="deleteRow(this)">حذف</button></td>
    `;
    
    tableBody.appendChild(newRow);
}

// حذف صف
function deleteRow(button) {
    if (confirm('<?php echo __("confirm_delete_patient"); ?>')) {
        const row = button.closest('tr');
        const recordId = row.getAttribute('data-id');
        
        row.style.transition = 'all 0.3s ease';
        row.style.opacity = '0';
        row.style.transform = 'translateX(-100%)';
        setTimeout(() => {
            row.remove();
            updateStatistics();
            
            // إذا كان السجل يحتوي على ID (محفوظ في قاعدة البيانات)
            if (recordId) {
                window.location.href = `delete.php?type=kpi&id=${recordId}`;
            } else {
                isDataChanged = true;
                showNotification('<?php echo __("patient_deleted"); ?>', 'success');
            }
        }, 300);
    }
}

// جعل الخلية قابلة للتحرير
function makeEditable(cell, type = 'text', options = null) {
    if (currentEditingCell && currentEditingCell !== cell) {
        finishEditing();
    }
    
    if (cell.classList.contains('editing')) {
        return;
    }
    
    currentEditingCell = cell;
    const originalValue = cell.textContent.trim();
    
    cell.classList.add('editing');
    
    let input;
    
    if (type === 'select' && options) {
        input = document.createElement('select');
        input.className = 'cell-input';
        options.forEach(option => {
            const optionElement = document.createElement('option');
            optionElement.value = option;
            optionElement.textContent = option;
            if (option === originalValue) {
                optionElement.selected = true;
            }
            input.appendChild(optionElement);
        });
    } else {
        input = document.createElement('input');
        input.className = 'cell-input';
        input.type = type;
        input.value = originalValue;
        
        if (type === 'number') {
            input.min = '0';
            input.max = '1';
            input.step = '1';
        } else if (type === 'date') {
            input.value = originalValue || new Date().toLocaleDateString('en-CA');
        }
    }
    
    cell.innerHTML = '';
    cell.appendChild(input);
    
    input.focus();
    if (input.select) input.select();
    
    input.addEventListener('blur', function() {
        finishEditing();
    });
    
    input.addEventListener('keydown', function(e) {
        switch(e.key) {
            case 'Enter':
                e.preventDefault();
                finishEditing();
                moveToNextCell('down');
                break;
            case 'Tab':
                e.preventDefault();
                finishEditing();
                moveToNextCell(e.shiftKey ? 'left' : 'right');
                break;
            case 'Escape':
                e.preventDefault();
                cancelEditing(originalValue);
                break;
            case 'ArrowUp':
                e.preventDefault();
                finishEditing();
                moveToNextCell('up');
                break;
            case 'ArrowDown':
                e.preventDefault();
                finishEditing();
                moveToNextCell('down');
                break;
            case 'ArrowLeft':
                if (input.selectionStart === 0 && input.selectionEnd === 0) {
                    e.preventDefault();
                    finishEditing();
                    moveToNextCell('left');
                }
                break;
            case 'ArrowRight':
                if (input.selectionStart === input.value.length && input.selectionEnd === input.value.length) {
                    e.preventDefault();
                    finishEditing();
                    moveToNextCell('right');
                }
                break;
        }
    });
}

// إنهاء التحرير
function finishEditing() {
    if (!currentEditingCell) return;
    
    const input = currentEditingCell.querySelector('.cell-input');
    if (input) {
        let newValue = input.value.trim();
        
        if (input.type === 'number') {
            const numValue = parseInt(newValue);
            if (isNaN(numValue) || numValue < 0 || numValue > 1) {
                newValue = '0';
            } else {
                newValue = numValue.toString();
            }
        }
        
        currentEditingCell.textContent = newValue;
        
        if (input.defaultValue !== newValue) {
            currentEditingCell.style.background = 'linear-gradient(135deg, #c8e6c9 0%, #a5d6a7 100%)';
            setTimeout(() => {
                currentEditingCell.style.background = '';
            }, 1000);
            isDataChanged = true;
        }
    }
    
    currentEditingCell.classList.remove('editing');
    currentEditingCell = null;
    updateStatistics();
}

// إلغاء التحرير
function cancelEditing(originalValue) {
    if (!currentEditingCell) return;
    currentEditingCell.textContent = originalValue;
    currentEditingCell.classList.remove('editing');
    currentEditingCell = null;
}

// الانتقال للخلية التالية
function moveToNextCell(direction) {
    if (!currentEditingCell) return;
    
    const currentRow = currentEditingCell.parentElement;
    const allRows = Array.from(document.querySelectorAll('#tableBody tr'));
    const currentRowIndex = allRows.indexOf(currentRow);
    const currentCells = Array.from(currentRow.querySelectorAll('td'));
    const currentCellIndex = currentCells.indexOf(currentEditingCell);
    
    let nextCell = null;
    
    switch(direction) {
        case 'right':
            if (currentCellIndex < currentCells.length - 2) { // -2 لتجنب عمود الإجراءات
                nextCell = currentCells[currentCellIndex + 1];
            } else if (currentRowIndex < allRows.length - 1) {
                const nextRow = allRows[currentRowIndex + 1];
                nextCell = nextRow.querySelector('td');
            }
            break;
            
        case 'left':
            if (currentCellIndex > 0) {
                nextCell = currentCells[currentCellIndex - 1];
            } else if (currentRowIndex > 0) {
                const prevRow = allRows[currentRowIndex - 1];
                const prevCells = Array.from(prevRow.querySelectorAll('td'));
                nextCell = prevCells[prevCells.length - 2]; // -2 لتجنب عمود الإجراءات
            }
            break;
            
        case 'down':
            if (currentRowIndex < allRows.length - 1) {
                const nextRow = allRows[currentRowIndex + 1];
                const nextCells = Array.from(nextRow.querySelectorAll('td'));
                nextCell = nextCells[Math.min(currentCellIndex, nextCells.length - 2)];
            }
            break;
            
        case 'up':
            if (currentRowIndex > 0) {
                const prevRow = allRows[currentRowIndex - 1];
                const prevCells = Array.from(prevRow.querySelectorAll('td'));
                nextCell = prevCells[Math.min(currentCellIndex, prevCells.length - 2)];
            }
            break;
    }
    
    if (nextCell && nextCell.onclick) {
        // تحديد نوع الخلية
        let cellType = 'text';
        if (nextCell.classList.contains('number-cell')) {
            cellType = 'number';
        } else if (nextCell.classList.contains('date-cell')) {
            cellType = 'date';
        }
        
        // الانتقال للخلية الجديدة
        setTimeout(() => {
            makeEditable(nextCell, cellType);
        }, 50);
    }
}

// تحديث الإحصائيات
function updateStatistics() {
    const rows = document.querySelectorAll('#tableBody tr');
    let totalPatients = 0;
    let totalInterventions = 0;
    let completedReports = 0;
    let pendingReports = 0;
    let advancedReports = 0;
    let followUpRequired = 0;
    
    console.log('Updating statistics for', rows.length, 'rows');
    
    rows.forEach((row, index) => {
        if (row.style.display === 'none') return; // تجاهل الصفوف المخفية بالفلتر
        
        const cells = row.querySelectorAll('td');
        console.log('Row', index, 'has', cells.length, 'cells');
        
        if (cells.length >= 10) {
            // التحقق من وجود بيانات صحيحة في الصف
            const patientName = cells[1].textContent.trim();
            const medicalNumber = cells[2].textContent.trim();
            
            // تجاهل الصفوف الفارغة
            if (patientName && medicalNumber) {
                totalPatients++;
                
                // حساب التدخلات الأساسية (الخلايا من 3 إلى 8)
                let basicInterventions = 0;
                for (let i = 3; i <= 8; i++) {
                    const cellValue = cells[i].textContent.trim();
                    const value = parseInt(cellValue) || 0;
                    console.log('Cell', i, 'value:', cellValue, 'parsed:', value);
                    totalInterventions += value;
                    basicInterventions += value;
                }
                
                // تحديد حالة التقرير
                if (basicInterventions > 0) {
                    completedReports++;
                } else {
                    pendingReports++;
                }
                
                // حساب المتابعة المطلوبة
                const highRiskDrugs = parseInt(cells[5].textContent.trim()) || 0;
                const medicalErrors = parseInt(cells[7].textContent.trim()) || 0;
                if (highRiskDrugs > 0 || medicalErrors > 0) {
                    followUpRequired++;
                }
            }
        }
    });
    
    console.log('Final statistics:', {
        totalPatients,
        totalInterventions,
        completedReports,
        pendingReports,
        advancedReports,
        followUpRequired
    });
    
    // تحديث العناصر في الكروت
    if (document.getElementById('cardTotalPatients')) document.getElementById('cardTotalPatients').textContent = totalPatients;
    if (document.getElementById('cardTotalInterventions')) document.getElementById('cardTotalInterventions').textContent = totalInterventions;
    if (document.getElementById('cardCompletedReports')) document.getElementById('cardCompletedReports').textContent = completedReports;
    if (document.getElementById('cardPendingReports')) document.getElementById('cardPendingReports').textContent = pendingReports;
    
    // تحديث العناصر في الجدول
    if (document.getElementById('footerTotalPatients')) document.getElementById('footerTotalPatients').textContent = totalPatients;
    if (document.getElementById('footerTotalInterventions')) document.getElementById('footerTotalInterventions').textContent = totalInterventions;
    if (document.getElementById('footerCompletedReports')) document.getElementById('footerCompletedReports').textContent = completedReports;
    if (document.getElementById('footerPendingReports')) document.getElementById('footerPendingReports').textContent = pendingReports;
    if (document.getElementById('footerOverallTotal')) document.getElementById('footerOverallTotal').textContent = totalInterventions;
    
    // إضافة تأثيرات بصرية للكروت
    animateStatCards();
}

// تحريك الكروت الإحصائية
function animateStatCards() {
    const cards = document.querySelectorAll('.stat-card');
    cards.forEach((card, index) => {
        setTimeout(() => {
            card.style.transform = 'scale(1.05)';
            setTimeout(() => {
                card.style.transform = 'scale(1)';
            }, 200);
        }, index * 100);
    });
}

// حفظ البيانات
function saveData() {
    if (!selectedUnitId) {
        showNotification('يرجى اختيار قسم أولاً', 'warning');
        return;
    }
    
    if (currentEditingCell) {
        finishEditing();
    }
    
    const rows = document.querySelectorAll('#tableBody tr');
    const data = [];
    
    console.log('Starting save process for', rows.length, 'rows');
    
    rows.forEach((row, index) => {
        const cells = row.querySelectorAll('td');
        if (cells.length >= 10) {
            const patientName = cells[1].textContent.trim();
            const medicalNumber = cells[2].textContent.trim();
            
            console.log(`Row ${index}: name=${patientName}, medical=${medicalNumber}`);
            
            // التحقق من صحة البيانات - يكفي اسم المريض فقط
            if (patientName) {
                
                const rowData = {
                    record_date: cells[0].textContent.trim(),
                    patient_name: patientName,
                    medical_number: medicalNumber,
                    drug_compatibility: parseInt(cells[3].textContent.trim()) || 0,
                    antibiotic_program: parseInt(cells[4].textContent.trim()) || 0,
                    high_risk_drugs: parseInt(cells[5].textContent.trim()) || 0,
                    strict_priority: parseInt(cells[6].textContent.trim()) || 0,
                    error_documentation: parseInt(cells[7].textContent.trim()) || 0,
                    drug_definition: parseInt(cells[8].textContent.trim()) || 0,
                    medication_description: cells[9].textContent.trim() || 'غير محدد'
                };
                
                console.log(`Adding row data:`, rowData);
                data.push(rowData);
            } else {
                console.log(`Skipping row ${index} - missing required data`);
            }
        }
    });
    
    console.log('Total valid rows to save:', data.length);
    
    if (data.length === 0) {
        showNotification('يرجى إدخال بيانات صحيحة للمرضى قبل الحفظ', 'warning');
        return;
    }
    
    const formData = new FormData();
    formData.append('save_data', '1');
    formData.append('selected_unit', selectedUnitId);
    formData.append('selected_date', document.getElementById('dateFilter').value);
    formData.append('table_data', JSON.stringify(data));
    
    console.log('Sending data:', {
        unit_id: selectedUnitId,
        date: document.getElementById('dateFilter').value,
        data_count: data.length
    });
    
    showLoadingIndicator();
    
    fetch('api/save_kpi_data.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        hideLoadingIndicator();
        
        if (result.success) {
            showNotification(`تم حفظ ${result.count} سجل بنجاح للقسم: ${selectedUnitName}`, 'success');
            isDataChanged = false;
            
            // تأثير بصري للنجاح
            rows.forEach(row => {
                row.style.background = 'linear-gradient(135deg, #c8e6c9 0%, #a5d6a7 100%)';
                setTimeout(() => {
                    row.style.background = '';
                }, 1500);
            });
            
        } else {
            showNotification('خطأ في الحفظ: ' + result.message, 'error');
        }
    })
    .catch(error => {
        hideLoadingIndicator();
        console.error('خطأ:', error);
        showNotification('حدث خطأ في الاتصال بالخادم', 'error');
    });
}

// طباعة الجدول
function printTable() {
    if (!selectedUnitId) {
        showNotification('<?php echo __("please_select_unit_first"); ?>', 'warning');
        return;
    }
    
    const printWindow = window.open('', '_blank');
    const tableHTML = document.querySelector('.medical-table-wrapper').outerHTML;
    
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>جدول متابعة المرضى والأدوية - ${selectedUnitName}</title>
            <style>
                body { font-family: Arial, sans-serif; direction: rtl; margin: 20px; }
                .medical-table-wrapper { background: white; }
                .medical-table { width: 100%; border-collapse: collapse; font-size: 10px; }
                .medical-table th, .medical-table td { 
                    border: 1px solid #000; 
                    padding: 4px; 
                    text-align: center; 
                }
                .medical-table th { background: #f0f0f0; font-weight: bold; }
                .table-header-section { 
                    background: #333; 
                    color: white; 
                    padding: 15px; 
                    text-align: center; 
                }
                .btn-delete { display: none; }
                @media print {
                    body { margin: 0; }
                    .medical-table { font-size: 8px; }
                }
            </style>
        </head>
        <body>
            <h2 style="text-align: center; margin-bottom: 20px;">جدول متابعة المرضى والأدوية</h2>
            <p style="text-align: center; margin-bottom: 30px;">
                القسم: ${selectedUnitName} - تاريخ الطباعة: ${new Date().toLocaleDateString('ar-EG')}
            </p>
            ${tableHTML}
        </body>
        </html>
    `);
    
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
}

// إظهار الإشعارات
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px; max-width: 500px;';
    
    const icon = {
        success: 'fas fa-check-circle',
        error: 'fas fa-exclamation-circle',
        warning: 'fas fa-exclamation-triangle',
        info: 'fas fa-info-circle'
    }[type] || 'fas fa-info-circle';
    
    notification.innerHTML = `
        <i class="${icon} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        if (notification.parentNode) {
            notification.classList.remove('show');
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 150);
        }
    }, 5000);
}

// إظهار مؤشر التحميل
function showLoadingIndicator() {
    const loader = document.createElement('div');
    loader.id = 'loadingIndicator';
    loader.className = 'position-fixed top-50 start-50 translate-middle';
    loader.style.zIndex = '10000';
    loader.innerHTML = `
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">جاري التحميل...</span>
        </div>
        <div class="mt-2 text-center">جاري الحفظ...</div>
    `;
    document.body.appendChild(loader);
}

// إخفاء مؤشر التحميل
function hideLoadingIndicator() {
    const loader = document.getElementById('loadingIndicator');
    if (loader) {
        loader.remove();
    }
}

// إخفاء التنبيهات
function hideAlerts() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        if (alert.classList.contains('show')) {
            alert.classList.remove('show');
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.parentNode.removeChild(alert);
                }
            }, 150);
        }
    });
}

// تصدير Excel
function exportToExcel() {
    // تعيين التواريخ الافتراضية
    const today = new Date().toISOString().split('T')[0];
    const lastWeek = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    
    document.getElementById('exportFromDate').value = lastWeek;
    document.getElementById('exportToDate').value = today;
    
    // تعيين القسم الحالي إذا كان محدد
    if (selectedUnitId) {
        document.getElementById('exportUnit').value = selectedUnitId;
    }
    
    // إظهار النافذة المنبثقة
    const modal = new bootstrap.Modal(document.getElementById('exportModal'));
    modal.show();
}

// تنفيذ التصدير
function performExport() {
    const fromDate = document.getElementById('exportFromDate').value;
    const toDate = document.getElementById('exportToDate').value;
    const unitId = document.getElementById('exportUnit').value;
    const pharmacist = document.getElementById('exportPharmacist').value;
    const includeStats = document.getElementById('includeStatistics').checked;
    const includeReports = document.getElementById('includeReports').checked;
    
    if (!fromDate || !toDate) {
        showNotification('<?php echo __("please_select_date_range"); ?>', 'warning');
        return;
    }
    
    if (new Date(fromDate) > new Date(toDate)) {
        showNotification('<?php echo __("from_date_before_to_date"); ?>', 'warning');
        return;
    }
    
    // تحديد نوع التصدير
    let exportUrl;
    const params = new URLSearchParams({
        from_date: fromDate,
        to_date: toDate
    });
    
    if (unitId) {
        params.append('unit_id', unitId);
    }
    
    if (pharmacist) {
        params.append('pharmacist', pharmacist);
    }
    
    if (includeReports) {
        // التصدير الموحد
        params.append('include_medication_tracking', '1');
        params.append('include_reports', '1');
        exportUrl = `export/unified_department_excel.php?${params.toString()}`;
    } else {
        // التصدير العادي لجدول المتابعة فقط
        params.append('include_statistics', includeStats ? '1' : '0');
        exportUrl = `export/patient_medication_excel.php?${params.toString()}`;
    }
    
    // إظهار مؤشر التحميل
    showLoadingIndicator();
    
    // إنشاء iframe مخفي للتحميل
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = exportUrl;
    document.body.appendChild(iframe);
    
    // إزالة iframe بعد التحميل
    setTimeout(() => {
        document.body.removeChild(iframe);
        hideLoadingIndicator();
        
        const exportType = includeReports ? 'التقرير الموحد' : 'جدول متابعة المرضى';
        showNotification(`تم بدء تحميل ${exportType} بنجاح`, 'success');
        
        // إغلاق النافذة المنبثقة
        const modal = bootstrap.Modal.getInstance(document.getElementById('exportModal'));
        modal.hide();
    }, 2000);
}

console.log('تم تحميل جميع وظائف JavaScript بنجاح');

// -------------------
// DASHBOARD CHARTS
// -------------------

// Load Chart.js from CDN
const chartScript = document.createElement('script');
chartScript.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js';
chartScript.onload = function() {
    console.log('Chart.js loaded! Waiting for DOM...');
    // Wait for DOM content to be fully loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initCharts);
    } else {
        initCharts();
    }
};
document.head.appendChild(chartScript);

function initCharts() {
    console.log('Chart initialization started');
    console.log('Status Labels:', <?php echo json_encode($status_labels); ?>);
    console.log('Status Counts:', <?php echo json_encode($status_counts); ?>);
    console.log('Unit Labels:', <?php echo json_encode($unit_labels); ?>);
    console.log('Unit Counts:', <?php echo json_encode($unit_counts); ?>);
    console.log('Time Labels:', <?php echo json_encode($time_labels); ?>);
    console.log('Time Counts:', <?php echo json_encode($time_counts); ?>);
    console.log('Interv Labels:', <?php echo json_encode($interv_labels); ?>);
    console.log('Interv Counts:', <?php echo json_encode($interv_counts); ?>);
    
    // Status Distribution Chart (Pie)
    const statusCtx = document.getElementById('statusChart');
    console.log('statusCtx element:', statusCtx);
    if (statusCtx) {
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode($status_labels); ?>,
                datasets: [{
                    data: <?php echo json_encode($status_counts); ?>,
                    backgroundColor: [
                        '#667eea',  // purple - pending
                        '#11998e',  // green - completed
                        '#f5576c'   // red - cancelled
                    ],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 25,
                            padding: 15,
                            font: {
                                size: 14
                            }
                        }
                    }
                }
            }
        });
    }

    // Reports Per Unit Chart (Bar)
    const unitCtx = document.getElementById('unitChart');
    console.log('unitCtx element:', unitCtx);
    if (unitCtx) {
        new Chart(unitCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($unit_labels); ?>,
                datasets: [{
                    label: 'عدد التقارير',
                    data: <?php echo json_encode($unit_counts); ?>,
                    backgroundColor: 'rgba(102, 126, 234, 0.9)',
                    borderColor: 'rgba(102, 126, 234, 1)',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0,
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }

    // Reports Over Time Chart (Line)
    const timeCtx = document.getElementById('timeChart');
    console.log('timeCtx element:', timeCtx);
    if (timeCtx) {
        new Chart(timeCtx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($time_labels); ?>,
                datasets: [{
                    label: 'عدد التقارير',
                    data: <?php echo json_encode($time_counts); ?>,
                    fill: true,
                    backgroundColor: 'rgba(240, 147, 251, 0.4)',
                    borderColor: 'rgba(245, 87, 108, 1)',
                    borderWidth: 3,
                    tension: 0.4,
                    pointRadius: 8,
                    pointHoverRadius: 12
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0,
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }

    // Interventions Distribution Chart (Bar)
    const intervCtx = document.getElementById('intervChart');
    console.log('intervCtx element:', intervCtx);
    if (intervCtx) {
        new Chart(intervCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($interv_labels); ?>,
                datasets: [{
                    label: 'عدد المرات',
                    data: <?php echo json_encode($interv_counts); ?>,
                    backgroundColor: [
                        'rgba(102, 126, 234, 0.9)',
                        'rgba(17, 153, 142, 0.9)',
                        'rgba(240, 147, 251, 0.9)',
                        'rgba(79, 172, 254, 0.9)',
                        'rgba(48, 207, 208, 0.9)',
                        'rgba(250, 112, 154, 0.9)'
                    ],
                    borderColor: [
                        'rgba(102, 126, 234, 1)',
                        'rgba(17, 153, 142, 1)',
                        'rgba(240, 147, 251, 1)',
                        'rgba(79, 172, 254, 1)',
                        'rgba(48, 207, 208, 1)',
                        'rgba(250, 112, 154, 1)'
                    ],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0,
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }
}

// Export Dashboard to Excel
function exportDashboardToExcel() {
    const dashboardFrom = document.getElementById('dashboard_from').value;
    const dashboardTo = document.getElementById('dashboard_to').value;
    const dashboardUnit = document.getElementById('dashboard_unit').value;

    let url = 'export/kpi_dashboard_excel.php?';
    const params = new URLSearchParams();
    params.set('dashboard_from', dashboardFrom);
    params.set('dashboard_to', dashboardTo);
    if (dashboardUnit) {
        params.set('dashboard_unit', dashboardUnit);
    }

    window.location.href = url + params.toString();
}

</script>

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