<?php

use App\Core\Auth;
use App\Core\Tenant;

$tenantId = Tenant::id();
$branchFilter = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : 0;
$userBranchId = ($auth instanceof Auth) ? $auth->branchId() : null;
if ($userBranchId !== null && $branchFilter === 0) {
    $branchFilter = $userBranchId;
}

$totalPatients = 0;
$todayOrders = 0;
$pendingResults = 0;
$totalTests = 0;
$totalOrders = 0;
$totalCategories = 0;
$patientsChildren = 0;
$patientsMale = 0;
$patientsFemale = 0;
$patientsByMonth = array_fill(1, 12, 0);
$testCategories = [];
$testCategoriesCounts = [];
$financialPaid = 0;
$financialPartial = 0;
$financialUnpaid = 0;
$lowStockItems = [];
$todayRevenue = 0;
$unpaidInvoicesCount = 0;
$ordersByDay = [];
$pendingHomeVisits = 0;
$branchCond = $branchFilter > 0 ? ' AND o.branch_id = ' . (int)$branchFilter : '';
$orderTenantAnd = '';
try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $orderTenantAnd = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
$tenantCond = '';
$tenantAnd = '';
try {
    $db->query('SELECT tenant_id FROM patients LIMIT 1');
    $tenantCond = ' WHERE tenant_id = ' . (int)$tenantId;
    $tenantAnd = ' AND tenant_id = ' . (int)$tenantId;
} catch (Throwable $e) {}

