<?php
/**
 * الإحصائيات والإحصائيات الذكية - للمساعدة في اكتشاف الأمراض
 */
$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

$dateFrom = trim($_GET['from'] ?? '');
$dateTo = trim($_GET['to'] ?? '');
$dateFilter = '';
$dateParams = [];
if ($dateFrom !== '') {
    $dateFilter .= ' AND o.order_date >= ?';
    $dateParams[] = $dateFrom . ' 00:00:00';
}
if ($dateTo !== '') {
    $dateFilter .= ' AND o.order_date <= ?';
    $dateParams[] = $dateTo . ' 23:59:59';
}

$stats = [
    'abnormal_by_test' => [],
    'orders_by_status' => [],
    'gender_dist' => [],
    'age_groups' => [],
    'monthly_trend' => [],
    'per_test' => [],
];

try {
    $stmt = $db->prepare("SELECT t.name AS test_name, r.flag, COUNT(*) AS cnt
                         FROM results r
                         JOIN order_items oi ON oi.id = r.order_item_id
                         JOIN lab_orders o ON o.id = oi.order_id
                         JOIN tests t ON t.id = oi.test_id
                         WHERE r.flag IN ('L','H','C') AND r.flag IS NOT NULL $tenantCond $doctorCond $dateFilter
                         GROUP BY oi.test_id, r.flag ORDER BY cnt DESC LIMIT 15");
    $stmt->execute($dateParams);
    $stats['abnormal_by_test'] = $stmt->fetchAll();

    $stmt = $db->prepare("SELECT COUNT(*) AS c FROM lab_orders o WHERE status = 'completed' $tenantCond $doctorCond $dateFilter");
    $stmt->execute($dateParams);
    $completed = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(*) AS c FROM lab_orders o WHERE status IN ('new','in_progress') $tenantCond $doctorCond $dateFilter");
    $stmt->execute($dateParams);
    $pending = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(*) AS c FROM lab_orders o WHERE status = 'cancelled' $tenantCond $doctorCond $dateFilter");
    $stmt->execute($dateParams);
    $cancelled = (int)$stmt->fetchColumn();
    $stats['orders_by_status'] = ['مكتمل' => $completed, 'قيد التنفيذ' => $pending, 'ملغي' => $cancelled];

    $stmt = $db->prepare("SELECT p.gender, COUNT(DISTINCT o.patient_id) AS cnt
                         FROM lab_orders o JOIN patients p ON p.id = o.patient_id
                         WHERE 1=1 $tenantCond $doctorCond $dateFilter AND p.gender IN ('M','F')
                         GROUP BY p.gender");
    $stmt->execute($dateParams);
    foreach ($stmt->fetchAll() as $row) {
        $stats['gender_dist'][$row['gender'] === 'M' ? 'ذكر' : 'أنثى'] = (int)$row['cnt'];
    }

    $stmt = $db->prepare("SELECT
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) < 15 THEN 1 ELSE 0 END) AS child,
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) BETWEEN 15 AND 40 THEN 1 ELSE 0 END) AS young,
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) BETWEEN 41 AND 60 THEN 1 ELSE 0 END) AS mid,
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) > 60 OR p.date_of_birth IS NULL THEN 1 ELSE 0 END) AS senior
        FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE 1=1 $tenantCond $doctorCond $dateFilter");
    $stmt->execute($dateParams);
    $ag = $stmt->fetch();
    if ($ag) {
        $stats['age_groups'] = ['أطفال (<15)' => (int)($ag['child'] ?? 0), 'شباب (15-40)' => (int)($ag['young'] ?? 0), 'وسط (41-60)' => (int)($ag['mid'] ?? 0), 'كبار (>60)' => (int)($ag['senior'] ?? 0)];
    }

    $stmt = $db->prepare("SELECT YEAR(o.order_date) AS y, MONTH(o.order_date) AS m, COUNT(*) AS c FROM lab_orders o WHERE YEAR(o.order_date) >= YEAR(CURDATE())-1 $tenantCond $doctorCond $dateFilter GROUP BY YEAR(o.order_date), MONTH(o.order_date) ORDER BY YEAR(o.order_date), MONTH(o.order_date)");
    $stmt->execute($dateParams);
    $stats['monthly_trend'] = $stmt->fetchAll();

    $stmt = $db->prepare("SELECT t.id, t.name, COUNT(*) AS total, SUM(CASE WHEN r.flag IN ('L','H','C') THEN 1 ELSE 0 END) AS abnormal
                         FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id
                         JOIN tests t ON t.id = oi.test_id
                         LEFT JOIN results r ON r.order_item_id = oi.id
                         WHERE oi.test_id IS NOT NULL $tenantCond $doctorCond $dateFilter
                         GROUP BY oi.test_id ORDER BY total DESC LIMIT 15");
    $stmt->execute($dateParams);
    $stats['per_test'] = $stmt->fetchAll();
} catch (Throwable $e) {}

