<?php
// ==================== إعدادات أولية ====================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'التحليلات المتقدمة';
include __DIR__ . '/../../includes/header.php'; 
checkLogin();

if (!hasPermission('view_reports')) {
    header('Location: ' . SITE_URL . '/pages/errors/access_denied.php');
    exit();
}

$db = getDB();

// ==================== فلترة التواريخ ====================
$start_date = $_GET['start_date'] ?? '';
$end_date   = $_GET['end_date'] ?? '';
$date_filter_caption = "إحصائيات شاملة للنظام";

function getStat($db, $table, $dateCol = '', $start = '', $end = '', $extra = '') {
    $sql = "SELECT COUNT(*) as count FROM `$table` WHERE 1=1";
    $params = [];
    if ($dateCol && $start && $end) {
        $sql .= " AND `$dateCol` BETWEEN ? AND ?";
        $params = [$start, $end];
    }
    if ($extra) { $sql .= " AND $extra"; }
    try {
        $res = $db->selectOne($sql, $params);
        return $res ? $res['count'] : 0;
    } catch (Exception $e) { return 0; }
}

if ($start_date && $end_date) {
    $date_filter_caption = "النتائج التشغيلية من $start_date إلى $end_date";
}

$data = [
    'halls'      => getStat($db, 'halls'), 
    'machines'   => getStat($db, 'machines'),
    'employees'  => getStat($db, 'employees'),
    'meds'       => getStat($db, 'medications'),
    'users'      => getStat($db, 'users'),
    'patients'   => getStat($db, 'patients', 'created_at', $start_date, $end_date),
    'prescripts' => getStat($db, 'prescriptions', 'date', $start_date, $end_date),
    'dispensed'  => getStat($db, 'medication_dispensing', 'dispense_date', $start_date, $end_date),
    'labs'       => getStat($db, 'lab_requests', 'created_at', $start_date, $end_date),
    'shifts'     => getStat($db, 'shifts', 'shift_date', $start_date, $end_date),
    'done'       => getStat($db, 'appointments', 'created_at', $start_date, $end_date, "status='Completed'"),
    'pending'    => getStat($db, 'appointments', 'created_at', $start_date, $end_date, "status='Scheduled'"),
    'cancelled'  => getStat($db, 'appointments', 'created_at', $start_date, $end_date, "status='Cancelled'"),
];
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;800&display=swap" rel="stylesheet">

