<?php
require_once 'auth.php';
requireLogin();

function formatBaghdadDateTime12($value) {
    if (empty($value)) return '-';
    try {
        $dt = new DateTime((string)$value, new DateTimeZone('Asia/Baghdad'));
        $dt->setTimezone(new DateTimeZone('Asia/Baghdad'));
        $period = ((int)$dt->format('H') < 12) ? 'ص' : 'م';
        return $dt->format('Y-m-d h:i') . ' ' . $period;
    } catch (Exception $e) {
        return (string)$value;
    }
}

// إحصائيات
$stats = [];
$stats['hospitals'] = $conn->query("SELECT COUNT(*) as c FROM hospitals")->fetch_assoc()['c'];
$stats['devices'] = $conn->query("SELECT COUNT(*) as c FROM devices")->fetch_assoc()['c'];
$stats['devices_today'] = $conn->query("SELECT COUNT(*) as c FROM devices WHERE DATE(created_at) = CURDATE()")->fetch_assoc()['c'];
$stats['warranty_active'] = $conn->query("SELECT COUNT(*) as c FROM devices WHERE DATE_ADD(installation_date, INTERVAL warranty_months MONTH) >= CURDATE()")->fetch_assoc()['c'];
$stats['warranty_expired'] = $stats['devices'] - $stats['warranty_active'];
$stats['maintenance_due'] = 0;
$stats['warranty_expiring_soon'] = $conn->query("SELECT COUNT(*) as c FROM devices WHERE DATE_ADD(installation_date, INTERVAL warranty_months MONTH) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)")->fetch_assoc()['c'];
$devs = $conn->query("SELECT d.id, d.installation_date, (SELECT MAX(created_at) FROM job_sheet_images WHERE device_id = d.id) as last_m FROM devices d");
while ($d = $devs->fetch_assoc()) {
    $ref = $d['last_m'] ? strtotime($d['last_m']) : strtotime($d['installation_date']);
    if ($ref <= strtotime('-3 months')) $stats['maintenance_due']++;
}

// آخر الأجهزة المضافة
$recentDevicesList = [];
$rdq = $conn->query("SELECT d.id, d.invoice_number, d.hospital_name, dn.name as device_name, d.created_at FROM devices d JOIN device_names dn ON d.device_name_id = dn.id ORDER BY d.created_at DESC LIMIT 5");
if ($rdq) while ($r = $rdq->fetch_assoc()) $recentDevicesList[] = $r;

// أجهزة قد تحتاج صيانة (الأقدم تنصيباً)
$urgentList = [];
$urgent = $conn->query("SELECT d.id, d.invoice_number, d.hospital_name, dn.name as device_name, d.installation_date FROM devices d JOIN device_names dn ON d.device_name_id = dn.id ORDER BY d.installation_date ASC LIMIT 5");
if ($urgent) while ($r = $urgent->fetch_assoc()) $urgentList[] = $r;

// أجهزة الإضافة الشهرية (آخر 6 أشهر)
$monthlyDevices = [];
for ($i = 5; $i >= 0; $i--) {
    $date = date('Y-m', strtotime("-$i months"));
    $label = date('M Y', strtotime("-$i months"));
    $cnt = $conn->query("SELECT COUNT(*) as c FROM devices WHERE DATE_FORMAT(created_at,'%Y-%m') = '$date'")->fetch_assoc()['c'];
    $monthlyDevices[] = ['label' => $label, 'count' => (int)$cnt];
}

$today = date('Y-m-d');
$devicesThisMonth = $conn->query("SELECT COUNT(*) as c FROM devices WHERE DATE_FORMAT(created_at,'%Y-%m') = DATE_FORMAT(CURDATE(),'%Y-%m')")->fetch_assoc()['c'];

