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

$filter = $_GET['status'] ?? 'all'; // all, active, expiring_soon, expired

$today = date('Y-m-d');
$plus30 = date('Y-m-d', strtotime('+30 days'));

$base = "SELECT d.*, 
    c.name as customer_name, g.name_ar as gov_name, 
    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
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";

$where = '';
switch ($filter) {
    case 'active':
        $where = " WHERE DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) > '$plus30'";
        break;
    case 'expiring_soon':
        $where = " WHERE DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) BETWEEN '$today' AND '$plus30'";
        break;
    case 'expired':
        $where = " WHERE DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) < '$today'";
        break;
}

$sql = $base . $where . " ORDER BY DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) ASC";
$result = $conn->query($sql);
if (!$result) $result = $conn->query($base . " ORDER BY DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) ASC");

$devices = [];
while ($d = $result->fetch_assoc()) {
    $warranty_end = strtotime($d['warranty_end_date']);
    $d['warranty_days_left'] = ceil(($warranty_end - time()) / 86400);
    if ($warranty_end >= time()) {
        $d['warranty_status'] = $d['warranty_days_left'] <= 30 ? 'expiring_soon' : 'active';
    } else {
        $d['warranty_status'] = 'expired';
    }
    $devices[] = $d;
}

// إحصائيات
$stats = [
    'active' => $conn->query("SELECT COUNT(*) c FROM devices WHERE DATE_ADD(installation_date, INTERVAL warranty_months MONTH) > DATE_ADD(CURDATE(), INTERVAL 30 DAY)")->fetch_assoc()['c'],
    'expiring_soon' => $conn->query("SELECT COUNT(*) c FROM devices WHERE DATE_ADD(installation_date, INTERVAL warranty_months MONTH) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)")->fetch_assoc()['c'],
    'expired' => $conn->query("SELECT COUNT(*) c FROM devices WHERE DATE_ADD(installation_date, INTERVAL warranty_months MONTH) < CURDATE()")->fetch_assoc()['c'],
];
?>
<!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">
    <style>
        .warranty-stat-card { border-radius: 16px; transition: transform 0.2s; }
        .warranty-stat-card:hover { transform: translateY(-2px); }
        .warranty-stat-card.stat-active { background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%); border: 1px solid #86efac; }
        .warranty-stat-card.stat-expiring { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #fcd34d; }
        .warranty-stat-card.stat-expired { background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); border: 1px solid #fca5a5; }
        .filter-tabs .nav-link { border-radius: 10px; font-weight: 500; padding: 0.5rem 1rem; }
        .filter-tabs .nav-link.active { background: #0f172a; color: #fff !important; }
        .filter-tabs .nav-link:not(.active) { color: #475569; }
        .filter-tabs .nav-link:not(.active):hover { background: #f1f5f9; }
        .warranty-badge-active { background: #22c55e; color: #fff; }
        .warranty-badge-expiring { background: #f59e0b; color: #fff; }
        .warranty-badge-expired { background: #ef4444; color: #fff; }
        .warranty-table .table { margin-bottom: 0; }
        .warranty-table thead th { font-size: 0.85rem; white-space: nowrap; }
    </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">الأجهزة حسب حالة الضمان</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-shield-check me-2"></i>الأجهزة حسب حالة الضمان</h2>
                <div class="d-flex gap-2">
                    <?php if (canExport()): ?><a href="export.php?type=warranty" class="btn btn-success btn-sm"><i class="bi bi-file-excel me-1"></i> تصدير Excel</a><?php endif; ?>
                    <button onclick="printPDF()" class="btn btn-primary btn-sm"><i class="bi bi-file-pdf me-1"></i> تصدير PDF</button>
                </div>
            </div>

            <!-- بطاقات الإحصائيات -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-4">
                    <a href="?status=active" class="text-decoration-none">
                    <div class="card warranty-stat-card stat-active h-100">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="rounded-circle bg-success bg-opacity-25 p-3">
                                <i class="bi bi-shield-check text-success fs-4"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats['active'] ?></h3>
                                <small class="text-success fw-600">داخل الضمان</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4">
                    <a href="?status=expiring_soon" class="text-decoration-none">
                    <div class="card warranty-stat-card stat-expiring 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['expiring_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=expired" class="text-decoration-none">
                    <div class="card warranty-stat-card stat-expired 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-shield-x text-danger fs-4"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats['expired'] ?></h3>
                                <small class="text-danger fw-600">منتهي الضمان</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
            </div>

            <!-- فلاتر التبويبات -->
            <ul class="nav 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['active'] + $stats['expiring_soon'] + $stats['expired'] ?>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $filter === 'active' ? 'active' : '' ?>" href="?status=active">
                        <i class="bi bi-shield-check me-1"></i> داخل الضمان (<?= $stats['active'] ?>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $filter === 'expiring_soon' ? 'active' : '' ?>" href="?status=expiring_soon">
                        <i class="bi bi-clock me-1"></i> تنتهي قريباً (<?= $stats['expiring_soon'] ?>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $filter === 'expired' ? 'active' : '' ?>" href="?status=expired">
                        <i class="bi bi-shield-x me-1"></i> منتهي (<?= $stats['expired'] ?>)
                    </a>
                </li>
            </ul>

            <!-- الجدول -->
            <div class="card warranty-table">
                <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'=>'الكل', 'active'=>'داخل الضمان', 'expiring_soon'=>'تنتهي قريباً', 'expired'=>'منتهي'];
                        echo 'عرض: ' . ($labels[$filter] ?? 'الكل');
                        ?>
                    </span>
                    <input type="text" id="warrantySearch" 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="warrantyTable">
                        <thead class="table-light">
                            <tr>
                                <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): 
                            $badgeClass = 'warranty-badge-' . $d['warranty_status'];
                            $statusText = $d['warranty_status'] === 'active' ? 'متبقي ' . $d['warranty_days_left'] . ' يوم' : ($d['warranty_status'] === 'expiring_soon' ? 'تنتهي خلال ' . $d['warranty_days_left'] . ' يوم' : 'منتهي');
                        ?>
                        <tr class="align-middle" data-search="<?= htmlspecialchars($d['invoice_number'].' '.$d['customer_name'].' '.$d['hospital_name'].' '.$d['device_name']) ?>">
                            <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['device_name']) ?></td>
                            <td><?= htmlspecialchars($d['model_name']) ?></td>
                            <td><?= $d['installation_date'] ?></td>
                            <td><?= $d['warranty_end_date'] ?></td>
                            <td>
                                <span class="badge <?= $badgeClass ?>"><?= $statusText ?></span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($devices)): ?>
                        <tr>
                            <td colspan="9" class="text-center text-muted py-5">
                                <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                                لا توجد أجهزة في هذه الفئة
                            </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 src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
    document.getElementById('warrantySearch')?.addEventListener('input', function() {
        const q = this.value.toLowerCase();
        document.querySelectorAll('#warrantyTable tbody tr').forEach(tr => {
            if (tr.cells.length < 2) return;
            const txt = (tr.dataset.search || '').toLowerCase();
            tr.style.display = txt.includes(q) ? '' : 'none';
        });
    });
    function printPDF() {
        const opt = {
            margin: 10,
            filename: 'warranty_report_' + new Date().toISOString().slice(0,10) + '.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: { scale: 2 },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' }
        };
        const el = document.getElementById('warrantyTable').closest('.card');
        html2pdf().set(opt).from(el).save();
    }
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
