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

$success = '';
$error = '';

if (isset($_GET['imported'])) {
    $imp = (int)$_GET['imported'];
    $skip = (int)($_GET['skipped'] ?? 0);
    $success = "تم استيراد $imp جهاز بنجاح" . ($skip > 0 ? " وتخطي $skip (مكرر أو خطأ)" : "");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['import_file']['name']) && isset($_POST['action']) && $_POST['action'] === 'import_devices') {
    if (function_exists('require_csrf')) require_csrf();
    if (!canEdit()) { header('Location: devices_list.php'); exit; }
    $ext = strtolower(pathinfo($_FILES['import_file']['name'], PATHINFO_EXTENSION));
    $allowed = ['xlsx', 'xls', 'csv'];
    if (!in_array($ext, $allowed)) {
        $error = 'صيغة الملف غير مدعومة. استخدم xlsx أو xls أو csv';
    } elseif ($_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
        $error = 'فشل رفع الملف';
    } else {
        $tmp = $_FILES['import_file']['tmp_name'];
        $govMap = []; $r = $conn->query("SELECT id, name_ar FROM governorates");
        while ($row = $r->fetch_assoc()) $govMap[trim($row['name_ar'])] = $row['id'];
        $engMap = []; $r = $conn->query("SELECT id, name FROM engineers");
        while ($row = $r->fetch_assoc()) $engMap[trim($row['name'])] = $row['id'];
        $nameMap = []; $r = $conn->query("SELECT id, name FROM device_names");
        while ($row = $r->fetch_assoc()) $nameMap[$row['name']] = $row['id'];
        $compMap = []; $r = $conn->query("SELECT id, name FROM companies");
        while ($row = $r->fetch_assoc()) $compMap[$row['name']] = $row['id'];
        $modelCache = [];
        $r = $conn->query("SELECT dm.id, dm.device_name_id, dm.company_id, dm.model_name, dn.name as dn, c.name as cn FROM device_models dm JOIN device_names dn ON dm.device_name_id = dn.id JOIN companies c ON dm.company_id = c.id");
        while ($row = $r->fetch_assoc()) {
            $modelCache[trim($row['dn']) . '|' . trim($row['cn']) . '|' . trim($row['model_name'])] = $row['id'];
        }
        $custCache = [];
        $r = $conn->query("SELECT id, name, hospital_name FROM customers");
        while ($row = $r->fetch_assoc()) {
            $custCache[trim($row['name']) . '|' . trim($row['hospital_name'] ?? '')] = $row['id'];
        }
        $imported = 0;
        $skipped = 0;
        $seenInvoice = [];
        $defGovId = $conn->query("SELECT id FROM governorates LIMIT 1")->fetch_assoc()['id'] ?? null;
        $processRow = function($invoice, $custName, $hospital, $phone, $govName, $devName, $modName, $compName, $qty, $instDate, $warr, $engName, $notes) use ($conn, $govMap, $engMap, &$nameMap, &$compMap, &$modelCache, &$custCache, &$imported, &$skipped, &$seenInvoice, $defGovId) {
            $invoice = trim((string)$invoice);
            $custName = trim((string)$custName);
            $hospital = trim((string)$hospital);
            $phone = trim((string)$phone) ?: '07000000000';
            $govName = trim((string)$govName);
            $devName = trim((string)$devName);
            $modName = trim((string)$modName);
            $compName = trim((string)$compName);
            $engName = trim((string)$engName);
            $notes = trim((string)$notes);
            if (empty($invoice) || empty($custName) || empty($hospital) || empty($devName) || empty($modName) || empty($compName) || empty($instDate) || empty($engName)) return;
            $engId = $engMap[$engName] ?? null;
            if (!$engId) { $skipped++; return; }
            $govId = $govMap[$govName] ?? $defGovId;
            if (!$govId) { $skipped++; return; }
            $custKey = $custName . '|' . $hospital;
            $custId = $custCache[$custKey] ?? null;
            if (!$custId) {
                if ($govId) {
                    $stmt = $conn->prepare("INSERT INTO customers (name, hospital_name, phone, governorate_id) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("sssi", $custName, $hospital, $phone, $govId);
                } else {
                    $stmt = $conn->prepare("INSERT INTO customers (name, hospital_name, phone, governorate_id) VALUES (?, ?, ?, NULL)");
                    $stmt->bind_param("sss", $custName, $hospital, $phone);
                }
                if ($stmt->execute()) {
                    $custId = $conn->insert_id;
                    $custCache[$custKey] = $custId;
                } else { $skipped++; return; }
            }
            $dnId = $nameMap[$devName] ?? null;
            if (!$dnId) {
                $st = $conn->prepare("INSERT IGNORE INTO device_names (name) VALUES (?)");
                $st->bind_param("s", $devName);
                $st->execute();
                $dnId = $conn->insert_id;
                if (!$dnId) { $r2 = $conn->prepare("SELECT id FROM device_names WHERE name = ?"); $r2->bind_param("s", $devName); $r2->execute(); $row2 = $r2->get_result()->fetch_assoc(); $dnId = $row2['id'] ?? null; }
                if ($dnId) $nameMap[$devName] = $dnId;
            }
            $coId = $compMap[$compName] ?? null;
            if (!$coId) {
                $st = $conn->prepare("INSERT IGNORE INTO companies (name) VALUES (?)");
                $st->bind_param("s", $compName);
                $st->execute();
                $coId = $conn->insert_id;
                if (!$coId) { $r2 = $conn->prepare("SELECT id FROM companies WHERE name = ?"); $r2->bind_param("s", $compName); $r2->execute(); $row2 = $r2->get_result()->fetch_assoc(); $coId = $row2['id'] ?? null; }
                if ($coId) $compMap[$compName] = $coId;
            }
            if (!$dnId || !$coId) { $skipped++; return; }
            $modKey = $devName . '|' . $compName . '|' . $modName;
            $modId = $modelCache[$modKey] ?? null;
            if (!$modId) {
                $st = $conn->prepare("INSERT IGNORE INTO device_models (device_name_id, company_id, model_name) VALUES (?, ?, ?)");
                $st->bind_param("iis", $dnId, $coId, $modName);
                $st->execute();
                $modId = $conn->insert_id;
                if (!$modId) { $r2 = $conn->prepare("SELECT id FROM device_models WHERE device_name_id=? AND company_id=? AND model_name=?"); $r2->bind_param("iis", $dnId, $coId, $modName); $r2->execute(); $row2 = $r2->get_result()->fetch_assoc(); $modId = $row2['id'] ?? null; }
                if ($modId) $modelCache[$modKey] = $modId;
            }
            if (!$modId) { $skipped++; return; }
            $dupKey = $invoice . '|' . $custId . '|' . $modId . '|' . $instDate;
            if (isset($seenInvoice[$dupKey])) { $skipped++; return; }
            $qty = max(1, (int)$qty);
            $warr = max(1, (int)$warr);
            if (is_numeric($instDate) && $instDate > 10000) {
                $instDate = date('Y-m-d', (int)(($instDate - 25569) * 86400));
            } else {
                $instDate = date('Y-m-d', strtotime($instDate));
            }
            if (!$instDate || $instDate === '1970-01-01') { $skipped++; return; }
            $stmt = $conn->prepare("INSERT INTO devices (invoice_number, customer_id, hospital_name, phone, governorate_id, device_name_id, device_model_id, company_id, quantity, installation_date, warranty_months, engineer_id, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sisiiiiiiisis", $invoice, $custId, $hospital, $phone, $govId, $dnId, $modId, $coId, $qty, $instDate, $warr, $engId, $notes);
            if ($stmt->execute()) {
                $imported++;
                $seenInvoice[$dupKey] = 1;
                if (function_exists('logActivity')) logActivity('add', 'devices', $conn->insert_id, $invoice . ' - ' . $hospital . ' (استيراد)');
            } else $skipped++;
        };
        if ($ext === 'csv') {
            $handle = fopen($tmp, 'r');
            if ($handle) {
                $bom = fread($handle, 3);
                if ($bom !== chr(0xEF).chr(0xBB).chr(0xBF)) rewind($handle);
                $header = fgetcsv($handle);
                $cols = ['invoice'=>1,'cust'=>2,'hosp'=>3,'phone'=>4,'gov'=>5,'dev'=>6,'mod'=>7,'comp'=>8,'qty'=>9,'inst'=>10,'warr'=>11,'eng'=>12,'notes'=>13];
                if ($header && count($header) >= 6) {
                    foreach ($header as $i => $h) {
                        $h = (string)$h;
                        if (stripos($h,'فاتور')!==false) $cols['invoice']=$i;
                        elseif (stripos($h,'زبون')!==false) $cols['cust']=$i;
                        elseif (stripos($h,'مستشفى')!==false) $cols['hosp']=$i;
                        elseif (stripos($h,'هاتف')!==false) $cols['phone']=$i;
                        elseif (stripos($h,'محافظ')!==false) $cols['gov']=$i;
                        elseif (stripos($h,'جهاز')!==false && stripos($h,'موديل')===false) $cols['dev']=$i;
                        elseif (stripos($h,'موديل')!==false) $cols['mod']=$i;
                        elseif (stripos($h,'شركة')!==false) $cols['comp']=$i;
                        elseif (stripos($h,'عدد')!==false||stripos($h,'العدد')!==false) $cols['qty']=$i;
                        elseif (stripos($h,'تنصيب')!==false) $cols['inst']=$i;
                        elseif (stripos($h,'ضمان')!==false) $cols['warr']=$i;
                        elseif (stripos($h,'مهندس')!==false) $cols['eng']=$i;
                        elseif (stripos($h,'ملاحظ')!==false) $cols['notes']=$i;
                    }
                }
                while (($row = fgetcsv($handle)) !== false) {
                    $processRow(
                        $row[$cols['invoice']]??$row[1]??'',
                        $row[$cols['cust']]??$row[2]??'',
                        $row[$cols['hosp']]??$row[3]??'',
                        $row[$cols['phone']]??$row[4]??'',
                        $row[$cols['gov']]??$row[5]??'',
                        $row[$cols['dev']]??$row[6]??'',
                        $row[$cols['mod']]??$row[7]??'',
                        $row[$cols['comp']]??$row[8]??'',
                        $row[$cols['qty']]??$row[9]??1,
                        $row[$cols['inst']]??$row[10]??'',
                        $row[$cols['warr']]??$row[11]??12,
                        $row[$cols['eng']]??$row[12]??'',
                        $row[$cols['notes']]??$row[13]??''
                    );
                }
                fclose($handle);
            }
        } else {
            if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
                $error = 'مكتبة Excel غير متوفرة. استخدم ملف CSV للاستيراد.';
            } else {
                require_once __DIR__ . '/vendor/autoload.php';
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($ext === 'xlsx' ? 'Xlsx' : 'Xls');
                $spreadsheet = $reader->load($tmp);
                $sheet = $spreadsheet->getActiveSheet();
                $rows = $sheet->toArray();
                $cols = ['invoice'=>1,'cust'=>2,'hosp'=>3,'phone'=>4,'gov'=>5,'dev'=>6,'mod'=>7,'comp'=>8,'qty'=>9,'inst'=>10,'warr'=>11,'eng'=>12,'notes'=>13];
                if (!empty($rows[0]) && count($rows[0]) >= 6) {
                    foreach ($rows[0] as $i => $h) {
                        $h = is_string($h) ? $h : '';
                        if (stripos($h,'فاتور')!==false) $cols['invoice']=$i;
                        elseif (stripos($h,'زبون')!==false) $cols['cust']=$i;
                        elseif (stripos($h,'مستشفى')!==false) $cols['hosp']=$i;
                        elseif (stripos($h,'هاتف')!==false) $cols['phone']=$i;
                        elseif (stripos($h,'محافظ')!==false) $cols['gov']=$i;
                        elseif (stripos($h,'جهاز')!==false && stripos($h,'موديل')===false) $cols['dev']=$i;
                        elseif (stripos($h,'موديل')!==false) $cols['mod']=$i;
                        elseif (stripos($h,'شركة')!==false) $cols['comp']=$i;
                        elseif (stripos($h,'عدد')!==false||stripos($h,'العدد')!==false) $cols['qty']=$i;
                        elseif (stripos($h,'تنصيب')!==false) $cols['inst']=$i;
                        elseif (stripos($h,'ضمان')!==false) $cols['warr']=$i;
                        elseif (stripos($h,'مهندس')!==false) $cols['eng']=$i;
                        elseif (stripos($h,'ملاحظ')!==false) $cols['notes']=$i;
                    }
                }
                for ($i = 1; $i < count($rows); $i++) {
                    $row = $rows[$i] ?? [];
                    $processRow(
                        $row[$cols['invoice']]??$row[1]??'',
                        $row[$cols['cust']]??$row[2]??'',
                        $row[$cols['hosp']]??$row[3]??'',
                        $row[$cols['phone']]??$row[4]??'',
                        $row[$cols['gov']]??$row[5]??'',
                        $row[$cols['dev']]??$row[6]??'',
                        $row[$cols['mod']]??$row[7]??'',
                        $row[$cols['comp']]??$row[8]??'',
                        $row[$cols['qty']]??$row[9]??1,
                        $row[$cols['inst']]??$row[10]??'',
                        $row[$cols['warr']]??$row[11]??12,
                        $row[$cols['eng']]??$row[12]??'',
                        $row[$cols['notes']]??$row[13]??''
                    );
                }
            }
        }
        if (empty($error)) {
            header('Location: devices_list.php?imported=' . $imported . '&skipped=' . $skipped);
            exit;
        }
    }
}

