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

if (!isset($_SESSION['user_id'])) { redirect('login.php'); }
$currentPage = 'dashboard';
PagePermissions::requirePageAccess($currentPage);

$db = new Database();
$conn = $db->getConnection();
$page_title = __('dashboard') . ' - ' . __('system_name');
$isAr = (Translation::getLanguage() === 'ar');

// ============================================================
// 1. الإحصائيات الأساسية
// ============================================================
$stats = [];
try {
    $stmt = $conn->query("SELECT COUNT(*) as total_patients, SUM(CASE WHEN DATE(created_at)=CURDATE() THEN 1 ELSE 0 END) as today_patients, SUM(CASE WHEN MONTH(created_at)=MONTH(CURDATE()) AND YEAR(created_at)=YEAR(CURDATE()) THEN 1 ELSE 0 END) as month_patients FROM patients");
    $patient_stats = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $conn->query("SELECT COUNT(*) as total_reports, SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END) as pending_reports, SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed_reports, SUM(CASE WHEN DATE(created_at)=CURDATE() THEN 1 ELSE 0 END) as today_reports, SUM(CASE WHEN WEEK(created_at)=WEEK(CURDATE()) THEN 1 ELSE 0 END) as week_reports, SUM(CASE WHEN MONTH(created_at)=MONTH(CURDATE()) AND YEAR(created_at)=YEAR(CURDATE()) THEN 1 ELSE 0 END) as month_reports FROM antibiotic_reports");
    $report_stats = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $conn->query("SELECT COUNT(*) as total_antibiotics, SUM(CASE WHEN is_active=1 THEN 1 ELSE 0 END) as active_antibiotics FROM antibiotics");
    $antibiotic_stats = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $conn->query("SELECT COUNT(*) as total_units, SUM(CASE WHEN is_active=1 THEN 1 ELSE 0 END) as active_units FROM units");
    $unit_stats = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $conn->query("SELECT COUNT(*) as total_users, SUM(CASE WHEN is_active=1 THEN 1 ELSE 0 END) as active_users FROM users");
    $user_stats = $stmt->fetch(PDO::FETCH_ASSOC);

    $stats = array_merge($patient_stats, $report_stats, $antibiotic_stats, $unit_stats, $user_stats);
} catch (Exception $e) {
    $stats = array_fill_keys(['total_patients','today_patients','month_patients','total_reports','pending_reports','completed_reports','today_reports','week_reports','month_reports','total_antibiotics','active_antibiotics','total_units','active_units','total_users','active_users'], 0);
}

// ============================================================
// 2. التقارير الشهرية (آخر 12 شهر)
// ============================================================
$monthly_reports = [];
try {
    $stmt = $conn->query("SELECT DATE_FORMAT(created_at,'%Y-%m') as month, COUNT(*) as count FROM antibiotic_reports WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) GROUP BY DATE_FORMAT(created_at,'%Y-%m') ORDER BY month");
    $monthly_reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $monthly_reports = []; }

// ============================================================
// 3. التقارير لكل صيدلي (آخر 6 أشهر)
// ============================================================
$pharmacist_reports = [];
try {
    $stmt = $conn->query("SELECT u.full_name as pharmacist_name, COUNT(ar.id) as total, SUM(CASE WHEN MONTH(ar.created_at)=MONTH(CURDATE()) AND YEAR(ar.created_at)=YEAR(CURDATE()) THEN 1 ELSE 0 END) as this_month FROM antibiotic_reports ar JOIN users u ON ar.reporting_pharmacist_id=u.id GROUP BY ar.reporting_pharmacist_id, u.full_name ORDER BY total DESC LIMIT 15");
    $pharmacist_reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $pharmacist_reports = []; }

// ============================================================
// 4. التدخلات: نتيجة التدخل (قبول/رفض/تأجيل)
// ============================================================
$intervention_results = [];
try {
    $stmt = $conn->query("SELECT result_of_intervention, COUNT(*) as count FROM antibiotic_reports WHERE result_of_intervention IS NOT NULL AND result_of_intervention != '' GROUP BY result_of_intervention");
    $intervention_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $intervention_results = []; }

// ============================================================
// 5. التدخلات لكل قسم/وحدة
// ============================================================
$unit_interventions = [];
try {
    $stmt = $conn->query("SELECT u.unit_name, COUNT(ar.id) as total, SUM(CASE WHEN ar.result_of_intervention='accept' THEN 1 ELSE 0 END) as accepted, SUM(CASE WHEN ar.result_of_intervention='reject' THEN 1 ELSE 0 END) as rejected FROM antibiotic_reports ar JOIN units u ON ar.unit_id=u.id GROUP BY ar.unit_id, u.unit_name ORDER BY total DESC LIMIT 13");
    $unit_interventions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $unit_interventions = []; }