<style>
    body { font-family: 'Cairo', sans-serif; background-color: #f0f2f5; }
    .header-card { background: linear-gradient(135deg, #1a2a6c, #1f52b2ff, #8195a0ff); color: white; border-radius: 15px; border: none; }
    .stat-card { border: none; border-radius: 15px; transition: 0.3s; background: #fff; position: relative; overflow: hidden; }
    .stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.08) !important; }
    .icon-wrapper { width: 55px; height: 55px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.6rem; margin-bottom: 10px; z-index: 2; position: relative; }
    
    .bg-soft-blue { background: #e3f2fd; color: #1976d2; }
    .bg-soft-green { background: #e8f5e9; color: #2e677d; }
    .bg-soft-purple { background: #f3e5f5; color: #7b1fa2; }
    .bg-soft-orange { background: #fff3e0; color: #0034ef; }
    .bg-soft-red { background: #ffebee; color: #f90000; }
    .bg-soft-cyan { background: #e0f7fa; color: #00838f; }

    .counter-value { font-weight: 800; color: #1e293b; font-size: 1.6rem; position: relative; z-index: 2; }
    .label-text { color: #64748b; font-weight: 600; font-size: 0.9rem; position: relative; z-index: 2; }
    .status-badge { font-size: 0.7rem; padding: 3px 8px; border-radius: 10px; z-index: 2; position: relative; }
    .watermark-icon { position: absolute; bottom: -10px; left: -10px; font-size: 4rem; opacity: 0.07; transform: rotate(-15deg); z-index: 1; }

    @media print { .no-print { display: none !important; } }
</style>

<div class="container-fluid py-4" dir="rtl">
    
    <div class="card header-card shadow mb-4 animate__animated animate__fadeIn">
        <div class="card-body p-4 d-flex justify-content-between align-items-center text-right">
            <div>
                <h3 class="fw-bold mb-1"><i class="bi bi-activity me-2"></i> التقارير المتقدمة</h3>
                <p class="mb-0 text-white-50 small"><?= $date_filter_caption ?></p>
            </div>
            <div class="no-print">
                <button onclick="window.print()" class="btn btn-light rounded-pill shadow-sm">
                    <i class="bi bi-printer me-1"></i> طباعة
                </button>
            </div>
        </div>
    </div>

    <div class="card stat-card shadow-sm mb-4 no-print border-0">
        <div class="card-body p-3 text-right">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label class="form-label fw-bold small">من تاريخ</label>
                    <input type="date" name="start_date" value="<?= $start_date ?>" class="form-control border-0 bg-light">
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-bold small">إلى تاريخ</label>
                    <input type="date" name="end_date" value="<?= $end_date ?>" class="form-control border-0 bg-light">
                </div>
                <div class="col-md-4">
                    <button type="submit" class="btn btn-primary w-100 shadow-sm rounded-3">تحديث الإحصائيات</button>
                </div>
            </form>
        </div>
    </div>

    <div class="row g-3 text-right">
        <?php
        $stats_config = [
            ['عدد الصالات', $data['halls'], 'bi-door-open-fill', 'bg-soft-blue', false],
            ['أجهزة الغسيل', $data['machines'], 'bi-pc-display-horizontal', 'bg-soft-blue', false],
            ['أصناف الأدوية', $data['meds'], 'bi-box-seam-fill', 'bg-soft-purple', false],
            ['الطاقم الطبي', $data['employees'], 'bi-person-vcard-fill', 'bg-soft-green', false],
            ['مستخدمي النظام', $data['users'], 'bi-person-lock', 'bg-soft-cyan', false],
            ['المرضى الجدد', $data['patients'], 'bi-people-fill', 'bg-soft-green', true],
            ['جلسات الغسيل', $data['shifts'], 'bi-clock-history', 'bg-soft-purple', true],
            ['وصفات طبية', $data['prescripts'], 'bi-file-earmark-medical-fill', 'bg-soft-red', true],
            ['أدوية مصروفة', $data['dispensed'], 'bi-cart-check-fill', 'bg-soft-orange', true],
            ['طلبات المختبر', $data['labs'], 'bi-droplet-fill', 'bg-soft-blue', true],
            ['حجوزات مكتملة', $data['done'], 'bi-calendar-check-fill', 'bg-soft-green', true],
            ['حجوزات مجدولة', $data['pending'], 'bi-calendar-event-fill', 'bg-soft-orange', true],
            ['حجوزات ملغاة', $data['cancelled'], 'bi-calendar-x-fill', 'bg-soft-red', true],
        ];

        foreach ($stats_config as $index => $stat): ?>
            <div class="col-xl-3 col-lg-4 col-sm-6">
                <div class="card stat-card shadow-sm h-100 p-3">
                    <i class="bi <?= $stat[2] ?> watermark-icon"></i>
                    <div class="card-body p-2">
                        <div class="d-flex justify-content-between mb-2">
                            <div class="icon-wrapper <?= $stat[3] ?>">
                                <i class="bi <?= $stat[2] ?>"></i>
                            </div>
                            <span class="badge bg-light text-dark status-badge align-self-start border">
                                <?= $stat[4] ? 'تاريخي' : 'إجمالي' ?>
                            </span>
                        </div>
                        <p class="label-text mb-1"><?= $stat[0] ?></p>
                        <h3 class="counter-value mb-0" data-target="<?= $stat[1] ?>">0</h3>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('.counter-value').forEach(counter => {
            const updateCount = () => {
                const target = +counter.getAttribute('data-target');
                const count = +counter.innerText.replace(/,/g, '');
                const increment = Math.max(target / 20, 1);
                if (count < target) {
                    counter.innerText = Math.ceil(count + increment).toLocaleString();
                    setTimeout(updateCount, 40);
                } else { counter.innerText = target.toLocaleString(); }
            };
            updateCount();
        });
    });
</script>

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