// متابعة إرسال المهندسين اليوم
$engineersSentToday = [];
$sentQ = $conn->query("SELECT e.id, e.name, COUNT(d.id) as sent_count
    FROM engineers e
    JOIN devices d ON d.engineer_id = e.id AND DATE(d.created_at) = CURDATE()
    GROUP BY e.id, e.name
    ORDER BY sent_count DESC, e.name ASC");
if ($sentQ) while ($r = $sentQ->fetch_assoc()) $engineersSentToday[] = $r;

$engineersNotSentToday = [];
$notSentQ = $conn->query("SELECT e.id, e.name
    FROM engineers e
    LEFT JOIN devices d ON d.engineer_id = e.id AND DATE(d.created_at) = CURDATE()
    GROUP BY e.id, e.name
    HAVING COUNT(d.id) = 0
    ORDER BY e.name ASC");
if ($notSentQ) while ($r = $notSentQ->fetch_assoc()) $engineersNotSentToday[] = $r;

$stats['engineers_total'] = $conn->query("SELECT COUNT(*) as c FROM engineers")->fetch_assoc()['c'];
$stats['engineers_sent_today'] = count($engineersSentToday);
$stats['engineers_not_sent_today'] = count($engineersNotSentToday);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <?php include 'includes/favicon.php'; ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة التحكم - نظام صيانة الأجهزة</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/dashboard.css" rel="stylesheet">
</head>
<body class="dashboard-body">
    <?php include 'includes/header.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid py-4 px-4">
            <nav aria-label="breadcrumb" class="mb-3">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item active" aria-current="page">لوحة التحكم</li>
                </ol>
            </nav>
            <!-- ترحيب وإجراءات سريعة -->
            <div class="dashboard-hero mb-4">
                <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
                    <div>
                        <h1 class="dashboard-welcome mb-1">مرحباً، <?= htmlspecialchars($_SESSION['username'] ?? '') ?></h1>
                        <p class="dashboard-subtitle mb-2"><?= date('Y-m-d') ?> · <?= ['الأحد','الإثنين','الثلاثاء','الأربعاء','الخميس','الجمعة','السبت'][date('w')] ?> · نظام صيانة الأجهزة</p>
                        <div class="d-flex gap-2 flex-wrap">
                            <?php if (canEdit()): ?><a href="devices.php" class="btn btn-primary btn-lg"><i class="bi bi-plus-circle me-1"></i> إضافة جهاز</a><?php endif; ?>
                            <?php if (canExport()): ?><a href="export.php?type=all" class="btn btn-outline-success btn-lg"><i class="bi bi-file-excel me-1"></i> تصدير Excel</a><?php endif; ?>
                            <a href="search.php" class="btn btn-outline-primary btn-lg"><i class="bi bi-search me-1"></i> بحث سريع</a>
                        </div>
                    </div>
                    <div class="dashboard-quick-stats">
                        <div class="quick-stat-item">
                            <span class="quick-stat-value"><?= $devicesThisMonth ?></span>
                            <span class="quick-stat-label">جهاز هذا الشهر</span>
                        </div>
                        <div class="quick-stat-item">
                            <span class="quick-stat-value"><?= $stats['devices_today'] ?></span>
                            <span class="quick-stat-label">جهاز اليوم</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- بطاقات الإحصائيات -->
            <div class="dashboard-section-title">نظرة عامة على الإحصائيات</div>
            <div class="row g-3 mb-5">
                <div class="col-6 col-md-4 col-xl-2">
                    <a href="hospitals.php" class="text-decoration-none">
                    <div class="card stat-card-pro stat-primary-pro h-100">
                        <div class="card-body d-flex align-items-center">
                            <div class="stat-icon"><i class="bi bi-hospital"></i></div>
                            <div class="flex-grow-1">
                                <h3 class="stat-value mb-0"><?= $stats['hospitals'] ?></h3>
                                <small class="stat-label">مستشفى</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <a href="devices_list.php" class="text-decoration-none">
                    <div class="card stat-card-pro stat-secondary-pro h-100">
                        <div class="card-body d-flex align-items-center">
                            <div class="stat-icon"><i class="bi bi-cpu"></i></div>
                            <div class="flex-grow-1">
                                <h3 class="stat-value mb-0"><?= $stats['devices'] ?></h3>
                                <small class="stat-label">جهاز</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <a href="warranty.php" class="text-decoration-none">
                    <div class="card stat-card-pro stat-success-pro h-100">
                        <div class="card-body d-flex align-items-center">
                            <div class="stat-icon"><i class="bi bi-shield-check"></i></div>
                            <div class="flex-grow-1">
                                <h3 class="stat-value mb-0"><?= $stats['warranty_active'] ?></h3>
                                <small class="stat-label">داخل الضمان</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <a href="warranty.php" class="text-decoration-none">
                    <div class="card stat-card-pro stat-danger-pro h-100">
                        <div class="card-body d-flex align-items-center">
                            <div class="stat-icon"><i class="bi bi-shield-x"></i></div>
                            <div class="flex-grow-1">
                                <h3 class="stat-value mb-0"><?= $stats['warranty_expired'] ?></h3>
                                <small class="stat-label">منتهي الضمان</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <a href="maintenance_query.php" class="text-decoration-none">
                    <div class="card stat-card-pro stat-warning-pro h-100">
                        <div class="card-body d-flex align-items-center">
                            <div class="stat-icon"><i class="bi bi-tools"></i></div>
                            <div class="flex-grow-1">
                                <h3 class="stat-value mb-0"><?= $stats['maintenance_due'] ?></h3>
                                <small class="stat-label">تحتاج صيانة</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <a href="devices_list.php?created_range=today" class="text-decoration-none">
                    <div class="card stat-card-pro stat-info-pro h-100">
                        <div class="card-body d-flex align-items-center">
                            <div class="stat-icon"><i class="bi bi-calendar2-check"></i></div>
                            <div class="flex-grow-1">
                                <h3 class="stat-value mb-0"><?= $stats['devices_today'] ?></h3>
                                <small class="stat-label">تسجيلات اليوم</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
            </div>
            
            <div class="dashboard-section-title mt-2">البيانات والتقارير</div>
            <div class="row g-4">
                <!-- آخر الأجهزة + صيانة عاجلة -->
                <div class="col-lg-8">
                    <div class="row g-4">
                        <div class="col-12">
                            <div class="card dashboard-card h-100">
                                <div class="card-header bg-transparent border-0 d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0 fw-600"><i class="bi bi-clock-history text-primary me-2"></i>آخر الأجهزة المضافة</h5>
                                    <a href="devices_list.php" class="btn btn-sm btn-outline-primary">عرض الكل</a>
                                </div>
                                <div class="card-body pt-2">
                                    <?php if (!empty($recentDevicesList)): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-sm mb-0 dashboard-table">
                                            <thead><tr><th>الفاتورة</th><th>المستشفى</th><th>الجهاز</th><th>التاريخ</th></tr></thead>
                                            <tbody>
                                            <?php foreach ($recentDevicesList as $rd): ?>
                                            <tr class="cursor-pointer" onclick="location.href='device_view.php?id=<?= $rd['id'] ?>'">
                                                <td><a href="device_view.php?id=<?= $rd['id'] ?>" class="text-decoration-none"><?= htmlspecialchars($rd['invoice_number']) ?></a></td>
                                                <td><?= htmlspecialchars($rd['hospital_name']) ?></td>
                                                <td><?= htmlspecialchars($rd['device_name']) ?></td>
                                                <td class="text-muted"><?= htmlspecialchars(formatBaghdadDateTime12($rd['created_at'])) ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <p class="text-muted mb-0 text-center py-3">لا توجد أجهزة مسجلة بعد.<?php if (canEdit()): ?> <a href="devices.php">أضف جهازاً</a><?php endif; ?></p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="card dashboard-card h-100">
                                <div class="card-header bg-transparent border-0 d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0 fw-600"><i class="bi bi-exclamation-triangle text-warning me-2"></i>أقدم الأجهزة (تحتاج متابعة)</h5>
                                    <a href="maintenance_query.php" class="btn btn-sm btn-outline-warning">تفاصيل الصيانة</a>
                                </div>
                                <div class="card-body pt-2">
                                    <?php if (!empty($urgentList)): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-sm mb-0 dashboard-table">
                                            <thead><tr><th>الفاتورة</th><th>المستشفى</th><th>الجهاز</th><th>تاريخ التنصيب</th></tr></thead>
                                            <tbody>
                                            <?php foreach ($urgentList as $u): ?>
                                            <tr class="cursor-pointer" onclick="location.href='device_view.php?id=<?= $u['id'] ?>'">
                                                <td><a href="device_view.php?id=<?= $u['id'] ?>" class="text-decoration-none"><?= htmlspecialchars($u['invoice_number']) ?></a></td>
                                                <td><?= htmlspecialchars($u['hospital_name']) ?></td>
                                                <td><?= htmlspecialchars($u['device_name']) ?></td>
                                                <td class="text-muted"><?= $u['installation_date'] ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <p class="text-muted mb-0 text-center py-3">لا توجد أجهزة تحتاج متابعة</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- القائمة الجانبية -->
                <div class="col-lg-4">
                    <div class="dashboard-section-title">الوصول السريع</div>
                    <div class="card dashboard-card mb-4 dashboard-sidebar">
                        <div class="card-body">
                            <a href="hospitals.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-hospital"></i> المستشفيات
                            </a>
                            <?php if (canEdit()): ?><a href="devices.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-plus-circle"></i> إضافة جهاز
                            </a><?php endif; ?>
                            <a href="devices_list.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-list-ul"></i> قائمة الأجهزة
                            </a>
                            <a href="maintenance_query.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-calendar-check"></i> صيانة دورية
                            </a>
                            <a href="warranty.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-shield-check"></i> حالة الضمان
                            </a>
                            <a href="customers.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-people"></i> الزبائن
                            </a>
                            <hr class="my-3">
                            <small class="text-muted px-2 d-block mb-2" style="font-size:0.7rem;">الإعدادات</small>
                            <a href="engineers.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-person-badge"></i> المهندسين
                            </a>
                            <a href="companies.php" class="nav-link-pro d-block text-decoration-none mb-1">
                                <i class="bi bi-building"></i> الشركات
                            </a>
                            <a href="device_models.php" class="nav-link-pro d-block text-decoration-none">
                                <i class="bi bi-collection"></i> أسماء الأجهزة وموديلاتها
                            </a>
                        </div>
                    </div>
                    <!-- تنبيهات -->
                    <div class="card dashboard-card mb-4 dashboard-alerts">
                        <div class="card-header bg-transparent border-0 py-2">
                            <h6 class="mb-0 fw-600"><i class="bi bi-bell text-primary me-2"></i>تنبيهات</h6>
                        </div>
                        <div class="card-body py-2">
                            <?php if ($stats['maintenance_due'] > 0): ?>
                            <a href="maintenance_query.php" class="alert-item alert-item-warning d-block py-2 px-3 rounded mb-2 text-decoration-none">
                                <i class="bi bi-tools me-2"></i><strong><?= $stats['maintenance_due'] ?></strong> جهاز يحتاج صيانة
                            </a>
                            <?php endif; ?>
                            <?php if ($stats['warranty_expiring_soon'] > 0): ?>
                            <a href="warranty.php" class="alert-item alert-item-info d-block py-2 px-3 rounded mb-2 text-decoration-none">
                                <i class="bi bi-clock me-2"></i><strong><?= $stats['warranty_expiring_soon'] ?></strong> جهاز تنتهي ضمانته خلال 30 يوم
                            </a>
                            <?php endif; ?>
                            <?php if ($stats['warranty_expired'] > 0): ?>
                            <a href="warranty.php" class="alert-item alert-item-danger d-block py-2 px-3 rounded mb-2 text-decoration-none">
                                <i class="bi bi-shield-x me-2"></i><strong><?= $stats['warranty_expired'] ?></strong> جهاز منتهي الضمان
                            </a>
                            <?php endif; ?>
                            <?php if ($stats['maintenance_due'] == 0 && $stats['warranty_expiring_soon'] == 0 && $stats['warranty_expired'] == 0): ?>
                            <p class="text-muted small mb-0 py-1"><i class="bi bi-check-circle text-success me-1"></i>لا توجد تنبيهات</p>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="card dashboard-card mb-4">
                        <div class="card-header bg-transparent border-0 py-2 d-flex justify-content-between align-items-center">
                            <h6 class="mb-0 fw-600"><i class="bi bi-person-lines-fill text-primary me-2"></i>متابعة المهندسين اليوم</h6>
                            <span class="badge bg-dark"><?= $stats['engineers_total'] ?></span>
                        </div>
                        <div class="card-body py-2">
                            <div class="d-flex gap-2 mb-3 flex-wrap">
                                <span class="badge bg-success">أرسلوا اليوم: <?= $stats['engineers_sent_today'] ?></span>
                                <span class="badge bg-danger">لم يرسلوا: <?= $stats['engineers_not_sent_today'] ?></span>
                            </div>
                            <?php if (!empty($engineersNotSentToday)): ?>
                            <div class="small mb-2 text-muted">المهندسون الذين لم يرسلوا اليوم:</div>
                            <div class="d-flex flex-wrap gap-1">
                                <?php foreach ($engineersNotSentToday as $eng): ?>
                                    <a href="devices_list.php?engineer_id=<?= (int)$eng['id'] ?>" class="badge rounded-pill text-bg-warning text-decoration-none">
                                        <?= htmlspecialchars($eng['name']) ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                            <?php else: ?>
                            <div class="text-success small"><i class="bi bi-check-circle me-1"></i>كل المهندسين أرسلوا اليوم</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <!-- رسم بياني للضمان -->
                    <?php if ($stats['devices'] > 0): ?>
                    <div class="card dashboard-card dashboard-chart-card mb-4">
                        <div class="card-header bg-transparent border-0 py-2">
                            <h6 class="mb-0 fw-600"><i class="bi bi-pie-chart text-primary me-2"></i>حالة الضمان</h6>
                        </div>
                        <div class="card-body py-2">
                            <canvas id="warrantyChart" height="180"></canvas>
                        </div>
                    </div>
                    <!-- رسم الأجهزة الشهرية -->
                    <div class="card dashboard-card dashboard-chart-card">
                        <div class="card-header bg-transparent border-0 py-2">
                            <h6 class="mb-0 fw-600"><i class="bi bi-bar-chart text-primary me-2"></i>الأجهزة المضافة (6 أشهر)</h6>
                        </div>
                        <div class="card-body py-2">
                            <canvas id="monthlyChart" height="150"></canvas>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php include 'includes/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <?php if ($stats['devices'] > 0): ?>
    <script>
    new Chart(document.getElementById('warrantyChart'), {
        type: 'doughnut',
        data: {
            labels: ['داخل الضمان', 'منتهي الضمان'],
            datasets: [{
                data: [<?= $stats['warranty_active'] ?>, <?= $stats['warranty_expired'] ?>],
                backgroundColor: ['#22c55e', '#ef4444'],
                borderWidth: 3,
                borderColor: '#fff',
                hoverOffset: 8
            }]
        },
        options: {
            responsive: true,
            cutout: '65%',
            plugins: {
                legend: { position: 'bottom' }
            }
        }
    });
    new Chart(document.getElementById('monthlyChart'), {
        type: 'bar',
        data: {
            labels: [<?= implode(',', array_map(function($m) { return "'" . $m['label'] . "'"; }, $monthlyDevices)) ?>],
            datasets: [{
                label: 'أجهزة',
                data: [<?= implode(',', array_column($monthlyDevices, 'count')) ?>],
                backgroundColor: 'rgba(59, 130, 246, 0.8)',
                borderRadius: 8,
                borderSkipped: false
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { stepSize: 1 },
                    grid: { color: 'rgba(0,0,0,0.05)' }
                },
                x: { grid: { display: false } }
            }
        }
    });
    </script>
    <?php endif; ?>
</body>
</html>
