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

$id = (int)($_GET['id'] ?? 0);
if (!$id) {
    header('Location: devices_list.php');
    exit;
}

$stmt = $conn->prepare("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
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 d.id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$d = $stmt->get_result()->fetch_assoc();

if (!$d) {
    header('Location: devices_list.php');
    exit;
}

$serials = [];
$sq = $conn->prepare("SELECT serial_number FROM device_serials WHERE device_id = ?");
$sq->bind_param("i", $id);
$sq->execute();
$sqRes = $sq->get_result();
while ($s = $sqRes->fetch_assoc()) $serials[] = $s['serial_number'];

$images = [];
$iq = $conn->prepare("SELECT image_path, created_at FROM job_sheet_images WHERE device_id = ? ORDER BY created_at DESC");
$iq->bind_param("i", $id);
$iq->execute();
$iqRes = $iq->get_result();
while ($img = $iqRes->fetch_assoc()) $images[] = $img;

$warrantyExpired = $d['warranty_end'] && strtotime($d['warranty_end']) < time();
$visitType = trim((string)($d['visit_type'] ?? ''));
$visitTypeMap = [
    'صيانة' => 'صيانة',
    'تنصيب' => 'تنصيب',
    'صيانة دورية' => 'صيانة دورية',
    'تدريب' => 'تدريب'
];
$createdAtFormatted = '-';
if (!empty($d['created_at'])) {
    try {
        $dt = new DateTime($d['created_at'], new DateTimeZone('Asia/Baghdad'));
        $dt->setTimezone(new DateTimeZone('Asia/Baghdad'));
        $period = ((int)$dt->format('H') < 12) ? 'ص' : 'م';
        $createdAtFormatted = $dt->format('Y-m-d h:i:s') . ' ' . $period;
    } catch (Exception $e) {
        $createdAtFormatted = $d['created_at'];
    }
}
?>
<!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>تفاصيل الجهاز #<?= $id ?> - نظام صيانة</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">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid py-4">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4">
                <div>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-1">
                            <li class="breadcrumb-item"><a href="devices_list.php">الأجهزة</a></li>
                            <li class="breadcrumb-item active">جهاز #<?= $id ?></li>
                        </ol>
                    </nav>
                    <h2 class="page-title mb-0"><i class="bi bi-cpu"></i> <?= htmlspecialchars($d['device_name']) ?> - <?= htmlspecialchars($d['invoice_number']) ?></h2>
                </div>
                <div class="d-flex gap-2">
                    <a href="devices_list.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-right"></i> رجوع</a>
                    <?php if (canExport()): ?><a href="export.php?type=all" class="btn btn-success btn-sm"><i class="bi bi-file-excel"></i> تصدير</a><?php endif; ?>
                </div>
            </div>
            
            <div class="row g-4">
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-header <?= $warrantyExpired ? 'bg-danger' : 'bg-success' ?> text-white">
                            <h5 class="mb-0"><i class="bi bi-info-circle"></i> معلومات الجهاز</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-borderless mb-0">
                                <tr><td class="text-muted" width="40%">رقم الفاتورة</td><td><?= htmlspecialchars($d['invoice_number']) ?></td></tr>
                                <tr><td class="text-muted">الزبون</td><td><?= htmlspecialchars($d['customer_name']) ?></td></tr>
                                <tr><td class="text-muted">المستشفى</td><td><?= htmlspecialchars($d['hospital_name']) ?></td></tr>
                                <tr><td class="text-muted">الهاتف</td><td><?= htmlspecialchars($d['phone']) ?></td></tr>
                                <tr><td class="text-muted">المحافظة</td><td><?= htmlspecialchars($d['gov_name']) ?></td></tr>
                                <tr><td class="text-muted">الجهاز</td><td><?= htmlspecialchars($d['device_name']) ?></td></tr>
                                <tr><td class="text-muted">الموديل</td><td><?= htmlspecialchars($d['model_name']) ?></td></tr>
                                <tr><td class="text-muted">الشركة</td><td><?= htmlspecialchars($d['company_name']) ?></td></tr>
                                <tr><td class="text-muted">العدد</td><td><?= $d['quantity'] ?></td></tr>
                                <tr><td class="text-muted">الأرقام التسلسلية</td><td><?= implode('، ', $serials) ?: '-' ?></td></tr>
                                <tr><td class="text-muted">تاريخ التنصيب</td><td><?= $d['installation_date'] ?></td></tr>
                                <tr><td class="text-muted">فترة الضمان</td><td><?= $d['warranty_months'] ?> شهر</td></tr>
                                <tr><td class="text-muted">نهاية الضمان</td><td><span class="badge bg-<?= $warrantyExpired ? 'danger' : 'success' ?>"><?= $d['warranty_end'] ?></span></td></tr>
                                <tr><td class="text-muted">المهندس</td><td><?= htmlspecialchars($d['engineer_name']) ?></td></tr>
                                <tr>
                                    <td class="text-muted">تفاصيل الزيارة</td>
                                    <td><?= htmlspecialchars($visitTypeMap[$visitType] ?? ($visitType !== '' ? $visitType : '-')) ?></td>
                                </tr>
                                <tr><td class="text-muted">تاريخ التسجيل</td><td dir="ltr"><?= htmlspecialchars($createdAtFormatted) ?></td></tr>
                                <?php if (!empty($d['notes'])): ?>
                                <tr><td class="text-muted">الملاحظات</td><td><?= nl2br(htmlspecialchars($d['notes'])) ?></td></tr>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="bi bi-image"></i> صور الجوب شيت</h5>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($images)): ?>
                            <div class="row g-2">
                                <?php foreach ($images as $img): 
                                    $imgPath = 'uploads/' . $img['image_path'];
                                ?>
                                <div class="col-6">
                                    <a href="<?= $imgPath ?>" target="_blank" class="d-block">
                                        <img src="<?= $imgPath ?>" alt="جوب شيت" class="img-fluid rounded border" style="max-height: 150px; object-fit: cover;">
                                    </a>
                                    <small class="text-muted"><?= date('Y-m-d', strtotime($img['created_at'])) ?></small>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php else: ?>
                            <p class="text-muted mb-0">لا توجد صور مرفقة</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </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>
</body>
</html>