$search = trim($_GET['q'] ?? '');
$customer_id = (int)($_GET['customer_id'] ?? 0);
$engineer_id = (int)($_GET['engineer_id'] ?? 0);
$company_id = (int)($_GET['company_id'] ?? 0);
$device_name_id = (int)($_GET['device_name_id'] ?? 0);
$device_model_id = (int)($_GET['device_model_id'] ?? 0);
$visit_type = trim($_GET['visit_type'] ?? '');
$created_range = trim($_GET['created_range'] ?? ''); // all, today, week, month
$created_from = trim($_GET['created_from'] ?? '');
$created_to = trim($_GET['created_to'] ?? '');
$filter = $_GET['status'] ?? 'all'; // all, warranty_active, warranty_expired, maintenance_due
$sort = $_GET['sort'] ?? 'newest'; // newest, oldest, warranty_asc, warranty_desc
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

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

$where = " WHERE 1=1";
$params = [];
$types = '';
$visit_type_options = ['صيانة', 'تنصيب', 'صيانة دورية', 'تدريب'];
$chk_visit_filter = @$conn->query("SHOW COLUMNS FROM devices LIKE 'visit_type'");
$has_visit_col_filter = ($chk_visit_filter && $chk_visit_filter->num_rows > 0);

if ($customer_id) {
    $where .= " AND d.customer_id = ?";
    $params[] = $customer_id;
    $types .= "i";
}
if ($engineer_id) {
    $where .= " AND d.engineer_id = ?";
    $params[] = $engineer_id;
    $types .= "i";
}
if ($company_id) {
    $where .= " AND d.company_id = ?";
    $params[] = $company_id;
    $types .= "i";
}
if ($device_name_id) {
    $where .= " AND d.device_name_id = ?";
    $params[] = $device_name_id;
    $types .= "i";
}
if ($device_model_id) {
    $where .= " AND d.device_model_id = ?";
    $params[] = $device_model_id;
    $types .= "i";
}
if ($visit_type !== '' && in_array($visit_type, $visit_type_options, true) && $has_visit_col_filter) {
    $where .= " AND d.visit_type = ?";
    $params[] = $visit_type;
    $types .= "s";
}
// فلترة التاريخ: إذا تم اختيار "من/إلى" يأخذ أولوية على الأزرار السريعة
$valid_from = preg_match('/^\d{4}-\d{2}-\d{2}$/', $created_from) ? $created_from : '';
$valid_to = preg_match('/^\d{4}-\d{2}-\d{2}$/', $created_to) ? $created_to : '';
if ($valid_from !== '' || $valid_to !== '') {
    if ($valid_from !== '') {
        $where .= " AND DATE(d.created_at) >= ?";
        $params[] = $valid_from;
        $types .= "s";
    }
    if ($valid_to !== '') {
        $where .= " AND DATE(d.created_at) <= ?";
        $params[] = $valid_to;
        $types .= "s";
    }
} elseif ($created_range === 'today') {
    $where .= " AND DATE(d.created_at) = CURDATE()";
} elseif ($created_range === 'week') {
    $where .= " AND DATE(d.created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
} elseif ($created_range === 'month') {
    $where .= " AND DATE(d.created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
}
if ($search) {
    $where .= " AND (d.invoice_number LIKE ? OR c.name LIKE ? OR d.hospital_name LIKE ? OR dn.name LIKE ?)";
    $s = "%$search%";
    $params = array_merge($params, [$s, $s, $s, $s]);
    $types .= "ssss";
}