// ============================================================
// 6. تعريف المشكلة (problem_definition)
// ============================================================
$problem_types = [];
try {
    $stmt = $conn->query("SELECT problem_type, COUNT(*) as count FROM problem_definitions GROUP BY problem_type ORDER BY count DESC LIMIT 10");
    $problem_types = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $problem_types = []; }

// ============================================================
// 7. أكثر المضادات/الأدوية استخداماً
// ============================================================
$top_antibiotics = [];
try {
    $stmt = $conn->query("SELECT COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as drug_name, a.category, COUNT(ar.id) as usage_count, SUM(CASE WHEN MONTH(ar.created_at)=MONTH(CURDATE()) AND YEAR(ar.created_at)=YEAR(CURDATE()) THEN 1 ELSE 0 END) as month_usage FROM antibiotic_reports ar LEFT JOIN antibiotics a ON ar.antibiotic_id=a.id GROUP BY ar.antibiotic_id, ar.other_medication_name, a.antibiotic_name, a.category ORDER BY usage_count DESC LIMIT 10");
    $top_antibiotics = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $top_antibiotics = []; }

// ============================================================
// 8. إحصائيات الأقسام التفصيلية
// ============================================================
$unit_details = [];
try {
    $stmt = $conn->query("SELECT u.unit_name, u.unit_code, COUNT(DISTINCT ar.patient_id) as patient_count, COUNT(ar.id) as report_count, SUM(CASE WHEN ar.status='pending' THEN 1 ELSE 0 END) as pending_count, SUM(CASE WHEN ar.status='completed' THEN 1 ELSE 0 END) as completed_count FROM units u LEFT JOIN antibiotic_reports ar ON u.id=ar.unit_id WHERE u.is_active=1 GROUP BY u.id, u.unit_name, u.unit_code ORDER BY report_count DESC");
    $unit_details = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $unit_details = []; }

// ============================================================
// 9. التقارير الشهرية لكل نوع (ICU, Nursery, Internal, Handover)
// ============================================================
$dept_monthly = [];
try {
    $icu = $conn->query("SELECT DATE_FORMAT(created_at,'%Y-%m') as month, COUNT(*) as count FROM icu_daily_reports WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY month ORDER BY month")->fetchAll(PDO::FETCH_KEY_PAIR);
    $nursery = $conn->query("SELECT DATE_FORMAT(created_at,'%Y-%m') as month, COUNT(*) as count FROM nursery_pediatric_reports WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY month ORDER BY month")->fetchAll(PDO::FETCH_KEY_PAIR);
    $internal = $conn->query("SELECT DATE_FORMAT(created_at,'%Y-%m') as month, COUNT(*) as count FROM internal_reports WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY month ORDER BY month")->fetchAll(PDO::FETCH_KEY_PAIR);
    $handover = $conn->query("SELECT DATE_FORMAT(created_at,'%Y-%m') as month, COUNT(*) as count FROM pharmacy_handover_forms WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY month ORDER BY month")->fetchAll(PDO::FETCH_KEY_PAIR);
    // بناء مصفوفة موحدة للأشهر الـ 6
    $months6 = [];
    for ($i = 5; $i >= 0; $i--) {
        $months6[] = date('Y-m', strtotime("-$i months"));
    }
    foreach ($months6 as $m) {
        $dept_monthly[] = ['month' => $m, 'icu' => $icu[$m] ?? 0, 'nursery' => $nursery[$m] ?? 0, 'internal' => $internal[$m] ?? 0, 'handover' => $handover[$m] ?? 0];
    }
} catch (Exception $e) { $dept_monthly = []; }

// ============================================================
// 10. إجمالي الإجازات لكل شهر
// ============================================================
$holidays_monthly = [];
try {
    $stmt = $conn->query("SELECT DATE_FORMAT(holiday_date,'%Y-%m') as month, COUNT(*) as count FROM holidays WHERE holiday_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) GROUP BY month ORDER BY month");
    $holidays_monthly = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $holidays_monthly = []; }

// ============================================================
// 11. نسبة مهام الصيدلاني لكل شهر (آخر 6 أشهر)
// ============================================================
$pharmacist_monthly = [];
try {
    $stmt = $conn->query("SELECT u.full_name, DATE_FORMAT(ar.created_at,'%Y-%m') as month, COUNT(*) as count FROM antibiotic_reports ar JOIN users u ON ar.reporting_pharmacist_id=u.id WHERE ar.created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY ar.reporting_pharmacist_id, u.full_name, month ORDER BY month, count DESC");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) {
        $pharmacist_monthly[$r['full_name']][$r['month']] = $r['count'];
    }
} catch (Exception $e) { $pharmacist_monthly = []; }

// ============================================================
// 12. آخر التقارير
// ============================================================
$recent_reports = [];
try {
    $stmt = $conn->query("SELECT ar.id, ar.created_at, ar.status, p.patient_name, p.mrn, COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic, u.unit_name as unit FROM antibiotic_reports ar LEFT JOIN patients p ON ar.patient_id=p.id LEFT JOIN antibiotics a ON ar.antibiotic_id=a.id LEFT JOIN units u ON ar.unit_id=u.id ORDER BY ar.created_at DESC LIMIT 10");
    $recent_reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $recent_reports = []; }

