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

$filter = $_GET['status'] ?? 'all'; // all, overdue, due_soon

$sql = "SELECT d.*, 
    c.name as customer_name, g.name_ar as gov_name, c.phone as phone,
    dn.name as device_name, dm.model_name, co.name as company_name, e.name as engineer_name,
    DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) as warranty_end_date,
    (SELECT MAX(jsi.created_at) FROM job_sheet_images jsi WHERE jsi.device_id = d.id) as last_maintenance
FROM devices d
JOIN customers c ON d.customer_id = c.id
JOIN governorates g ON d.governorate_id = g.id
JOIN device_names dn ON d.device_name_id = dn.id
JOIN device_models dm ON d.device_model_id = dm.id
JOIN companies co ON d.company_id = co.id
JOIN engineers e ON d.engineer_id = e.id
ORDER BY d.installation_date ASC";

$result = $conn->query($sql);
$three_months = 90 * 86400; // ثواني
$two_months_half = 75 * 86400; // ~2.5 شهر - ستستحق خلال 30 يوم
$today_ts = time();

$devices_all = [];
$overdue = [];
$due_soon = [];

while ($d = $result->fetch_assoc()) {
    $last_ts = $d['last_maintenance'] ? strtotime($d['last_maintenance']) : strtotime($d['installation_date']);
    $days_since = floor(($today_ts - $last_ts) / 86400);
    $d['days_since_maintenance'] = $days_since;
    $d['last_maintenance_display'] = $d['last_maintenance'] ? date('Y-m-d', strtotime($d['last_maintenance'])) : 'لم تُجرَ بعد';
    
    if ($days_since >= 90) {
        $d['maintenance_status'] = 'overdue';
        $d['days_overdue'] = $days_since - 90;
        $overdue[] = $d;
    } elseif ($days_since >= 60) {
        $d['maintenance_status'] = 'due_soon';
        $d['days_until_due'] = 90 - $days_since;
        $due_soon[] = $d;
    }
}

$devices_all = array_merge($overdue, $due_soon);
usort($devices_all, function($a, $b) { return $b['days_since_maintenance'] - $a['days_since_maintenance']; });

switch ($filter) {
    case 'overdue':
        $devices = $overdue;
        usort($devices, function($a, $b) { return $b['days_overdue'] - $a['days_overdue']; });
        break;
    case 'due_soon':
        $devices = $due_soon;
        usort($devices, function($a, $b) { return $a['days_until_due'] - $b['days_until_due']; });
        break;
    default:
        $devices = $devices_all;
}