// فلترة حسب الحالة
switch ($filter) {
    case 'warranty_active':
        $where .= " AND DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) > DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
        break;
    case 'warranty_expired':
        $where .= " AND DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) < CURDATE()";
        break;
    case 'maintenance_due':
        $where .= " AND IFNULL((SELECT DATE(jsi.created_at) FROM job_sheet_images jsi WHERE jsi.device_id = d.id ORDER BY jsi.created_at DESC LIMIT 1), d.installation_date) <= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)";
        break;
}

$chk_ser = @$conn->query("SHOW COLUMNS FROM devices LIKE 'serial_number'");
$has_serial_col = ($chk_ser && $chk_ser->num_rows > 0);
$serial_select = $has_serial_col
    ? "COALESCE(d.serial_number, (SELECT GROUP_CONCAT(serial_number) FROM device_serials WHERE device_id = d.id)) as serial_display"
    : "(SELECT GROUP_CONCAT(serial_number) FROM device_serials WHERE device_id = d.id) as serial_display";

$chk_visit = @$conn->query("SHOW COLUMNS FROM devices LIKE 'visit_type'");
$has_visit_col = ($chk_visit && $chk_visit->num_rows > 0) || $has_visit_col_filter;
$visit_select = $has_visit_col ? "d.visit_type," : "NULL as visit_type,";