try {
    $stmt = $db->query('SELECT COUNT(*) AS c FROM patients' . $tenantCond);
    $row = $stmt->fetch();
    $totalPatients = (int)$row['c'];

    $testTenantAnd = ''; try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testTenantAnd = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
    $stmt = $db->query('SELECT COUNT(*) AS c FROM tests WHERE 1=1' . $testTenantAnd);
    $row = $stmt->fetch();
    $totalTests = (int)$row['c'];

    $sql = 'SELECT COUNT(*) AS c FROM lab_orders WHERE 1=1' . $orderTenantAnd;
    if ($branchFilter > 0) $sql .= ' AND branch_id = ' . (int)$branchFilter;
    $stmt = $db->query($sql);
    $row = $stmt->fetch();
    $totalOrders = (int)$row['c'];

    $stmt = $db->query('SELECT COUNT(*) AS c FROM test_categories');
    $row = $stmt->fetch();
    $totalCategories = (int)$row['c'];

    $sql = 'SELECT COUNT(*) AS c FROM lab_orders WHERE DATE(order_date) = CURDATE()' . $orderTenantAnd;
    if ($branchFilter > 0) $sql .= ' AND branch_id = ' . (int)$branchFilter;
    $stmt = $db->query($sql);
    $row = $stmt->fetch();
    $todayOrders = (int)$row['c'];

    $stmt = $db->query("SELECT COUNT(*) AS c FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE oi.status IN ('pending','in_progress')" . str_replace('tenant_id', 'o.tenant_id', $orderTenantAnd) . $branchCond);
    $row = $stmt->fetch();
    $pendingResults = (int)$row['c'];

    $stmt = $db->query(
        "SELECT
            SUM(CASE WHEN date_of_birth IS NOT NULL AND TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) < 15 THEN 1 ELSE 0 END) AS children_count,
            SUM(CASE WHEN gender = 'M' AND (date_of_birth IS NULL OR TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) >= 15) THEN 1 ELSE 0 END) AS male_count,
            SUM(CASE WHEN gender = 'F' AND (date_of_birth IS NULL OR TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) >= 15) THEN 1 ELSE 0 END) AS female_count
         FROM patients $tenantCond"
    );
    $row = $stmt->fetch();
    if ($row) {
        $patientsChildren = (int)$row['children_count'];
        $patientsMale = (int)$row['male_count'];
        $patientsFemale = (int)$row['female_count'];
    }

    $stmt = $db->query(
        "SELECT MONTH(created_at) AS m, COUNT(*) AS c
         FROM patients
         WHERE created_at IS NOT NULL AND YEAR(created_at) = YEAR(CURDATE())" . $tenantAnd . "
         GROUP BY MONTH(created_at)"
    );
    foreach ($stmt->fetchAll() as $row) {
        $m = (int)$row['m'];
        if ($m >= 1 && $m <= 12) {
            $patientsByMonth[$m] = (int)$row['c'];
        }
    }

    $stmt = $db->query(
        "SELECT c.name, COUNT(t.id) AS c
         FROM test_categories c
         LEFT JOIN tests t ON t.category_id = c.id
         GROUP BY c.id, c.name
         ORDER BY c.name"
    );
    foreach ($stmt->fetchAll() as $row) {
        $testCategories[] = (string)$row['name'];
        $testCategoriesCounts[] = (int)$row['c'];
    }

    $stmt = $db->query(
        "SELECT
            SUM(CASE WHEN payment_status = 'paid' THEN 1 ELSE 0 END) AS paid_count,
            SUM(CASE WHEN payment_status = 'partial' THEN 1 ELSE 0 END) AS partial_count,
            SUM(CASE WHEN payment_status = 'unpaid' THEN 1 ELSE 0 END) AS unpaid_count
         FROM lab_orders WHERE 1=1" . $orderTenantAnd . ($branchFilter > 0 ? ' AND branch_id = ' . (int)$branchFilter : '')
    );
    $row = $stmt->fetch();
    if ($row) {
        $financialPaid = (int)$row['paid_count'];
        $financialPartial = (int)$row['partial_count'];
        $financialUnpaid = (int)$row['unpaid_count'];
    }

    try {
        $invT = ''; try { $db->query('SELECT tenant_id FROM inventory_items LIMIT 1'); $invT = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        $stmt = $db->query('SELECT item_code, name, current_quantity, min_quantity FROM inventory_items WHERE min_quantity > 0 AND current_quantity <= min_quantity' . $invT . ' ORDER BY current_quantity ASC LIMIT 10');
        $lowStockItems = $stmt->fetchAll();
    } catch (Throwable $e) {}
    try {
        $ordT = ''; try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $ordT = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        $stmt = $db->query("SELECT COALESCE(SUM(i.paid_amount), 0) AS rev FROM invoices i JOIN lab_orders o ON o.id = i.order_id WHERE DATE(i.issue_date) = CURDATE()" . $ordT . ($branchFilter > 0 ? ' AND o.branch_id = ' . (int)$branchFilter : ''));
        $row = $stmt->fetch();
        $todayRevenue = (float)($row['rev'] ?? 0);
    } catch (Throwable $e) {}
    try {
        try {
            $db->query('SELECT tenant_id FROM lab_orders LIMIT 1');
            $stmt = $db->query("SELECT COUNT(*) AS c FROM invoices i JOIN lab_orders o ON o.id = i.order_id WHERE (i.net_amount - i.paid_amount) > 0 AND o.tenant_id = " . (int)$tenantId . "");
        } catch (Throwable $e) {
            $stmt = $db->query("SELECT COUNT(*) AS c FROM invoices i WHERE (i.net_amount - i.paid_amount) > 0");
        }
        $row = $stmt->fetch();
        $unpaidInvoicesCount = (int)($row['c'] ?? 0);
    } catch (Throwable $e) {}
    $expiredItems = [];
    $expiringSoonItems = [];
    try {
        $invT2 = ''; try { $db->query('SELECT tenant_id FROM inventory_items LIMIT 1'); $invT2 = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        $stmt = $db->query('SELECT item_code, name, expiry_date FROM inventory_items WHERE expiry_date IS NOT NULL AND expiry_date < CURDATE()' . $invT2 . ' ORDER BY expiry_date LIMIT 5');
        $expiredItems = $stmt->fetchAll();
        $stmt = $db->query('SELECT item_code, name, expiry_date FROM inventory_items WHERE expiry_date IS NOT NULL AND expiry_date >= CURDATE() AND expiry_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)' . $invT2 . ' ORDER BY expiry_date LIMIT 5');
        $expiringSoonItems = $stmt->fetchAll();
    } catch (Throwable $e) {}

    try {
        $hvTenantAnd = '';
        try {
            $db->query('SELECT tenant_id FROM home_visit_requests LIMIT 1');
            $hvTenantAnd = ' AND tenant_id = ' . (int)$tenantId;
        } catch (Throwable $e) {}
        $stmt = $db->query("SELECT COUNT(*) AS c FROM home_visit_requests WHERE status = 'pending'" . $hvTenantAnd);
        $row = $stmt->fetch();
        $pendingHomeVisits = (int)($row['c'] ?? 0);
    } catch (Throwable $e) {}

    $ordersByDay = [];
    try {
        $stmt = $db->query("SELECT DATE(order_date) AS d, COUNT(*) AS c FROM lab_orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 14 DAY)" . $orderTenantAnd . ($branchFilter > 0 ? ' AND branch_id = ' . (int)$branchFilter : '') . " GROUP BY DATE(order_date) ORDER BY d ASC");
        $ordersByDay = $stmt->fetchAll();
    } catch (Throwable $e) {}
} catch (Throwable $e) {
}

$patientsByMonthLabels = ['يناير','فبراير','مارس','أبريل','مايو','يونيو','يوليو','أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر'];
$patientsByMonthValues = [];
for ($i = 1; $i <= 12; $i++) {
    $patientsByMonthValues[] = $patientsByMonth[$i] ?? 0;
}
$branchesForFilter = [];
try {
    try {
        $db->query('SELECT tenant_id FROM branches LIMIT 1');
        $stmt = $db->prepare('SELECT id, name FROM branches WHERE is_active = 1 AND tenant_id = ? ORDER BY name');
        $stmt->execute([$tenantId]);
    } catch (Throwable $e) {
        $stmt = $db->query('SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name');
    }
    $branchesForFilter = $stmt->fetchAll();
} catch (Throwable $e) {}
$userName = $_SESSION['user_name'] ?? 'مستخدم';
$greeting = date('G') < 12 ? 'صباح الخير' : (date('G') < 18 ? 'مساء الخير' : 'مساء النور');
$todayAr = date('Y-m-d');
$dateDisplay = date('j') . ' ' . ($patientsByMonthLabels[date('n')-1] ?? '') . ' ' . date('Y');
?>
<div class="dashboard">
    <header class="dashboard-header">
        <div class="dashboard-header-inner">
            <div class="dashboard-welcome">
                <h1 class="dashboard-title"><?php echo htmlspecialchars($greeting . '، ' . $userName, ENT_QUOTES, 'UTF-8'); ?></h1>
                <p class="dashboard-date"><?php echo htmlspecialchars($dateDisplay, ENT_QUOTES, 'UTF-8'); ?></p>
            </div>
            <?php if ($userBranchId === null && count($branchesForFilter) > 1): ?>
            <form method="get" class="dashboard-branch-form">
                <input type="hidden" name="page" value="dashboard">
                <label class="dashboard-branch-label">الفرع:</label>
                <select name="branch_id" onchange="this.form.submit()" class="dashboard-branch-select">
                    <option value="">كل الفروع</option>
                    <?php foreach ($branchesForFilter as $br): ?>
                    <option value="<?php echo (int)$br['id']; ?>" <?php echo $branchFilter === (int)$br['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($br['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
            <?php endif; ?>
            <div class="dashboard-actions">
                <?php if (isset($auth) && $auth->can('orders.create')): ?><a href="index.php?page=orders&action=create" class="btn-primary dashboard-btn-primary"><span>طلب جديد</span></a><?php endif; ?>
                <?php if (isset($auth) && $auth->can('patients.create')): ?><a href="index.php?page=patients&action=create" class="btn-secondary">مريض جديد</a><?php endif; ?>
                <?php if ($pendingResults > 0 && isset($auth) && $auth->can('results.view')): ?><a href="index.php?page=results" class="btn-secondary dashboard-pending-btn">نتائج معلقة <span class="badge-count"><?php echo $pendingResults; ?></span></a><?php endif; ?>
            </div>
        </div>
    </header>

    <?php if ($pendingResults > 0 || $pendingHomeVisits > 0 || count($lowStockItems) > 0 || count($expiredItems) > 0 || count($expiringSoonItems) > 0 || $unpaidInvoicesCount > 0): ?>
    <section class="dashboard-alerts">
        <h2 class="dashboard-section-title"><span class="dashboard-section-icon">🔔</span> تنبيهات تحتاج متابعة</h2>
        <div class="alerts-grid">
            <?php if ($pendingResults > 0): ?>
            <a href="index.php?page=results" class="alert-card alert-card--warning">
                <span class="alert-card-icon">📋</span>
                <span class="alert-card-text"><?php echo $pendingResults; ?> نتيجة بانتظار الإدخال</span>
            </a>
            <?php endif; ?>
            <?php if ($pendingHomeVisits > 0 && isset($auth) && $auth->can('orders.view')): ?>
            <a href="index.php?page=home_visits&status=pending" class="alert-card alert-card--info">
                <span class="alert-card-icon">🏠</span>
                <span class="alert-card-text"><?php echo $pendingHomeVisits; ?> طلب زيارة منزلية معلّق</span>
            </a>
            <?php endif; ?>
            <?php if ($unpaidInvoicesCount > 0 && isset($auth) && $auth->can('billing.view')): ?>
            <a href="index.php?page=billing" class="alert-card alert-card--info">
                <span class="alert-card-icon">💰</span>
                <span class="alert-card-text"><?php echo $unpaidInvoicesCount; ?> فاتورة برصيد متبقي</span>
            </a>
            <?php endif; ?>
            <?php foreach ($lowStockItems as $li): ?>
            <a href="index.php?page=inventory" class="alert-card alert-card--caution">
                <span class="alert-card-icon">📦</span>
                <span class="alert-card-text"><?php echo htmlspecialchars($li['name'], ENT_QUOTES, 'UTF-8'); ?> قرب النفاد</span>
            </a>
            <?php endforeach; ?>
            <?php foreach ($expiredItems as $ei): ?>
            <a href="index.php?page=inventory" class="alert-card alert-card--danger">
                <span class="alert-card-icon">⏱</span>
                <span class="alert-card-text"><?php echo htmlspecialchars($ei['name'], ENT_QUOTES, 'UTF-8'); ?> منتهي الصلاحية</span>
            </a>
            <?php endforeach; ?>
            <?php foreach ($expiringSoonItems as $es): ?>
            <a href="index.php?page=inventory" class="alert-card alert-card--caution">
                <span class="alert-card-icon">📅</span>
                <span class="alert-card-text"><?php echo htmlspecialchars($es['name'], ENT_QUOTES, 'UTF-8'); ?> تنتهي صلاحيته قريباً (<?php echo htmlspecialchars($es['expiry_date'], ENT_QUOTES, 'UTF-8'); ?>)</span>
            </a>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <section class="dashboard-stats">
        <h2 class="dashboard-section-title"><span class="dashboard-section-icon">📊</span> نظرة عامة</h2>
        <div class="stats-grid stats-grid--dashboard">
            <div class="stat-card stat-card--primary">
                <div class="stat-card-icon">👥</div>
                <div class="stat-card-content">
                    <span class="stat-label">إجمالي المرضى</span>
                    <span class="stat-value"><?php echo number_format($totalPatients); ?></span>
                </div>
            </div>
            <div class="stat-card stat-card--teal">
                <div class="stat-card-icon">🧪</div>
                <div class="stat-card-content">
                    <span class="stat-label">الفحوصات المعرّفة</span>
                    <span class="stat-value"><?php echo number_format($totalTests); ?></span>
                </div>
            </div>
            <div class="stat-card stat-card--blue">
                <div class="stat-card-icon">📋</div>
                <div class="stat-card-content">
                    <span class="stat-label">إجمالي الطلبات</span>
                    <span class="stat-value"><?php echo number_format($totalOrders); ?></span>
                </div>
            </div>
            <div class="stat-card stat-card--purple">
                <div class="stat-card-icon">📂</div>
                <div class="stat-card-content">
                    <span class="stat-label">أقسام التحاليل</span>
                    <span class="stat-value"><?php echo number_format($totalCategories); ?></span>
                </div>
            </div>
        </div>
    </section>

    <section class="dashboard-today">
        <h2 class="dashboard-section-title"><span class="dashboard-section-icon">📅</span> اليوم</h2>
        <div class="stats-grid stats-grid--today">
            <div class="stat-card stat-card--compact">
                <div class="stat-card-content">
                    <span class="stat-label">طلبات اليوم</span>
                    <span class="stat-value stat-value--lg"><?php echo $todayOrders; ?></span>
                </div>
            </div>
            <div class="stat-card stat-card--compact">
                <div class="stat-card-content">
                    <span class="stat-label">بانتظار النتائج</span>
                    <span class="stat-value stat-value--lg"><?php echo $pendingResults; ?></span>
                </div>
            </div>
            <?php if (isset($auth) && $auth->can('billing.view')): ?>
            <a href="index.php?page=billing" class="stat-card stat-card--compact stat-card--revenue">
                <div class="stat-card-content">
                    <span class="stat-label">إيرادات اليوم</span>
                    <span class="stat-value stat-value--lg stat-value--success"><?php echo number_format($todayRevenue, 0); ?> <small>د.ع</small></span>
                </div>
            </a>
            <?php endif; ?>
        </div>
    </section>
<?php
$featureCards = [
    ['page' => 'patients', 'icon' => 'blue', 'emoji' => '👤', 'title' => 'المرضى', 'desc' => 'سجلات المرضى وبيانات الاتصال', 'group' => 'ops'],
    ['page' => 'doctors', 'icon' => 'teal', 'emoji' => '🩺', 'title' => 'الأطباء', 'desc' => 'الأطباء والعيادات المحوّلة', 'group' => 'ops'],
    ['page' => 'orders', 'icon' => 'teal', 'emoji' => '🧪', 'title' => 'الطلبات', 'desc' => 'إنشاء ومتابعة الطلبات', 'group' => 'ops'],
    ['page' => 'tests', 'icon' => 'purple', 'emoji' => '📋', 'title' => 'الفحوصات', 'desc' => 'كتالوج الفحوصات والأسعار', 'group' => 'ops'],
    ['page' => 'results', 'icon' => 'purple', 'emoji' => '📊', 'title' => 'النتائج', 'desc' => 'إدخال واعتماد النتائج', 'group' => 'ops'],
    ['page' => 'billing', 'icon' => 'orange', 'emoji' => '💰', 'title' => 'الفواتير', 'desc' => 'إصدار الفواتير والمدفوعات', 'group' => 'ops'],
    ['page' => 'inventory', 'icon' => 'orange', 'emoji' => '📦', 'title' => 'المخزون', 'desc' => 'مواد وكواشف المختبر', 'group' => 'admin'],
    ['page' => 'branches', 'icon' => 'green', 'emoji' => '🏢', 'title' => 'الفروع', 'desc' => 'إدارة فروع المختبر', 'group' => 'admin'],
    ['page' => 'reports', 'icon' => 'red', 'emoji' => '📈', 'title' => 'التقارير', 'desc' => 'الإيرادات والطلبات والأداء', 'group' => 'admin'],
    ['page' => 'quality', 'icon' => 'green', 'emoji' => '✅', 'title' => 'ضبط الجودة', 'desc' => 'مراقبة الجودة والعينات', 'group' => 'qa'],
    ['page' => 'integration', 'icon' => 'gray', 'emoji' => '⚙️', 'title' => 'تكامل الأجهزة', 'desc' => 'ربط أجهزة التحاليل', 'group' => 'qa'],
    ['page' => 'security', 'icon' => 'pink', 'emoji' => '🔒', 'title' => 'الأمان', 'desc' => 'الصلاحيات وسجل التدقيق', 'group' => 'system'],
];
?>
    <section class="dashboard-features">
        <h2 class="dashboard-section-title"><span class="dashboard-section-icon">⚡</span> الوصول السريع</h2>
        <div class="feature-grid feature-grid--dashboard">
            <?php foreach ($featureCards as $card): ?>
                <?php if (in_array($card['page'], $allowedPages ?? [], true)): ?>
            <a href="index.php?page=<?php echo htmlspecialchars($card['page'], ENT_QUOTES, 'UTF-8'); ?>" class="feature-card feature-card--dashboard">
                <div class="feature-icon <?php echo htmlspecialchars($card['icon'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo $card['emoji']; ?></div>
                <div class="feature-title"><?php echo htmlspecialchars($card['title'], ENT_QUOTES, 'UTF-8'); ?></div>
                <div class="feature-desc"><?php echo htmlspecialchars($card['desc'], ENT_QUOTES, 'UTF-8'); ?></div>
            </a>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    </section>
    <section class="dashboard-charts">
        <h2 class="dashboard-section-title"><span class="dashboard-section-icon">📈</span> الإحصائيات والرسوم البيانية</h2>
        <div class="charts-row">
            <div class="chart-card">
                <h3 class="chart-title">توزيع المرضى (أطفال / ذكور / إناث)</h3>
                <div class="chart-wrapper">
                    <canvas id="patientsGenderChart"></canvas>
                </div>
            </div>
            <div class="chart-card chart-card--wide">
                <h3 class="chart-title">المرضى الجدد خلال السنة</h3>
                <div class="chart-wrapper">
                    <canvas id="patientsMonthlyChart"></canvas>
                </div>
            </div>
        </div>
        <div class="charts-row">
            <div class="chart-card chart-card--wide">
                <h3 class="chart-title">التحاليل حسب الأقسام</h3>
                <div class="chart-wrapper">
                    <canvas id="testsByCategoryChart"></canvas>
                </div>
            </div>
            <div class="chart-card">
                <h3 class="chart-title">الموقف المالي للطلبات</h3>
                <div class="chart-wrapper">
                    <canvas id="financialStatusChart"></canvas>
                </div>
            </div>
        </div>
        <div class="charts-row">
            <div class="chart-card chart-card--wide">
                <h3 class="chart-title">الطلبات خلال آخر 14 يوم</h3>
                <div class="chart-wrapper">
                    <canvas id="ordersByDayChart"></canvas>
                </div>
            </div>
        </div>
    </section>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const patientsGenderData = {
    labels: ['الأطفال', 'الذكور', 'الإناث'],
    datasets: [{
        data: [<?php echo (int)$patientsChildren; ?>, <?php echo (int)$patientsMale; ?>, <?php echo (int)$patientsFemale; ?>],
        backgroundColor: ['#f97373', '#6366f1', '#22c55e']
    }]
};
const patientsMonthlyData = {
    labels: <?php echo json_encode($patientsByMonthLabels, JSON_UNESCAPED_UNICODE); ?>,
    datasets: [{
        label: 'Total Patients',
        data: <?php echo json_encode($patientsByMonthValues, JSON_UNESCAPED_UNICODE); ?>,
        backgroundColor: '#fb7185'
    }]
};
const testsByCategoryData = {
    labels: <?php echo json_encode($testCategories, JSON_UNESCAPED_UNICODE); ?>,
    datasets: [{
        label: 'Tests Departments',
        data: <?php echo json_encode($testCategoriesCounts, JSON_UNESCAPED_UNICODE); ?>,
        backgroundColor: '#4b5563'
    }]
};
const financialStatusData = {
    labels: ['مدفوعة', 'جزئياً', 'غير مدفوعة'],
    datasets: [{
        data: [<?php echo (int)$financialPaid; ?>, <?php echo (int)$financialPartial; ?>, <?php echo (int)$financialUnpaid; ?>],
        backgroundColor: ['#16a34a', '#f97316', '#ef4444']
    }]
};
var ordersByDayLabels = <?php echo json_encode(array_column($ordersByDay, 'd')); ?>;
var ordersByDayValues = <?php echo json_encode(array_map(function($r){ return (int)($r['c'] ?? 0); }, $ordersByDay)); ?>;
var chartDefaults = { responsive: true, maintainAspectRatio: false };
var patientsGenderCtx = document.getElementById('patientsGenderChart');
if (patientsGenderCtx) {
    new Chart(patientsGenderCtx, {
        type: 'doughnut',
        data: patientsGenderData,
        options: { ...chartDefaults, plugins: { legend: { position: 'bottom', labels: { usePointStyle: true } } }, cutout: '55%' }
    });
}
var patientsMonthlyCtx = document.getElementById('patientsMonthlyChart');
if (patientsMonthlyCtx) {
    new Chart(patientsMonthlyCtx, {
        type: 'bar',
        data: patientsMonthlyData,
        options: { ...chartDefaults, scales: { y: { beginAtZero: true } }, plugins: { legend: { display: false } } }
    });
}
var testsByCategoryCtx = document.getElementById('testsByCategoryChart');
if (testsByCategoryCtx) {
    new Chart(testsByCategoryCtx, {
        type: 'bar',
        data: testsByCategoryData,
        options: { ...chartDefaults, scales: { y: { beginAtZero: true } }, plugins: { legend: { display: false } } }
    });
}
var financialStatusCtx = document.getElementById('financialStatusChart');
if (financialStatusCtx) {
    new Chart(financialStatusCtx, {
        type: 'doughnut',
        data: financialStatusData,
        options: { ...chartDefaults, plugins: { legend: { position: 'bottom', labels: { usePointStyle: true } } }, cutout: '55%' }
    });
}
var ordersByDayCtx = document.getElementById('ordersByDayChart');
if (ordersByDayCtx && ordersByDayLabels && ordersByDayLabels.length) {
    new Chart(ordersByDayCtx, {
        type: 'line',
        data: { labels: ordersByDayLabels, datasets: [{ label: 'عدد الطلبات', data: ordersByDayValues, borderColor: '#0d9488', backgroundColor: 'rgba(13,148,136,0.1)', fill: true }] },
        options: { ...chartDefaults, scales: { y: { beginAtZero: true } }, plugins: { legend: { display: false } } }
    });
}
</script>