$stats = [
    'overdue' => count($overdue),
    'due_soon' => count($due_soon),
    'total' => count($devices_all),
];
?>
<!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>صيانة دورية كل 3 أشهر - نظام صيانة</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">
    <style>
        .maint-stat-card { border-radius: 16px; transition: transform 0.2s; }
        .maint-stat-card:hover { transform: translateY(-2px); }
        .maint-stat-card.stat-overdue { background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); border: 1px solid #fca5a5; }
        .maint-stat-card.stat-due-soon { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #fcd34d; }
        .maint-filter-tabs .nav-link { border-radius: 10px; font-weight: 500; padding: 0.5rem 1rem; }
        .maint-filter-tabs .nav-link.active { background: #0f172a; color: #fff !important; }
        .maint-filter-tabs .nav-link:not(.active) { color: #475569; }
        .maint-filter-tabs .nav-link:not(.active):hover { background: #f1f5f9; }
        .badge-overdue { background: #ef4444; color: #fff; }
        .badge-due-soon { background: #f59e0b; color: #fff; }
        .days-badge { font-size: 0.8rem; min-width: 85px; }
    </style>
</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"><a href="dashboard.php">الرئيسية</a></li>
                    <li class="breadcrumb-item active" aria-current="page">صيانة دورية كل 3 أشهر</li>
                </ol>
            </nav>

            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
                <h2 class="page-title mb-0"><i class="bi bi-tools me-2"></i>الأجهزة التي تستحق صيانة كل 3 أشهر</h2>
                <div class="d-flex gap-2">
                    <?php if (canExport()): ?><a href="export.php?type=maintenance" class="btn btn-success btn-sm"><i class="bi bi-file-excel me-1"></i> تصدير Excel</a><?php endif; ?>
                    <button onclick="window.print()" class="btn btn-primary btn-sm"><i class="bi bi-printer me-1"></i> طباعة</button>
                </div>
            </div>

            <!-- بطاقات الإحصائيات -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-4">
                    <a href="?status=overdue" class="text-decoration-none">
                    <div class="card maint-stat-card stat-overdue h-100">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="rounded-circle bg-danger bg-opacity-25 p-3">
                                <i class="bi bi-exclamation-triangle text-danger fs-4"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats['overdue'] ?></h3>
                                <small class="text-danger fw-600">متأخرة عن الصيانة</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4">
                    <a href="?status=due_soon" class="text-decoration-none">
                    <div class="card maint-stat-card stat-due-soon h-100">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="rounded-circle bg-warning bg-opacity-25 p-3">
                                <i class="bi bi-clock-history text-warning fs-4"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats['due_soon'] ?></h3>
                                <small class="fw-600" style="color:#b45309">ستستحق خلال 30 يوم</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4">
                    <a href="?status=all" class="text-decoration-none">
                    <div class="card maint-stat-card h-100" style="background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%); border: 1px solid #93c5fd;">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="rounded-circle bg-primary bg-opacity-25 p-3">
                                <i class="bi bi-tools text-primary fs-4"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats['total'] ?></h3>
                                <small class="text-primary fw-600">إجمالي المستحقة</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
            </div>

            <!-- فلاتر -->
            <ul class="nav maint-filter-tabs gap-2 mb-3">
                <li class="nav-item">
                    <a class="nav-link <?= $filter === 'all' ? 'active' : '' ?>" href="?status=all">
                        <i class="bi bi-grid-3x3-gap me-1"></i> الكل (<?= $stats['total'] ?>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $filter === 'overdue' ? 'active' : '' ?>" href="?status=overdue">
                        <i class="bi bi-exclamation-triangle me-1"></i> متأخرة (<?= $stats['overdue'] ?>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $filter === 'due_soon' ? 'active' : '' ?>" href="?status=due_soon">
                        <i class="bi bi-clock me-1"></i> ستستحق قريباً (<?= $stats['due_soon'] ?>)
                    </a>
                </li>
            </ul>

            <!-- الجدول -->
            <div class="card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2 py-3">
                    <span class="text-muted small">
                        <?php
                        $labels = ['all'=>'الكل', 'overdue'=>'متأخرة عن الصيانة', 'due_soon'=>'ستستحق خلال 30 يوم'];
                        echo 'عرض: ' . ($labels[$filter] ?? 'الكل');
                        ?>
                    </span>
                    <input type="text" id="maintenanceSearch" class="form-control form-control-sm" placeholder="بحث (فاتورة، زبون، مستشفى، جهاز)..." style="max-width: 280px;">
                </div>
                <div class="card-body p-0 overflow-auto" style="max-height: 60vh;">
                    <table class="table table-hover mb-0" id="maintenanceTable">
                        <thead class="table-light">
                            <tr>
                                <th>#</th><th>رقم الفاتورة</th><th>الزبون</th><th>المستشفى</th><th>الهاتف</th>
                                <th>الجهاز</th><th>الموديل</th><th>آخر صيانة</th><th>مضى</th><th>الحالة</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($devices as $d): 
                            $searchText = $d['invoice_number'].' '.$d['customer_name'].' '.$d['hospital_name'].' '.$d['device_name'];
                            if ($d['maintenance_status'] === 'overdue') {
                                $statusBadge = '<span class="badge badge-overdue days-badge">متأخر ' . $d['days_overdue'] . ' يوم</span>';
                            } else {
                                $statusBadge = '<span class="badge badge-due-soon days-badge">خلال ' . $d['days_until_due'] . ' يوم</span>';
                            }
                        ?>
                        <tr class="align-middle" data-search="<?= htmlspecialchars($searchText) ?>">
                            <td><?= $d['id'] ?></td>
                            <td>
                                <a href="device_view.php?id=<?= $d['id'] ?>" class="text-decoration-none fw-500"><?= htmlspecialchars($d['invoice_number']) ?></a>
                            </td>
                            <td><?= htmlspecialchars($d['customer_name']) ?></td>
                            <td><?= htmlspecialchars($d['hospital_name']) ?></td>
                            <td><?= htmlspecialchars($d['phone'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($d['device_name']) ?></td>
                            <td><?= htmlspecialchars($d['model_name']) ?></td>
                            <td><?= $d['last_maintenance_display'] ?></td>
                            <td><?= $d['days_since_maintenance'] ?> يوم</td>
                            <td><?= $statusBadge ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($devices)): ?>
                        <tr>
                            <td colspan="10" class="text-center text-muted py-5">
                                <i class="bi bi-check-circle fs-1 text-success d-block mb-2"></i>
                                لا توجد أجهزة مستحقة للصيانة حالياً
                                <p class="small mt-2 mb-0">جميع الأجهزة تمت صيانتها خلال الأشهر الثلاثة الماضية</p>
                            </td>
                        </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    document.getElementById('maintenanceSearch')?.addEventListener('input', function() {
        const q = this.value.toLowerCase();
        document.querySelectorAll('#maintenanceTable tbody tr').forEach(tr => {
            if (tr.cells.length < 2) return;
            const txt = (tr.dataset.search || '').toLowerCase();
            tr.style.display = txt.includes(q) ? '' : 'none';
        });
    });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