$base_sql = "SELECT d.*, c.name as customer_name, c.id as customer_id, g.name_ar as gov_name, 
    dn.name as device_name, dm.model_name, co.name as company_name, e.name as engineer_name, 
    $visit_select
    DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) as warranty_end,
    (SELECT MAX(jsi.created_at) FROM job_sheet_images jsi WHERE jsi.device_id = d.id) as last_maintenance,
    (SELECT image_path FROM job_sheet_images WHERE device_id = d.id ORDER BY created_at DESC LIMIT 1) as first_image,
    d.created_at as created_at_formatted,
    $serial_select
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 ($sort) {
    case 'oldest': $order = " ORDER BY d.installation_date ASC, d.id ASC"; break;
    case 'warranty_asc': $order = " ORDER BY warranty_end ASC, d.id ASC"; break;
    case 'warranty_desc': $order = " ORDER BY warranty_end DESC, d.id ASC"; break;
    default: $order = " ORDER BY d.id DESC";
}

$count_sql = "SELECT COUNT(*) as c FROM devices d JOIN customers c ON d.customer_id = c.id JOIN device_names dn ON d.device_name_id = dn.id $where";
if ($params) {
    $st = $conn->prepare($count_sql);
    $st->bind_param($types, ...$params);
    $st->execute();
    $total = $st->get_result()->fetch_assoc()['c'];
} else {
    $total = $conn->query($count_sql)->fetch_assoc()['c'];
}
$totalPages = ceil($total / $perPage) ?: 1;