include 'includes/header.php';
?>

<style>
:root { --dash-purple:#5e35b1; --dash-teal:#00897b; --dash-orange:#f57c00; --dash-red:#e53935; --dash-green:#43a047; --dash-blue:#1e88e5; }
.db-card { background:#fff; border-radius:14px; box-shadow:0 2px 12px rgba(0,0,0,.07); border:none; margin-bottom:1.2rem; }
.db-card .card-header { background:transparent; border-bottom:2px solid #f0f0f0; padding:1rem 1.25rem .6rem; font-weight:700; font-size:.95rem; color:var(--dash-purple); }
.chart-subtitle { font-size:.72rem; font-weight:400; color:#888; margin-top:3px; line-height:1.4; }
.kpi-box { border-radius:14px; padding:1.1rem 1rem; color:#fff; position:relative; overflow:hidden; min-height:100px; }
.kpi-box .kpi-num { font-size:2rem; font-weight:800; line-height:1; }
.kpi-box .kpi-lbl { font-size:.78rem; opacity:.9; margin-top:4px; }
.kpi-box .kpi-sub { font-size:.72rem; opacity:.75; margin-top:2px; }
.kpi-box .kpi-icon { position:absolute; left:1rem; top:50%; transform:translateY(-50%); font-size:2.8rem; opacity:.18; }
[dir=rtl] .kpi-box .kpi-icon { left:auto; right:1rem; }
.kpi-blue   { background:linear-gradient(135deg,#1e88e5,#1565c0); }
.kpi-orange { background:linear-gradient(135deg,#f57c00,#e65100); }
.kpi-teal   { background:linear-gradient(135deg,#00897b,#00695c); }
.kpi-red    { background:linear-gradient(135deg,#e53935,#b71c1c); }
.kpi-green  { background:linear-gradient(135deg,#43a047,#2e7d32); }
.kpi-purple { background:linear-gradient(135deg,#7b1fa2,#4a148c); }
.kpi-indigo { background:linear-gradient(135deg,#3949ab,#1a237e); }
.kpi-pink   { background:linear-gradient(135deg,#d81b60,#880e4f); }
.section-badge { display:inline-block; background:var(--dash-purple); color:#fff; border-radius:8px; padding:3px 12px; font-size:.78rem; font-weight:700; margin-bottom:.5rem; }
.chart-wrap { position:relative; height:260px; }
.chart-wrap-lg { position:relative; height:320px; }
.chart-wrap-sm { position:relative; height:200px; }
.unit-row { display:flex; align-items:center; gap:8px; padding:6px 0; border-bottom:1px solid #f5f5f5; }
.unit-row:last-child { border-bottom:none; }
.unit-bar { flex:1; height:8px; background:#eee; border-radius:4px; overflow:hidden; }
.unit-bar-fill { height:100%; border-radius:4px; background:linear-gradient(90deg,var(--dash-purple),#9c27b0); }
.drug-item { display:flex; justify-content:space-between; align-items:center; padding:7px 0; border-bottom:1px solid #f5f5f5; }
.drug-item:last-child { border-bottom:none; }
.rank-badge { width:24px; height:24px; border-radius:50%; background:var(--dash-purple); color:#fff; font-size:.7rem; font-weight:700; display:flex; align-items:center; justify-content:center; flex-shrink:0; }
.tab-section { border-bottom:2px solid #eee; margin-bottom:1rem; }
.tab-section .nav-link { color:#888; font-size:.82rem; padding:.4rem .9rem; border-radius:8px 8px 0 0; }
.tab-section .nav-link.active { color:var(--dash-purple); font-weight:700; border-bottom:2px solid var(--dash-purple); background:#f8f5ff; }
@media print { .no-print{display:none!important;} }
</style>

<!-- ===== HEADER ===== -->
<div class="d-flex justify-content-between align-items-center mb-3 no-print flex-wrap gap-2">
    <div>
        <h1 class="h4 mb-0 fw-bold" style="color:var(--dash-purple)"><?php echo __('dashboard'); ?></h1>
        <small class="text-muted"><?php echo __('system_overview'); ?></small>
    </div>
    <div class="d-flex gap-2 flex-wrap">
        <?php if (PagePermissions::hasPermission($currentPage,'print_dashboard')): ?>
        <button class="btn btn-sm btn-outline-secondary" onclick="window.print()"><i class="fas fa-print me-1"></i><?php echo __('print'); ?></button>
        <?php endif; ?>
        <?php if (PagePermissions::hasPermission($currentPage,'export_excel')): ?>
        <button class="btn btn-sm btn-success" onclick="window.location.href='export/dashboard_excel.php'"><i class="fas fa-file-excel me-1"></i>Excel</button>
        <?php endif; ?>
        <?php if (PagePermissions::hasPermission($currentPage,'comprehensive_report')): ?>
        <button class="btn btn-sm btn-primary" onclick="window.location.href='export/comprehensive_excel_report.php'"><i class="fas fa-file-excel me-1"></i><?php echo $isAr?'التقرير الشامل':'Comprehensive'; ?></button>
        <?php endif; ?>
    </div>
</div>

<!-- ===== KPI CARDS ===== -->
<div class="row g-3 mb-3">
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-blue">
            <div class="kpi-num"><?php echo $stats['total_reports']; ?></div>
            <div class="kpi-lbl"><?php echo $isAr?'إجمالي التقارير':'Total Reports'; ?></div>
            <div class="kpi-sub"><?php echo $stats['today_reports']; ?> <?php echo $isAr?'اليوم':'today'; ?></div>
            <i class="fas fa-file-medical kpi-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-green">
            <div class="kpi-num"><?php echo $stats['total_patients']; ?></div>
            <div class="kpi-lbl"><?php echo __('total_patients'); ?></div>
            <div class="kpi-sub"><?php echo $stats['month_patients']; ?> <?php echo $isAr?'هذا الشهر':'this month'; ?></div>
            <i class="fas fa-users kpi-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-teal">
            <div class="kpi-num"><?php echo round(($stats['completed_reports']/max($stats['total_reports'],1))*100); ?>%</div>
            <div class="kpi-lbl"><?php echo $isAr?'معدل الإنجاز':'Completion Rate'; ?></div>
            <div class="kpi-sub"><?php echo $stats['completed_reports']; ?> <?php echo $isAr?'مكتمل':'completed'; ?></div>
            <i class="fas fa-check-circle kpi-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-red">
            <div class="kpi-num"><?php echo $stats['pending_reports']; ?></div>
            <div class="kpi-lbl"><?php echo __('pending_reports'); ?></div>
            <div class="kpi-sub"><?php echo $isAr?'تحتاج متابعة':'need follow-up'; ?></div>
            <i class="fas fa-exclamation-triangle kpi-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-orange">
            <div class="kpi-num"><?php echo $stats['active_antibiotics']; ?></div>
            <div class="kpi-lbl"><?php echo __('active_antibiotics'); ?></div>
            <div class="kpi-sub"><?php echo $isAr?'من':'of'; ?> <?php echo $stats['total_antibiotics']; ?></div>
            <i class="fas fa-pills kpi-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-purple">
            <div class="kpi-num"><?php echo $stats['active_units']; ?></div>
            <div class="kpi-lbl"><?php echo $isAr?'الأقسام النشطة':'Active Units'; ?></div>
            <div class="kpi-sub"><?php echo $isAr?'من 13':'of 13'; ?></div>
            <i class="fas fa-hospital kpi-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-indigo">
            <div class="kpi-num"><?php echo $stats['week_reports']; ?></div>
            <div class="kpi-lbl"><?php echo $isAr?'تقارير هذا الأسبوع':'This Week Reports'; ?></div>
            <div class="kpi-sub"><?php echo $stats['month_reports']; ?> <?php echo $isAr?'هذا الشهر':'this month'; ?></div>
            <i class="fas fa-calendar-week kpi-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-3 col-xl-3">
        <div class="kpi-box kpi-pink">
            <div class="kpi-num"><?php echo $stats['active_users']; ?></div>
            <div class="kpi-lbl"><?php echo $isAr?'المستخدمون النشطون':'Active Users'; ?></div>
            <div class="kpi-sub"><?php echo $isAr?'من':'of'; ?> <?php echo $stats['total_users']; ?></div>
            <i class="fas fa-user-md kpi-icon"></i>
        </div>
    </div>
</div>

<!-- ===== QUICK ACTIONS ===== -->
<?php if (PagePermissions::hasPermission($currentPage,'quick_actions')): ?>
<div class="db-card no-print mb-3">
    <div class="card-header"><i class="fas fa-bolt me-2"></i><?php echo __('quick_actions'); ?></div>
    <div class="card-body py-2 d-flex flex-wrap gap-2">
        <?php if (PagePermissions::hasPermission('pharmacy','add_intervention')): ?>
        <a href="clinical_pharmacy_intervention.php" class="btn btn-sm btn-outline-primary"><i class="fas fa-file-medical me-1"></i><?php echo $isAr?'تدخل صيدلاني':'Clinical Intervention'; ?></a>
        <?php endif; ?>
        <?php if (PagePermissions::hasPermission('patients','add_patient')): ?>
        <a href="add_patient.php" class="btn btn-sm btn-outline-success"><i class="fas fa-user-plus me-1"></i><?php echo $isAr?'إضافة مريض':'Add Patient'; ?></a>
        <?php endif; ?>
        <?php if (PagePermissions::hasPermission('reports_center','view_reports_center')): ?>
        <a href="reports_center.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-folder-open me-1"></i><?php echo $isAr?'مركز التقارير':'Reports Center'; ?></a>
        <?php endif; ?>
        <?php if (PagePermissions::hasPermission('kpi','view_kpi')): ?>
        <a href="key_performance_indicators.php" class="btn btn-sm btn-outline-info"><i class="fas fa-chart-line me-1"></i>KPI</a>
        <?php endif; ?>
        <?php if (PagePermissions::hasPermission('advanced_search','use_advanced_search')): ?>
        <a href="advanced_search.php" class="btn btn-sm btn-outline-warning"><i class="fas fa-search me-1"></i><?php echo __('advanced_search'); ?></a>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- ===== ROW 1: Monthly Trend + Dept Monthly ===== -->
<div class="row g-3 mb-3">
    <div class="col-lg-7">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-chart-line me-2"></i><?php echo $isAr?'الاتجاه الشهري للتقارير (12 شهر)':'Monthly Reports Trend (12 months)'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'عدد تقارير التدخل الصيدلاني الإكلينيكي المُدخلة شهرياً خلال آخر سنة':'Number of clinical pharmacy intervention reports entered monthly over the last year'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap-lg"><canvas id="monthlyTrendChart"></canvas></div></div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-layer-group me-2"></i><?php echo $isAr?'تقارير الأقسام (6 أشهر)':'Department Reports (6 months)'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'مقارنة عدد تقارير كل قسم: رعايات / حضانة / داخلي / تسليم الصيدلة':'Comparison of reports per department: ICU / Nursery / Internal / Handover'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap-lg"><canvas id="deptMonthlyChart"></canvas></div></div>
        </div>
    </div>
</div>

<!-- ===== ROW 2: Intervention Results + Problem Types + Status ===== -->
<div class="row g-3 mb-3">
    <div class="col-lg-4">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-chart-pie me-2"></i><?php echo $isAr?'نتيجة التدخل الصيدلاني':'Intervention Results'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'نسبة قبول / رفض / تأجيل التدخلات الصيدلانية الإكلينيكية':'Acceptance / rejection / postponement rate of clinical pharmacy interventions'; ?></div>
            </div>
            <div class="card-body">
                <div class="chart-wrap"><canvas id="interventionPieChart"></canvas></div>
                <?php
                $accept=0; $reject=0; $postpone=0; $total_int=0;
                foreach($intervention_results as $r){
                    $total_int += $r['count'];
                    if($r['result_of_intervention']=='accept') $accept=$r['count'];
                    elseif($r['result_of_intervention']=='reject') $reject=$r['count'];
                    elseif($r['result_of_intervention']=='postpone') $postpone=$r['count'];
                }
                ?>
                <div class="mt-2 d-flex justify-content-around text-center">
                    <div><div class="fw-bold text-success fs-5"><?php echo $total_int>0?round($accept/$total_int*100):0; ?>%</div><small class="text-muted"><?php echo $isAr?'قبول':'Accept'; ?></small></div>
                    <div><div class="fw-bold text-danger fs-5"><?php echo $total_int>0?round($reject/$total_int*100):0; ?>%</div><small class="text-muted"><?php echo $isAr?'رفض':'Reject'; ?></small></div>
                    <div><div class="fw-bold text-warning fs-5"><?php echo $total_int>0?round($postpone/$total_int*100):0; ?>%</div><small class="text-muted"><?php echo $isAr?'تأجيل':'Postpone'; ?></small></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo $isAr?'أنواع المشاكل':'Problem Types'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'تصنيف المشاكل الدوائية الأكثر تكراراً في التدخلات الصيدلانية':'Most frequent drug problem types recorded in pharmacy interventions'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap"><canvas id="problemTypesChart"></canvas></div></div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-circle-half-stroke me-2"></i><?php echo __('reports_status_distribution'); ?>
                <div class="chart-subtitle"><?php echo $isAr?'توزيع حالات التقارير: مكتملة (تم اتخاذ الإجراء) مقابل معلقة (تحتاج متابعة)':'Report status: completed (action taken) vs pending (needs follow-up)'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap"><canvas id="statusPieChart"></canvas></div></div>
        </div>
    </div>
</div>

<!-- ===== ROW 3: Pharmacist Reports + Unit Interventions ===== -->
<div class="row g-3 mb-3">
    <div class="col-lg-6">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-user-md me-2"></i><?php echo $isAr?'التقارير لكل صيدلي':'Reports per Pharmacist'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'عدد التقارير المُدخلة من كل صيدلاني: الإجمالي من البداية وهذا الشهر':'Total reports entered by each pharmacist: all-time total vs this month'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap-lg"><canvas id="pharmacistChart"></canvas></div></div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-hospital me-2"></i><?php echo $isAr?'التدخلات لكل قسم':'Interventions per Unit'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'عدد التدخلات الصيدلانية لكل قسم مع تفصيل المقبول والمرفوض منها':'Pharmacy interventions per unit with accepted vs rejected breakdown'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap-lg"><canvas id="unitInterventionsChart"></canvas></div></div>
        </div>
    </div>
</div>

<!-- ===== ROW 4: Top Drugs + Holidays + Unit Details ===== -->
<div class="row g-3 mb-3">
    <div class="col-lg-4">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-pills me-2"></i><?php echo $isAr?'أكثر الأدوية استخداماً':'Most Used Drugs'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'الأدوية والمضادات الحيوية الأكثر ظهوراً في تقارير التدخل الصيدلاني':'Drugs & antibiotics most frequently appearing in intervention reports'; ?></div>
            </div>
            <div class="card-body" style="max-height:340px;overflow-y:auto;">
                <?php foreach(array_slice($top_antibiotics,0,10) as $i=>$d): ?>
                <div class="drug-item">
                    <div class="d-flex align-items-center gap-2">
                        <div class="rank-badge"><?php echo $i+1; ?></div>
                        <div>
                            <div class="fw-semibold" style="font-size:.82rem"><?php echo htmlspecialchars($d['drug_name']); ?></div>
                            <small class="text-muted"><?php echo htmlspecialchars($d['category']??''); ?></small>
                        </div>
                    </div>
                    <div class="text-end">
                        <span class="badge bg-primary"><?php echo $d['usage_count']; ?></span>
                        <div><small class="text-muted"><?php echo $d['month_usage']; ?> <?php echo $isAr?'هذا الشهر':'this month'; ?></small></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-calendar-day me-2"></i><?php echo $isAr?'الإجازات الشهرية':'Monthly Holidays'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'عدد أيام الإجازات الرسمية والدينية المُسجلة في النظام لكل شهر':'Number of official & religious holiday days registered in the system per month'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap"><canvas id="holidaysChart"></canvas></div></div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="db-card h-100">
            <div class="card-header">
                <i class="fas fa-building me-2"></i><?php echo $isAr?'أداء الأقسام':'Units Performance'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'إجمالي عدد تقارير التدخل الصيدلاني المُسجلة لكل قسم من البداية':'Total intervention reports recorded per unit since the beginning'; ?></div>
            </div>
            <div class="card-body" style="max-height:340px;overflow-y:auto;">
                <?php $max_r = max(array_merge(array_column($unit_details,'report_count'),[1])); ?>
                <?php foreach($unit_details as $u): ?>
                <div class="unit-row">
                    <div style="min-width:90px;font-size:.78rem;font-weight:600"><?php echo htmlspecialchars($u['unit_name']); ?></div>
                    <div class="unit-bar"><div class="unit-bar-fill" style="width:<?php echo $max_r>0?round($u['report_count']/$max_r*100):0; ?>%"></div></div>
                    <span class="badge bg-secondary" style="font-size:.7rem"><?php echo $u['report_count']; ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- ===== ROW 5: Pharmacist Monthly Stacked ===== -->
<div class="row g-3 mb-3">
    <div class="col-12">
        <div class="db-card">
            <div class="card-header">
                <i class="fas fa-chart-area me-2"></i><?php echo $isAr?'نسبة مهام الصيدلاني لكل شهر (آخر 6 أشهر)':'Pharmacist Tasks per Month (last 6 months)'; ?>
                <div class="chart-subtitle"><?php echo $isAr?'مقارنة مساهمة كل صيدلاني في إدخال التقارير شهرياً - يوضح توزيع العبء الوظيفي بين الفريق':'Monthly contribution of each pharmacist in report entry — shows workload distribution across the team'; ?></div>
            </div>
            <div class="card-body"><div class="chart-wrap-lg"><canvas id="pharmacistMonthlyChart"></canvas></div></div>
        </div>
    </div>
</div>

<!-- ===== Recent Reports Table ===== -->
<div class="db-card mb-3">
    <div class="card-header"><i class="fas fa-list me-2"></i><?php echo __('recent_activities'); ?></div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover table-sm mb-0" style="font-size:.82rem">
                <thead class="table-light">
                    <tr>
                        <th><?php echo __('date'); ?></th>
                        <th><?php echo __('patient_name'); ?></th>
                        <th><?php echo __('mrn'); ?></th>
                        <th><?php echo $isAr?'الدواء':'Drug'; ?></th>
                        <th><?php echo __('unit'); ?></th>
                        <th><?php echo __('status'); ?></th>
                        <th class="no-print"><?php echo $isAr?'إجراءات':'Actions'; ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($recent_reports as $r): ?>
                    <tr>
                        <td><?php echo date('Y-m-d',strtotime($r['created_at'])); ?></td>
                        <td><?php echo htmlspecialchars($r['patient_name']); ?></td>
                        <td><?php echo htmlspecialchars($r['mrn']); ?></td>
                        <td><?php echo htmlspecialchars($r['antibiotic']); ?></td>
                        <td><?php echo htmlspecialchars($r['unit']); ?></td>
                        <td><span class="badge <?php echo $r['status']=='completed'?'bg-success':'bg-warning text-dark'; ?>"><?php echo $r['status']=='completed'?__('completed'):__('pending'); ?></span></td>
                        <td class="no-print">
                            <?php if(PagePermissions::hasPermission('reports','view_reports')): ?>
                            <a href="view_medical_event.php?id=<?php echo $r['id']; ?>" class="btn btn-sm btn-outline-primary py-0 px-1"><i class="fas fa-eye"></i></a>
                            <?php endif; ?>
                            <?php if(PagePermissions::hasPermission('reports','edit_report')): ?>
                            <a href="edit_report.php?id=<?php echo $r['id']; ?>" class="btn btn-sm btn-outline-warning py-0 px-1"><i class="fas fa-edit"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
Chart.defaults.font.family = "'Cairo','Tajawal',sans-serif";
Chart.defaults.color = '#555';
const COLORS = ['#5e35b1','#1e88e5','#43a047','#f57c00','#e53935','#00897b','#d81b60','#3949ab','#00acc1','#7cb342','#fb8c00','#8e24aa'];

// 1. Monthly Trend (12 months)
new Chart(document.getElementById('monthlyTrendChart'), {
    type:'line',
    data:{
        labels: <?php echo json_encode(array_column($monthly_reports,'month')); ?>,
        datasets:[{
            label:'<?php echo $isAr?'عدد التقارير':'Reports Count'; ?>',
            data: <?php echo json_encode(array_column($monthly_reports,'count')); ?>,
            borderColor:'#5e35b1', backgroundColor:'rgba(94,53,177,.12)',
            tension:.4, fill:true, borderWidth:3, pointRadius:5, pointBackgroundColor:'#5e35b1'
        }]
    },
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{precision:0}}}}
});

// 2. Department Monthly Grouped Bar
new Chart(document.getElementById('deptMonthlyChart'), {
    type:'bar',
    data:{
        labels: <?php echo json_encode(array_column($dept_monthly,'month')); ?>,
        datasets:[
            {label:'<?php echo $isAr?'رعايات':'ICU'; ?>',    data:<?php echo json_encode(array_column($dept_monthly,'icu')); ?>,      backgroundColor:'#1e88e5',borderRadius:4},
            {label:'<?php echo $isAr?'حضانة':'Nursery'; ?>', data:<?php echo json_encode(array_column($dept_monthly,'nursery')); ?>,  backgroundColor:'#43a047',borderRadius:4},
            {label:'<?php echo $isAr?'داخلي':'Internal'; ?>', data:<?php echo json_encode(array_column($dept_monthly,'internal')); ?>, backgroundColor:'#f57c00',borderRadius:4},
            {label:'<?php echo $isAr?'تسليم':'Handover'; ?>', data:<?php echo json_encode(array_column($dept_monthly,'handover')); ?>, backgroundColor:'#9c27b0',borderRadius:4}
        ]
    },
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{boxWidth:12,font:{size:11}}}},scales:{y:{beginAtZero:true,ticks:{precision:0}}}}
});

// 3. Intervention Results Doughnut
<?php
$int_labels=[]; $int_data=[]; $int_colors=[];
$map=['accept'=>['#43a047',$isAr?'قبول':'Accept'],'reject'=>['#e53935',$isAr?'رفض':'Reject'],'postpone'=>['#f57c00',$isAr?'تأجيل':'Postpone']];
foreach($intervention_results as $r){
    $key=$r['result_of_intervention'];
    $int_labels[]=$map[$key][1]??$key;
    $int_data[]=(int)$r['count'];
    $int_colors[]=$map[$key][0]??'#999';
}
?>
new Chart(document.getElementById('interventionPieChart'), {
    type:'doughnut',
    data:{labels:<?php echo json_encode($int_labels); ?>,datasets:[{data:<?php echo json_encode($int_data); ?>,backgroundColor:<?php echo json_encode($int_colors); ?>,borderWidth:2}]},
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{boxWidth:12,font:{size:11}}}}}
});

// 4. Problem Types Horizontal Bar
<?php
$pt_labels=[]; $pt_data=[];
$pt_map=['medication_dispensing'=>'صرف الدواء','medication_safety'=>'سلامة الدواء','wrong_regimen'=>'نظام خاطئ','inappropriate_drug_choice'=>'اختيار غير مناسب','drug_related_problem'=>'مشكلة دوائية','wrong_administration'=>'إعطاء خاطئ','dose_adjustment'=>'تعديل جرعة','other_problem'=>'أخرى','medication_labelling'=>'تسمية الدواء','illegible_hand_writing'=>'خط غير مقروء'];
foreach($problem_types as $p){
    $pt_labels[]=$isAr?($pt_map[$p['problem_type']]??$p['problem_type']):$p['problem_type'];
    $pt_data[]=(int)$p['count'];
}
?>
new Chart(document.getElementById('problemTypesChart'), {
    type:'bar',
    data:{labels:<?php echo json_encode($pt_labels); ?>,datasets:[{label:'<?php echo $isAr?'عدد':'Count'; ?>',data:<?php echo json_encode($pt_data); ?>,backgroundColor:COLORS,borderRadius:5}]},
    options:{responsive:true,maintainAspectRatio:false,indexAxis:'y',plugins:{legend:{display:false}},scales:{x:{beginAtZero:true,ticks:{precision:0}}}}
});

// 5. Status Doughnut
new Chart(document.getElementById('statusPieChart'), {
    type:'doughnut',
    data:{
        labels:['<?php echo __('completed'); ?>','<?php echo __('pending'); ?>'],
        datasets:[{data:[<?php echo (int)$stats['completed_reports']; ?>,<?php echo (int)$stats['pending_reports']; ?>],backgroundColor:['#43a047','#f57c00'],borderWidth:2}]
    },
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{boxWidth:12,font:{size:11}}}}}
});

// 6. Pharmacist Bar
new Chart(document.getElementById('pharmacistChart'), {
    type:'bar',
    data:{
        labels:<?php echo json_encode(array_column($pharmacist_reports,'pharmacist_name')); ?>,
        datasets:[
            {label:'<?php echo $isAr?'الإجمالي':'Total'; ?>',     data:<?php echo json_encode(array_map('intval',array_column($pharmacist_reports,'total'))); ?>,      backgroundColor:'#5e35b1',borderRadius:5},
            {label:'<?php echo $isAr?'هذا الشهر':'This Month'; ?>',data:<?php echo json_encode(array_map('intval',array_column($pharmacist_reports,'this_month'))); ?>, backgroundColor:'#00897b',borderRadius:5}
        ]
    },
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'top',labels:{boxWidth:12,font:{size:11}}}},scales:{y:{beginAtZero:true,ticks:{precision:0}}}}
});

// 7. Unit Interventions Grouped Bar
new Chart(document.getElementById('unitInterventionsChart'), {
    type:'bar',
    data:{
        labels:<?php echo json_encode(array_column($unit_interventions,'unit_name')); ?>,
        datasets:[
            {label:'<?php echo $isAr?'الإجمالي':'Total'; ?>',   data:<?php echo json_encode(array_map('intval',array_column($unit_interventions,'total'))); ?>,    backgroundColor:'#1e88e5',borderRadius:5},
            {label:'<?php echo $isAr?'مقبول':'Accepted'; ?>',   data:<?php echo json_encode(array_map('intval',array_column($unit_interventions,'accepted'))); ?>, backgroundColor:'#43a047',borderRadius:5},
            {label:'<?php echo $isAr?'مرفوض':'Rejected'; ?>',   data:<?php echo json_encode(array_map('intval',array_column($unit_interventions,'rejected'))); ?>, backgroundColor:'#e53935',borderRadius:5}
        ]
    },
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'top',labels:{boxWidth:12,font:{size:11}}}},scales:{y:{beginAtZero:true,ticks:{precision:0}}}}
});

// 8. Holidays Monthly Bar
new Chart(document.getElementById('holidaysChart'), {
    type:'bar',
    data:{
        labels:<?php echo json_encode(array_column($holidays_monthly,'month')); ?>,
        datasets:[{label:'<?php echo $isAr?'الإجازات':'Holidays'; ?>',data:<?php echo json_encode(array_map('intval',array_column($holidays_monthly,'count'))); ?>,backgroundColor:'#d81b60',borderRadius:5}]
    },
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{precision:0}}}}
});

// 9. Pharmacist Monthly Stacked Bar
<?php
$pm_months = [];
for($i=5;$i>=0;$i--) $pm_months[]=date('Y-m',strtotime("-$i months"));
$pm_datasets=[];
$pm_colors_list=['#5e35b1','#1e88e5','#43a047','#f57c00','#e53935','#00897b','#d81b60','#3949ab','#00acc1','#7cb342'];
$ci=0;
foreach($pharmacist_monthly as $name=>$months_data){
    $vals=array_map(fn($m)=>(int)($months_data[$m]??0),$pm_months);
    $pm_datasets[]=['label'=>$name,'data'=>$vals,'backgroundColor'=>$pm_colors_list[$ci%count($pm_colors_list)],'borderRadius'=>4];
    $ci++;
}
?>
<?php if(!empty($pm_datasets)): ?>
new Chart(document.getElementById('pharmacistMonthlyChart'), {
    type:'bar',
    data:{labels:<?php echo json_encode($pm_months); ?>,datasets:<?php echo json_encode($pm_datasets); ?>},
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{boxWidth:10,font:{size:10}}}},scales:{x:{stacked:true},y:{stacked:true,beginAtZero:true,ticks:{precision:0}}}}
});
<?php endif; ?>

setTimeout(()=>location.reload(),300000);
</script>

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