$monthNames = ['', 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'];

$abnormalLabels = $abnormalLow = $abnormalHigh = $abnormalCrit = [];
if (!empty($stats['abnormal_by_test'])) {
    $groupedAb = [];
    foreach ($stats['abnormal_by_test'] as $r) {
        $n = $r['test_name'];
        if (!isset($groupedAb[$n])) $groupedAb[$n] = ['L'=>0,'H'=>0,'C'=>0];
        $groupedAb[$n][$r['flag']] = (int)$r['cnt'];
    }
    $abnormalLabels = array_keys($groupedAb);
    $abnormalLow = array_map(function($g) { return $g['L']; }, $groupedAb);
    $abnormalHigh = array_map(function($g) { return $g['H']; }, $groupedAb);
    $abnormalCrit = array_map(function($g) { return $g['C']; }, $groupedAb);
}

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="statistics_' . ($dateFrom ?: 'all') . '_' . ($dateTo ?: 'all') . '.csv"');
    echo "\xEF\xBB\xBF";
    echo "الإحصائيات,القيمة\n";
    echo "الفترة," . ($dateFrom ?: 'الكل') . " - " . ($dateTo ?: 'الآن') . "\n";
    echo "طلبات مكتملة," . ($stats['orders_by_status']['مكتمل'] ?? 0) . "\n";
    echo "طلبات قيد التنفيذ," . ($stats['orders_by_status']['قيد التنفيذ'] ?? 0) . "\n";
    echo "طلبات ملغاة," . ($stats['orders_by_status']['ملغي'] ?? 0) . "\n";
    echo "ذكر," . ($stats['gender_dist']['ذكر'] ?? 0) . "\n";
    echo "أنثى," . ($stats['gender_dist']['أنثى'] ?? 0) . "\n";
    foreach ($stats['age_groups'] ?? [] as $k => $v) { echo $k . "," . $v . "\n"; }
    echo "\nإحصائيات حسب الفحص\n";
    echo "الفحص,الإجمالي,غير طبيعية,النسبة\n";
    foreach ($stats['per_test'] ?? [] as $pt) {
        $pct = (int)$pt['total'] > 0 ? round((int)$pt['abnormal'] / (int)$pt['total'] * 100, 1) : 0;
        echo '"' . str_replace('"', '""', $pt['name']) . '",' . (int)$pt['total'] . ',' . (int)$pt['abnormal'] . ',' . $pct . "%\n";
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/svg+xml" href="favicon.svg">
    <title>الإحصائيات - Smart Doctor</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="doctor.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content doctor-statistics-page">
    <div class="doctor-stats-page-header">
        <div>
            <h1>الإحصائيات والتحليلات</h1>
            <p class="doctor-stats-subtitle">لمساعدتك في اكتشاف الأنماط والأمراض الشائعة</p>
        </div>
        <div class="doctor-stats-filters">
            <div class="doctor-stats-quick-filters">
                <a href="doctor.php?page=statistics&from=<?php echo date('Y-m-d'); ?>&to=<?php echo date('Y-m-d'); ?>" class="btn-secondary btn-sm">اليوم</a>
                <a href="doctor.php?page=statistics&from=<?php echo date('Y-m-d', strtotime('-1 day')); ?>&to=<?php echo date('Y-m-d', strtotime('-1 day')); ?>" class="btn-secondary btn-sm">أمس</a>
                <a href="doctor.php?page=statistics&from=<?php echo date('Y-m-d', strtotime('monday this week')); ?>&to=<?php echo date('Y-m-d'); ?>" class="btn-secondary btn-sm">هذا الأسبوع</a>
                <a href="doctor.php?page=statistics&from=<?php echo date('Y-m-01'); ?>&to=<?php echo date('Y-m-d'); ?>" class="btn-secondary btn-sm">هذا الشهر</a>
            </div>
            <form method="get" class="doctor-stats-date-form">
                <input type="hidden" name="page" value="statistics">
                <input type="date" name="from" value="<?php echo htmlspecialchars($dateFrom, ENT_QUOTES, 'UTF-8'); ?>" placeholder="من">
                <input type="date" name="to" value="<?php echo htmlspecialchars($dateTo, ENT_QUOTES, 'UTF-8'); ?>" placeholder="إلى">
                <button type="submit" class="btn-primary">تطبيق</button>
                <?php if ($dateFrom || $dateTo): ?><a href="doctor.php?page=statistics" class="btn-secondary">إلغاء</a><?php endif; ?>
                <a href="doctor.php?page=statistics&export=csv&from=<?php echo urlencode($dateFrom); ?>&to=<?php echo urlencode($dateTo); ?>" class="btn-secondary">📥 تصدير</a>
            </form>
        </div>
    </div>

    <div class="doctor-charts-row">
        <div class="doctor-chart-card card">
            <h3 class="doctor-chart-title">حالة الطلبات</h3>
            <div class="doctor-chart-container doctor-chart-doughnut">
                <canvas id="chartStatus"></canvas>
            </div>
        </div>
        <div class="doctor-chart-card card">
            <h3 class="doctor-chart-title">توزيع حسب الجنس</h3>
            <div class="doctor-chart-container doctor-chart-doughnut">
                <canvas id="chartGender"></canvas>
            </div>
        </div>
    </div>

    <div class="doctor-charts-row">
        <div class="doctor-chart-card card">
            <h3 class="doctor-chart-title">توزيع الفئات العمرية</h3>
            <div class="doctor-chart-container doctor-chart-bar">
                <canvas id="chartAge"></canvas>
            </div>
        </div>
        <div class="doctor-chart-card card">
            <h3 class="doctor-chart-title">النتائج غير الطبيعية حسب الفحص</h3>
            <?php if (empty($stats['abnormal_by_test'])): ?>
            <p style="color:var(--text-muted);">لا توجد بيانات</p>
            <?php else:
            $grouped = [];
            foreach ($stats['abnormal_by_test'] as $r) {
                $n = $r['test_name'];
                if (!isset($grouped[$n])) $grouped[$n] = ['L'=>0,'H'=>0,'C'=>0];
                $grouped[$n][$r['flag']] = (int)$r['cnt'];
            }
            ?>
            <div class="doctor-chart-container doctor-chart-bar doctor-chart-abnormal">
                <canvas id="chartAbnormal"></canvas>
            </div>
            <div class="table-wrapper">
                <table class="table">
                    <thead>
                        <tr>
                            <th>الفحص</th>
                            <th>منخفض</th>
                            <th>مرتفع</th>
                            <th>حرج</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($grouped as $name => $v):
                    ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); ?></strong></td>
                        <td><span style="color:#f59e0b;"><?php echo $v['L']; ?></span></td>
                        <td><span style="color:#ef4444;"><?php echo $v['H']; ?></span></td>
                        <td><span style="color:#dc2626;"><?php echo $v['C']; ?></span></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="doctor-chart-card doctor-chart-full card">
        <h3 class="doctor-chart-title">اتجاه الطلبات الشهري</h3>
        <div class="doctor-chart-container doctor-chart-line">
            <canvas id="chartTrend"></canvas>
        </div>
    </div>

    <?php if (!empty($stats['per_test'])): ?>
    <div class="doctor-chart-card card doctor-stats-per-test">
        <h3 class="doctor-chart-title">إحصائيات حسب نوع الفحص</h3>
        <div class="doctor-chart-container doctor-chart-bar" style="margin-bottom:20px;">
            <canvas id="chartPerTest"></canvas>
        </div>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>الفحص</th>
                        <th>إجمالي النتائج</th>
                        <th>غير طبيعية</th>
                        <th>نسبة غير طبيعية</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($stats['per_test'] as $pt): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($pt['name'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
                    <td><?php echo (int)$pt['total']; ?></td>
                    <td><span style="color:<?php echo (int)$pt['abnormal'] > 0 ? '#ef4444' : '#22c55e'; ?>;"><?php echo (int)$pt['abnormal']; ?></span></td>
                    <td><?php echo (int)$pt['total'] > 0 ? round((int)$pt['abnormal'] / (int)$pt['total'] * 100, 1) : 0; ?>%</td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</main>

<script>
(function(){
    var chartOptions = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { position: 'bottom', labels: { padding: 16, font: { size: 13 } } } }
    };
    var colors = ['#0d9488','#3b82f6','#f59e0b','#ef4444'];
    if (document.getElementById('chartStatus')) {
        new Chart(document.getElementById('chartStatus'), {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode(array_keys($stats['orders_by_status'])); ?>,
                datasets: [{ data: <?php echo json_encode(array_values($stats['orders_by_status'])); ?>, backgroundColor: colors, borderWidth: 2 }]
            },
            options: { ...chartOptions, cutout: '55%' }
        });
    }
    if (document.getElementById('chartGender')) {
        new Chart(document.getElementById('chartGender'), {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode(array_keys($stats['gender_dist'])); ?>,
                datasets: [{ data: <?php echo json_encode(array_values($stats['gender_dist'])); ?>, backgroundColor: ['#3b82f6','#ec4899'], borderWidth: 2 }]
            },
            options: { ...chartOptions, cutout: '55%' }
        });
    }
    if (document.getElementById('chartAge')) {
        new Chart(document.getElementById('chartAge'), {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_keys($stats['age_groups'])); ?>,
                datasets: [{ label: 'المرضى', data: <?php echo json_encode(array_values($stats['age_groups'])); ?>, backgroundColor: 'rgba(13,148,136,0.8)', borderColor: '#0d9488', borderWidth: 1 }]
            },
            options: {
                ...chartOptions,
                scales: {
                    y: { beginAtZero: true, ticks: { font: { size: 12 } } },
                    x: { ticks: { font: { size: 12 }, maxRotation: 0 } }
                }
            }
        });
    }
    var trend = <?php echo json_encode($stats['monthly_trend']); ?>;
    var monthNames = <?php echo json_encode($monthNames); ?>;
    if (document.getElementById('chartTrend') && trend.length) {
        var labels = trend.map(function(r){
            var m = parseInt(r.m, 10) || 0;
            var mn = monthNames[m] || m.toString();
            return mn;
        });
        var data = trend.map(function(r){ return r.c; });
        new Chart(document.getElementById('chartTrend'), {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{ label: 'الطلبات', data: data, borderColor: '#0d9488', backgroundColor: 'rgba(13,148,136,0.1)', fill: true, tension: 0.3, borderWidth: 2 }]
            },
            options: {
                ...chartOptions,
                scales: {
                    y: { beginAtZero: true, ticks: { font: { size: 12 } } },
                    x: { ticks: { font: { size: 12 } } }
                }
            }
        });
    }
    var abnormalLabels = <?php echo json_encode(array_map(function($n){ return mb_strlen($n) > 15 ? mb_substr($n,0,13).'..' : $n; }, $abnormalLabels)); ?>;
    var abnormalLow = <?php echo json_encode($abnormalLow ?? []); ?>;
    var abnormalHigh = <?php echo json_encode($abnormalHigh ?? []); ?>;
    var abnormalCrit = <?php echo json_encode($abnormalCrit ?? []); ?>;
    if (document.getElementById('chartAbnormal') && abnormalLabels.length > 0) {
        new Chart(document.getElementById('chartAbnormal'), {
            type: 'bar',
            data: {
                labels: abnormalLabels,
                datasets: [
                    { label: 'منخفض', data: abnormalLow, backgroundColor: 'rgba(245,158,11,0.8)', borderColor: '#f59e0b', borderWidth: 1 },
                    { label: 'مرتفع', data: abnormalHigh, backgroundColor: 'rgba(239,68,68,0.8)', borderColor: '#ef4444', borderWidth: 1 },
                    { label: 'حرج', data: abnormalCrit, backgroundColor: 'rgba(220,38,38,0.9)', borderColor: '#dc2626', borderWidth: 1 }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { position: 'bottom' } },
                scales: {
                    y: { beginAtZero: true, stacked: true, ticks: { font: { size: 11 } } },
                    x: { stacked: true, ticks: { font: { size: 10 }, maxRotation: 45 } }
                }
            }
        });
    }
    var perTest = <?php echo json_encode($stats['per_test'] ?? []); ?>;
    if (document.getElementById('chartPerTest') && perTest.length) {
        new Chart(document.getElementById('chartPerTest'), {
            type: 'bar',
            data: {
                labels: perTest.map(function(p){ return p.name.length > 20 ? p.name.substring(0,18)+'..' : p.name; }),
                datasets: [
                    { label: 'إجمالي', data: perTest.map(function(p){ return p.total; }), backgroundColor: 'rgba(59,130,246,0.7)', borderColor: '#3b82f6', borderWidth: 1 },
                    { label: 'غير طبيعية', data: perTest.map(function(p){ return p.abnormal; }), backgroundColor: 'rgba(239,68,68,0.7)', borderColor: '#ef4444', borderWidth: 1 }
                ]
            },
            options: {
                ...chartOptions,
                scales: {
                    y: { beginAtZero: true, stacked: false, ticks: { font: { size: 11 } } },
                    x: { ticks: { font: { size: 10 }, maxRotation: 45 } }
                }
            }
        });
    }
})();
</script>
</body>
</html>