$sql = $base_sql . $order . " LIMIT $perPage OFFSET $offset";
if ($params) {
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $devices = $stmt->get_result();
    } else {
        $error = 'خطأ في الاستعلام: ' . htmlspecialchars($conn->error);
        $devices = $conn->query($base_sql . $order . " LIMIT $perPage OFFSET $offset");
    }
} else {
    $devices = $conn->query($sql);
    if (!$devices) {
        $error = 'خطأ في الاستعلام: ' . htmlspecialchars($conn->error);
        $devices = $conn->query("SELECT d.*, c.name as customer_name, c.id as customer_id, g.name_ar as gov_name, 
            dn.name as device_name, dm.model_name, co.name as company_name, e.name as engineer_name, 
            $visit_select
            DATE_ADD(d.installation_date, INTERVAL d.warranty_months MONTH) as warranty_end,
            d.created_at as created_at_formatted,
            $serial_select
            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 1=1 $order LIMIT $perPage OFFSET $offset");
    }
}

$customer_name_filter = '';
$engineer_name_filter = '';
$company_name_filter = '';
$device_name_filter = '';
$device_model_filter = '';
$visit_type_filter = '';
$created_range_filter = '';
if ($customer_id) {
    $cn = $conn->query("SELECT name FROM customers WHERE id = $customer_id");
    if ($cn && $r = $cn->fetch_assoc()) $customer_name_filter = $r['name'];
}
if ($engineer_id) {
    $en = $conn->query("SELECT name FROM engineers WHERE id = $engineer_id");
    if ($en && $r = $en->fetch_assoc()) $engineer_name_filter = $r['name'];
}
if ($company_id) {
    $con = $conn->query("SELECT name FROM companies WHERE id = $company_id");
    if ($con && $r = $con->fetch_assoc()) $company_name_filter = $r['name'];
}
if ($device_name_id) {
    $dn = $conn->query("SELECT name FROM device_names WHERE id = $device_name_id");
    if ($dn && $r = $dn->fetch_assoc()) $device_name_filter = $r['name'];
}
if ($device_model_id) {
    $dm = $conn->query("SELECT dm.model_name, dn.name as device_name FROM device_models dm JOIN device_names dn ON dm.device_name_id = dn.id WHERE dm.id = $device_model_id");
    if ($dm && $r = $dm->fetch_assoc()) $device_model_filter = $r['device_name'] . ' - ' . $r['model_name'];
}
if ($visit_type !== '' && in_array($visit_type, $visit_type_options, true)) {
    $visit_type_filter = $visit_type;
}
if (in_array($created_range, ['today', 'week', 'month'], true)) {
    $created_range_map = ['today' => 'اليوم', 'week' => 'آخر 7 أيام', 'month' => 'آخر 30 يوم'];
    $created_range_filter = $created_range_map[$created_range];
}
if ($valid_from !== '' || $valid_to !== '') {
    $created_range_filter = 'من ' . ($valid_from !== '' ? $valid_from : '---') . ' إلى ' . ($valid_to !== '' ? $valid_to : '---');
}

// إحصائيات - محسوبة بدقة
$stats_total = $conn->query("SELECT COUNT(*) c FROM devices")->fetch_assoc()['c'];
$stats_warranty = $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'];
$stats_expired = $conn->query("SELECT COUNT(*) c FROM devices WHERE DATE_ADD(installation_date, INTERVAL warranty_months MONTH) < CURDATE()")->fetch_assoc()['c'];
$stats_maint = $conn->query("SELECT COUNT(DISTINCT d.id) as c FROM devices d 
    LEFT JOIN job_sheet_images jsi ON jsi.device_id = d.id 
    WHERE IFNULL((SELECT DATE(MAX(jsi2.created_at)) FROM job_sheet_images jsi2 WHERE jsi2.device_id = d.id), d.installation_date) <= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)")->fetch_assoc()['c'];

// المهندسين الذين لم يرسلوا اليوم (لا يوجد تسجيل أجهزة لهم اليوم)
$engineers_not_sent_today = [];
$ens = $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");
if ($ens) {
    while ($er = $ens->fetch_assoc()) $engineers_not_sent_today[] = $er;
}
?>
<!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>
        .dev-stat-card { border-radius: 16px; transition: transform 0.2s; }
        .dev-stat-card:hover { transform: translateY(-2px); }
        .dev-filter-tabs .nav-link { border-radius: 10px; font-weight: 500; padding: 0.5rem 1rem; font-size: 0.9rem; }
        .dev-filter-tabs .nav-link.active { background: #0f172a; color: #fff !important; }
        .dev-filter-tabs .nav-link:not(.active) { color: #475569; }
        .dev-filter-tabs .nav-link:not(.active):hover { background: #f1f5f9; }
        .badge-warranty-active { background: #22c55e; }
        .badge-warranty-expiring { background: #f59e0b; }
        .badge-warranty-expired { background: #ef4444; }
        .devices-table thead th {
            position: sticky;
            top: 0;
            z-index: 8;
            background: #163b6a !important;
            color: #ffffff !important;
            border-bottom: 2px solid #0f2b4c !important;
            font-weight: 700;
            white-space: nowrap;
        }
        .devices-table thead th:first-child { border-top-right-radius: 8px; }
        .devices-table thead th:last-child { border-top-left-radius: 8px; }
        .devices-table tbody td {
            color: #0f172a;
            border-color: #e2e8f0;
            vertical-align: middle;
        }
        .devices-table tbody tr:hover {
            background-color: #eef6ff !important;
        }
        .devices-table .text-muted {
            color: #475569 !important;
        }
    </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>
                    <?php if ($customer_name_filter): ?>
                    <li class="breadcrumb-item"><a href="customers.php">الزبائن</a></li>
                    <li class="breadcrumb-item active">أجهزة <?= htmlspecialchars($customer_name_filter) ?></li>
                    <?php elseif ($engineer_name_filter): ?>
                    <li class="breadcrumb-item"><a href="engineers.php">المهندسين</a></li>
                    <li class="breadcrumb-item active">أجهزة <?= htmlspecialchars($engineer_name_filter) ?></li>
                    <?php elseif ($company_name_filter): ?>
                    <li class="breadcrumb-item"><a href="companies.php">الشركات</a></li>
                    <li class="breadcrumb-item active">أجهزة <?= htmlspecialchars($company_name_filter) ?></li>
                    <?php elseif ($device_name_filter): ?>
                    <li class="breadcrumb-item"><a href="device_models.php">الأجهزة وموديلاتها</a></li>
                    <li class="breadcrumb-item active"><?= htmlspecialchars($device_name_filter) ?></li>
                    <?php elseif ($device_model_filter): ?>
                    <li class="breadcrumb-item"><a href="device_models.php">الأجهزة وموديلاتها</a></li>
                    <li class="breadcrumb-item active"><?= htmlspecialchars($device_model_filter) ?></li>
                    <?php else: ?>
                    <li class="breadcrumb-item active">قائمة الأجهزة</li>
                    <?php endif; ?>
                </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-cpu me-2"></i>قائمة الأجهزة
                    <?php 
                    $cancel_customer_q = array_filter(['engineer_id'=>$engineer_id,'company_id'=>$company_id]);
                    $cancel_engineer_q = array_filter(['customer_id'=>$customer_id,'company_id'=>$company_id]);
                    $cancel_company_q = array_filter(['customer_id'=>$customer_id,'engineer_id'=>$engineer_id]);
                    $cancel_device_name_q = array_filter(['customer_id'=>$customer_id,'engineer_id'=>$engineer_id,'company_id'=>$company_id,'device_model_id'=>$device_model_id]);
                    $cancel_device_model_q = array_filter(['customer_id'=>$customer_id,'engineer_id'=>$engineer_id,'company_id'=>$company_id,'device_name_id'=>$device_name_id]);
                    $cancel_visit_type_q = array_filter(['customer_id'=>$customer_id,'engineer_id'=>$engineer_id,'company_id'=>$company_id,'device_name_id'=>$device_name_id,'device_model_id'=>$device_model_id]);
                    $cancel_created_range_q = array_filter(['customer_id'=>$customer_id,'engineer_id'=>$engineer_id,'company_id'=>$company_id,'device_name_id'=>$device_name_id,'device_model_id'=>$device_model_id,'visit_type'=>$visit_type]);
                    ?>
                    <?php if ($customer_name_filter): ?>
                    <small class="text-muted fw-normal fs-6">— زبون: <?= htmlspecialchars($customer_name_filter) ?>
                        <a href="devices_list.php<?= $cancel_customer_q ? '?'.http_build_query($cancel_customer_q) : '' ?>" class="badge bg-secondary text-decoration-none ms-1">إلغاء</a>
                    </small>
                    <?php endif; ?>
                    <?php if ($engineer_name_filter): ?>
                    <small class="text-muted fw-normal fs-6">— مهندس: <?= htmlspecialchars($engineer_name_filter) ?>
                        <a href="devices_list.php<?= $cancel_engineer_q ? '?'.http_build_query($cancel_engineer_q) : '' ?>" class="badge bg-secondary text-decoration-none ms-1">إلغاء</a>
                    </small>
                    <?php endif; ?>
                    <?php if ($company_name_filter): ?>
                    <small class="text-muted fw-normal fs-6">— شركة: <?= htmlspecialchars($company_name_filter) ?>
                        <a href="devices_list.php<?= $cancel_company_q ? '?'.http_build_query($cancel_company_q) : '' ?>" class="badge bg-secondary text-decoration-none ms-1">إلغاء</a>
                    </small>
                    <?php endif; ?>
                    <?php if ($device_name_filter): ?>
                    <small class="text-muted fw-normal fs-6">— جهاز: <?= htmlspecialchars($device_name_filter) ?>
                        <a href="devices_list.php<?= $cancel_device_name_q ? '?'.http_build_query($cancel_device_name_q) : '' ?>" class="badge bg-secondary text-decoration-none ms-1">إلغاء</a>
                    </small>
                    <?php endif; ?>
                    <?php if ($device_model_filter): ?>
                    <small class="text-muted fw-normal fs-6">— موديل: <?= htmlspecialchars($device_model_filter) ?>
                        <a href="devices_list.php<?= $cancel_device_model_q ? '?'.http_build_query($cancel_device_model_q) : '' ?>" class="badge bg-secondary text-decoration-none ms-1">إلغاء</a>
                    </small>
                    <?php endif; ?>
                    <?php if ($visit_type_filter): ?>
                    <small class="text-muted fw-normal fs-6">— نوع الزيارة: <?= htmlspecialchars($visit_type_filter) ?>
                        <a href="devices_list.php<?= $cancel_visit_type_q ? '?'.http_build_query($cancel_visit_type_q) : '' ?>" class="badge bg-secondary text-decoration-none ms-1">إلغاء</a>
                    </small>
                    <?php endif; ?>
                    <?php if ($created_range_filter): ?>
                    <small class="text-muted fw-normal fs-6">— تاريخ التسجيل: <?= htmlspecialchars($created_range_filter) ?>
                        <a href="devices_list.php<?= $cancel_created_range_q ? '?'.http_build_query($cancel_created_range_q) : '' ?>" class="badge bg-secondary text-decoration-none ms-1">إلغاء</a>
                    </small>
                    <?php endif; ?>
                </h2>
                <div class="d-flex gap-2">
                    <?php if (canEdit()): ?><a href="devices.php" class="btn btn-primary btn-sm"><i class="bi bi-plus me-1"></i> إضافة جهاز</a><?php endif; ?>
                    <?php if (canExport()): ?><a href="export.php?type=devices" class="btn btn-success btn-sm"><i class="bi bi-file-excel me-1"></i> تصدير Excel</a><?php endif; ?>
                    <?php if (canEdit()): ?><button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#importModal"><i class="bi bi-upload me-1"></i> استيراد Excel</button><?php endif; ?>
                </div>
            </div>

            <?php if ($success): ?>
            <div class="alert alert-success d-flex align-items-center mb-4">
                <i class="bi bi-check-circle me-2"></i><?= $success ?>
            </div>
            <?php endif; ?>
            <?php if ($error): ?>
            <div class="alert alert-danger d-flex align-items-center mb-4">
                <i class="bi bi-exclamation-circle me-2"></i><?= $error ?>
            </div>
            <?php endif; ?>

            <?php
            $base_q = [];
            if ($customer_id) $base_q['customer_id'] = $customer_id;
            if ($engineer_id) $base_q['engineer_id'] = $engineer_id;
            if ($company_id) $base_q['company_id'] = $company_id;
            if ($device_name_id) $base_q['device_name_id'] = $device_name_id;
            if ($device_model_id) $base_q['device_model_id'] = $device_model_id;
            if ($visit_type !== '') $base_q['visit_type'] = $visit_type;
            if ($created_range !== '') $base_q['created_range'] = $created_range;
            if ($valid_from !== '') $base_q['created_from'] = $valid_from;
            if ($valid_to !== '') $base_q['created_to'] = $valid_to;
            if ($search) $base_q['q'] = $search;
            $base_qstr = $base_q ? http_build_query($base_q) . '&' : '';
            $base_q_quick = $base_q;
            unset($base_q_quick['created_from'], $base_q_quick['created_to']);
            $base_qstr_quick = $base_q_quick ? http_build_query($base_q_quick) . '&' : '';
            $has_any_filter = ($search !== '' || $customer_id || $engineer_id || $company_id || $device_name_id || $device_model_id || $visit_type !== '' || $created_range !== '' || $valid_from !== '' || $valid_to !== '' || $filter !== 'all' || $sort !== 'newest');
            ?>

            <!-- بطاقات الإحصائيات -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-3">
                    <a href="?<?= $base_qstr ?>status=all" class="text-decoration-none">
                    <div class="card dev-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 py-3">
                            <div class="rounded-circle bg-primary bg-opacity-25 p-2">
                                <i class="bi bi-cpu text-primary fs-5"></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 class="col-6 col-md-3">
                    <a href="?<?= $base_qstr ?>status=warranty_active" class="text-decoration-none">
                    <div class="card dev-stat-card h-100" style="background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%); border: 1px solid #86efac;">
                        <div class="card-body d-flex align-items-center gap-3 py-3">
                            <div class="rounded-circle bg-success bg-opacity-25 p-2">
                                <i class="bi bi-shield-check text-success fs-5"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats_warranty ?></h3>
                                <small class="text-success fw-600">داخل الضمان</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-3">
                    <a href="?<?= $base_qstr ?>status=warranty_expired" class="text-decoration-none">
                    <div class="card dev-stat-card h-100" style="background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); border: 1px solid #fca5a5;">
                        <div class="card-body d-flex align-items-center gap-3 py-3">
                            <div class="rounded-circle bg-danger bg-opacity-25 p-2">
                                <i class="bi bi-shield-x text-danger fs-5"></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 class="col-6 col-md-3">
                    <a href="?<?= $base_qstr ?>status=maintenance_due" class="text-decoration-none">
                    <div class="card dev-stat-card h-100" style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #fcd34d;">
                        <div class="card-body d-flex align-items-center gap-3 py-3">
                            <div class="rounded-circle bg-warning bg-opacity-25 p-2">
                                <i class="bi bi-tools text-warning fs-5"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats_maint ?></h3>
                                <small class="fw-600" style="color:#b45309">تحتاج صيانة</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
            </div>

            <div class="card mb-3 border-warning-subtle">
                <div class="card-header bg-warning-subtle d-flex justify-content-between align-items-center py-2">
                    <strong><i class="bi bi-person-x me-1"></i>المهندسين الذين لم يرسلوا اليوم</strong>
                    <span class="badge bg-dark"><?= count($engineers_not_sent_today) ?></span>
                </div>
                <div class="card-body py-2">
                    <?php if (!empty($engineers_not_sent_today)): ?>
                        <?php foreach ($engineers_not_sent_today as $eng): ?>
                            <a href="devices_list.php?engineer_id=<?= (int)$eng['id'] ?>" class="badge rounded-pill text-bg-warning text-decoration-none me-1 mb-1">
                                <?= htmlspecialchars($eng['name']) ?>
                            </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <span class="text-success">كل المهندسين أرسلوا اليوم</span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- فلاتر وترتيب -->
            <div class="d-flex flex-wrap gap-2 align-items-center mb-3">
                <ul class="nav dev-filter-tabs gap-1 me-2">
                    <li class="nav-item"><a class="nav-link <?= $filter === 'all' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=all">الكل</a></li>
                    <li class="nav-item"><a class="nav-link <?= $filter === 'warranty_active' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=warranty_active">داخل الضمان</a></li>
                    <li class="nav-item"><a class="nav-link <?= $filter === 'warranty_expired' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=warranty_expired">منتهي</a></li>
                    <li class="nav-item"><a class="nav-link <?= $filter === 'maintenance_due' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=maintenance_due">تحتاج صيانة</a></li>
                </ul>
                <div class="btn-group btn-group-sm me-2">
                    <a class="btn btn-outline-secondary <?= $created_range === 'today' ? 'active' : '' ?>" href="?<?= $base_qstr_quick ?>created_range=today">اليوم</a>
                    <a class="btn btn-outline-secondary <?= $created_range === 'week' ? 'active' : '' ?>" href="?<?= $base_qstr_quick ?>created_range=week">7 أيام</a>
                    <a class="btn btn-outline-secondary <?= $created_range === 'month' ? 'active' : '' ?>" href="?<?= $base_qstr_quick ?>created_range=month">30 يوم</a>
                </div>
                <div class="dropdown ms-auto">
                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">ترتيب</button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item <?= $sort === 'newest' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=<?= $filter ?>&sort=newest">الأحدث أولاً</a></li>
                        <li><a class="dropdown-item <?= $sort === 'oldest' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=<?= $filter ?>&sort=oldest">الأقدم أولاً</a></li>
                        <li><a class="dropdown-item <?= $sort === 'warranty_asc' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=<?= $filter ?>&sort=warranty_asc">الضمان: الأقرب للانتهاء</a></li>
                        <li><a class="dropdown-item <?= $sort === 'warranty_desc' ? 'active' : '' ?>" href="?<?= $base_qstr ?>status=<?= $filter ?>&sort=warranty_desc">الضمان: الأبعد</a></li>
                    </ul>
                </div>
            </div>

            <!-- الجدول -->
            <div class="card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2 py-3">
                    <form method="GET" class="d-flex gap-2">
                        <?php if ($customer_id): ?><input type="hidden" name="customer_id" value="<?= $customer_id ?>"><?php endif; ?>
                        <?php if ($engineer_id): ?><input type="hidden" name="engineer_id" value="<?= $engineer_id ?>"><?php endif; ?>
                        <?php if ($company_id): ?><input type="hidden" name="company_id" value="<?= $company_id ?>"><?php endif; ?>
                        <?php if ($device_name_id): ?><input type="hidden" name="device_name_id" value="<?= $device_name_id ?>"><?php endif; ?>
                        <?php if ($device_model_id): ?><input type="hidden" name="device_model_id" value="<?= $device_model_id ?>"><?php endif; ?>
                        <?php if ($filter !== 'all'): ?><input type="hidden" name="status" value="<?= $filter ?>"><?php endif; ?>
                        <?php if ($sort !== 'newest'): ?><input type="hidden" name="sort" value="<?= $sort ?>"><?php endif; ?>
                        <?php if ($created_range !== ''): ?><input type="hidden" name="created_range" value="<?= htmlspecialchars($created_range) ?>"><?php endif; ?>
                        <select name="visit_type" class="form-select form-select-sm" style="max-width: 180px;">
                            <option value="">كل أنواع الزيارة</option>
                            <?php foreach ($visit_type_options as $vt): ?>
                            <option value="<?= htmlspecialchars($vt) ?>" <?= $visit_type === $vt ? 'selected' : '' ?>><?= htmlspecialchars($vt) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input type="date" name="created_from" class="form-control form-control-sm" value="<?= htmlspecialchars($valid_from) ?>" title="من تاريخ" style="max-width: 150px;">
                        <input type="date" name="created_to" class="form-control form-control-sm" value="<?= htmlspecialchars($valid_to) ?>" title="إلى تاريخ" style="max-width: 150px;">
                        <input type="text" name="q" class="form-control form-control-sm" placeholder="بحث (فاتورة، زبون، مستشفى، جهاز)" value="<?= htmlspecialchars($search) ?>" style="max-width: 280px;">
                        <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i></button>
                        <?php if ($has_any_filter): ?><a href="devices_list.php" class="btn btn-outline-danger btn-sm"><i class="bi bi-x-circle"></i> مسح الفلاتر</a><?php endif; ?>
                    </form>
                    <span class="text-muted small"><?= $total ?> جهاز</span>
                </div>
                <div class="card-body p-0 overflow-auto" style="max-height: 55vh;">
                    <table class="table table-hover mb-0 devices-table">
                        <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>
                                <th>تفاصيل الزيارة</th><th>التنصيب</th><th>نهاية الضمان</th><th>تاريخ التسجيل</th><th>الحالة</th><th>إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php while ($d = $devices->fetch_assoc()): 
                            $warranty_ts = $d['warranty_end'] ? strtotime($d['warranty_end']) : 0;
                            $days_left = $warranty_ts ? ceil(($warranty_ts - time()) / 86400) : 0;
                            $expired = $warranty_ts && $warranty_ts < time();
                            $expiring = !$expired && $days_left <= 30;
                            $badgeClass = $expired ? 'badge-warranty-expired' : ($expiring ? 'badge-warranty-expiring' : 'badge-warranty-active');
                            $statusText = $expired ? 'منتهي' : ($expiring ? $days_left . ' يوم' : $days_left . ' يوم');
                        ?>
                        <tr class="align-middle <?= $expired ? 'table-danger' : ($expiring ? 'table-warning' : '') ?>" onclick="window.location.href='device_view.php?id=<?= $d['id'] ?>'" style="cursor:pointer">
                            <td><?= $d['id'] ?></td>
                            <td>
                                <?php 
                                $imgPath = !empty($d['first_image']) ? ('uploads/' . $d['first_image']) : '';
                                $imgExists = $imgPath && file_exists(__DIR__ . '/' . $imgPath);
                                if ($imgExists): ?>
                                <a href="device_view.php?id=<?= $d['id'] ?>" onclick="event.stopPropagation()">
                                    <img src="<?= htmlspecialchars($imgPath) ?>" alt="صورة" class="rounded" style="width:40px;height:40px;object-fit:cover;border:1px solid #dee2e6">
                                </a>
                                <?php else: ?>
                                <span class="text-muted" title="لا صورة"><i class="bi bi-image"></i></span>
                                <?php endif; ?>
                            </td>
                            <td><a href="device_view.php?id=<?= $d['id'] ?>" class="text-decoration-none fw-500" onclick="event.stopPropagation()"><?= htmlspecialchars($d['invoice_number']) ?></a></td>
                            <td class="small"><?= htmlspecialchars($d['serial_display'] ?? '-') ?></td>
                            <td><a href="devices_list.php?customer_id=<?= $d['customer_id'] ?>" class="text-decoration-none" onclick="event.stopPropagation()"><?= htmlspecialchars($d['customer_name']) ?></a></td>
                            <td><?= htmlspecialchars($d['hospital_name']) ?></td>
                            <td dir="ltr" class="small"><?= htmlspecialchars($d['phone'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($d['device_name']) ?></td>
                            <td><?= htmlspecialchars($d['model_name']) ?></td>
                            <td><?= htmlspecialchars($d['engineer_name'] ?? '-') ?></td>
                            <td>
                                <?php 
                                $visitType = isset($d['visit_type']) ? trim($d['visit_type']) : '';
                                if (!empty($visitType)) {
                                    $visitTypeLabels = [
                                        'صيانة' => '<span class="badge bg-warning text-dark">صيانة</span>',
                                        'تنصيب' => '<span class="badge bg-primary">تنصيب</span>',
                                        'صيانة دورية' => '<span class="badge bg-info">صيانة دورية</span>',
                                        'تدريب' => '<span class="badge bg-success">تدريب</span>'
                                    ];
                                    echo isset($visitTypeLabels[$visitType]) ? $visitTypeLabels[$visitType] : '<span class="badge bg-secondary">' . htmlspecialchars($visitType) . '</span>';
                                } else {
                                    echo '<span class="text-muted small">-</span>';
                                }
                                ?>
                            </td>
                            <?php
                            $installationDisplay = (!empty($d['installation_date']) && $d['installation_date'] !== '0000-00-00') ? $d['installation_date'] : '-';
                            $warrantyDisplay = (!empty($d['warranty_end']) && $d['warranty_end'] !== '0000-00-00') ? $d['warranty_end'] : '-';
                            ?>
                            <td><?= htmlspecialchars($installationDisplay) ?></td>
                            <td><?= htmlspecialchars($warrantyDisplay) ?></td>
                            <td class="small text-muted" dir="ltr">
                                <?php 
                                $createdAt = $d['created_at_formatted'] ?? ($d['created_at'] ?? '');
                                if ($createdAt) {
                                    try {
                                        $dt = new DateTime($createdAt, new DateTimeZone('Asia/Baghdad'));
                                        $dt->setTimezone(new DateTimeZone('Asia/Baghdad'));
                                        $period = ((int)$dt->format('H') < 12) ? 'ص' : 'م';
                                        echo htmlspecialchars($dt->format('Y-m-d'));
                                        echo '<br><small class="text-muted">' . htmlspecialchars($dt->format('h:i:s')) . ' ' . $period . '</small>';
                                    } catch (Exception $e) {
                                        echo htmlspecialchars($createdAt);
                                    }
                                } else {
                                    echo '-';
                                }
                                ?>
                            </td>
                            <td><span class="badge <?= $badgeClass ?>"><?= $statusText ?></span></td>
                            <td>
                                <div class="d-flex gap-1" onclick="event.stopPropagation()">
                                    <a href="device_view.php?id=<?= $d['id'] ?>" class="btn btn-sm btn-outline-primary" title="عرض"><i class="bi bi-eye"></i></a>
                                    <?php if (canEdit()): ?><a href="devices.php?id=<?= $d['id'] ?>" class="btn btn-sm btn-outline-success" title="تعديل"><i class="bi bi-pencil"></i></a><?php endif; ?>
                                    <?php if (canDelete()): ?><button type="button" class="btn btn-sm btn-outline-danger btn-delete-device" data-id="<?= $d['id'] ?>" data-invoice="<?= htmlspecialchars($d['invoice_number']) ?>" title="حذف"><i class="bi bi-trash"></i></button><?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        <?php if ($total === 0): ?>
                        <tr>
                            <td colspan="16" class="text-center text-muted py-5">
                                <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                                لا توجد أجهزة
                                <?php if ($filter !== 'all' || $search): ?>
                                <p class="small mt-2 mb-0">جرّب تغيير الفلتر أو البحث</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <?php if ($totalPages > 1): 
                    $pageParams = $base_q ?: [];
                    $pageParams['status'] = $filter;
                    if ($sort !== 'newest') $pageParams['sort'] = $sort;
                    $pageBase = '?' . http_build_query($pageParams);
                ?>
                <div class="card-footer bg-white py-3">
                    <nav>
                        <ul class="pagination pagination-sm justify-content-center mb-0">
                            <?php if ($page > 1): ?>
                            <li class="page-item"><a class="page-link" href="<?= $pageBase ?>&page=<?= $page-1 ?>">السابق</a></li>
                            <?php endif; ?>
                            <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                            <li class="page-item <?= $i == $page ? 'active' : '' ?>"><a class="page-link" href="<?= $pageBase ?>&page=<?= $i ?>"><?= $i ?></a></li>
                            <?php endfor; ?>
                            <?php if ($page < $totalPages): ?>
                            <li class="page-item"><a class="page-link" href="<?= $pageBase ?>&page=<?= $page+1 ?>">التالي</a></li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <p class="text-muted text-center small mt-2 mb-0">صفحة <?= $page ?> من <?= $totalPages ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- نافذة الاستيراد -->
    <?php if (canEdit()): ?>
    <div class="modal fade" id="importModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-upload me-2"></i>استيراد الأجهزة من Excel</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="import_devices">
                    <div class="modal-body">
                        <p class="text-muted small">الصيغ المدعومة: xlsx, xls, csv. الأعمدة المتوقعة: رقم الفاتورة، الزبون، المستشفى، الهاتف، المحافظة، الجهاز، الموديل، الشركة، العدد، تاريخ التنصيب، الضمان (شهر)، المهندس، الملاحظات. اسم المهندس يجب أن يكون مسجلاً مسبقاً. الزبائن والشركات وأسماء الأجهزة والموديلات غير الموجودة تُنشأ تلقائياً.</p>
                        <div class="mb-3">
                            <label class="form-label">اختر الملف</label>
                            <input type="file" name="import_file" class="form-control" accept=".xlsx,.xls,.csv" required>
                        </div>
                        <p class="small"><a href="export.php?type=devices" class="text-primary">حمّل ملف نموذج</a> من التصدير ثم أضف الأجهزة الجديدة فيه.</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-success"><i class="bi bi-upload me-1"></i>استيراد</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <?php if (canDelete()): ?>
    <script>
    function apiUrl(path) { return new URL(path, window.location.href).href; }
    document.querySelectorAll('.btn-delete-device').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            if (!confirm('حذف الجهاز برقم الفاتورة ' + (this.dataset.invoice || '') + '؟')) return;
            var u = apiUrl('api/devices.php?action=delete&id=' + this.dataset.id + (typeof window.csrfToken !== 'undefined' && window.csrfToken ? '&csrf_token=' + encodeURIComponent(window.csrfToken) : ''));
            fetch(u).then(r => r.json()).then(d => { if (d.success) location.reload(); else alert(d.message || 'فشل الحذف'); }).catch(function(err) { alert('خطأ في الاتصال. تأكد من وجود ملف api/devices.php على السيرفر.'); });
        });
    });
    </script>
    <?php endif; ?>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
