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

$tab = $_GET['tab'] ?? 'names'; // names | models
$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') {
    if (function_exists('require_csrf')) require_csrf();
    if (!canEdit()) { header('Location: device_models.php?tab=' . ($_GET['tab'] ?? 'names')); exit; }
    $action = $_POST['action'] ?? '';
    
    if (!empty($_FILES['import_file']['name']) && isset($_POST['action']) && ($_POST['action'] === 'import_names' || $_POST['action'] === 'import_models')) {
        $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'];
            $imported = 0;
            $skipped = 0;
            if ($_POST['action'] === 'import_names') {
                $existing = [];
                $r = $conn->query("SELECT name FROM device_names");
                while ($row = $r->fetch_assoc()) $existing[$row['name']] = 1;
                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);
                        $nameCol = 0;
                        if ($header) foreach ($header as $i => $h) {
                            if (stripos((string)$h, 'اسم') !== false || stripos((string)$h, 'جهاز') !== false || $h === 'name') $nameCol = $i;
                        }
                        while (($row = fgetcsv($handle)) !== false) {
                            $name = trim($row[$nameCol] ?? $row[0] ?? '');
                            if (empty($name)) continue;
                            if (isset($existing[$name])) { $skipped++; continue; }
                            $stmt = $conn->prepare("INSERT IGNORE INTO device_names (name) VALUES (?)");
                            $stmt->bind_param("s", $name);
                            if ($stmt->execute() && $stmt->affected_rows > 0) {
                                $imported++;
                                $existing[$name] = 1;
                                if (function_exists('logActivity')) logActivity('add', 'device_names', $conn->insert_id, $name . ' (استيراد)');
                            } else $skipped++;
                        }
                        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();
                    $nameCol = 0;
                    if (!empty($rows[0])) {
                        foreach ($rows[0] as $i => $h) {
                            $h = is_string($h) ? $h : '';
                            if (stripos($h, 'اسم') !== false || stripos($h, 'جهاز') !== false || $h === 'name') $nameCol = $i;
                        }
                    }
                    for ($i = 1; $i < count($rows); $i++) {
                        $row = $rows[$i] ?? [];
                        $name = trim($row[$nameCol] ?? $row[0] ?? '');
                        if (empty($name)) continue;
                        if (isset($existing[$name])) { $skipped++; continue; }
                        $stmt = $conn->prepare("INSERT IGNORE INTO device_names (name) VALUES (?)");
                        $stmt->bind_param("s", $name);
                        if ($stmt->execute() && $stmt->affected_rows > 0) {
                            $imported++;
                            $existing[$name] = 1;
                            if (function_exists('logActivity')) logActivity('add', 'device_names', $conn->insert_id, $name . ' (استيراد)');
                        } else $skipped++;
                    }
                    }
                }
                $tab = 'names';
            } else {
                $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'];
                $seenModels = [];
                $r = $conn->query("SELECT dm.device_name_id, dm.company_id, dm.model_name FROM device_models dm");
                while ($row = $r->fetch_assoc()) $seenModels[$row['device_name_id'].'_'.$row['company_id'].'_'.$row['model_name']] = 1;
                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);
                        $devCol = 0; $compCol = 1; $modCol = 2;
                        if ($header && count($header) >= 3) {
                            foreach ($header as $i => $h) {
                                $h = (string)$h;
                                if (stripos($h, 'جهاز') !== false || stripos($h, 'اسم الجهاز') !== false) $devCol = $i;
                                elseif (stripos($h, 'شركة') !== false) $compCol = $i;
                                elseif (stripos($h, 'موديل') !== false) $modCol = $i;
                            }
                        }
                        while (($row = fgetcsv($handle)) !== false) {
                            $devName = trim($row[$devCol] ?? $row[0] ?? '');
                            $compName = trim($row[$compCol] ?? $row[1] ?? '');
                            $modName = trim($row[$modCol] ?? $row[2] ?? '');
                            if (empty($devName) || empty($compName) || empty($modName)) continue;
                            $dnId = $nameMap[$devName] ?? null;
                            $coId = $compMap[$compName] ?? null;
                            if (!$dnId) {
                                $stmt = $conn->prepare("INSERT IGNORE INTO device_names (name) VALUES (?)");
                                $stmt->bind_param("s", $devName);
                                $stmt->execute();
                                $dnId = $conn->insert_id;
                                if (!$dnId) { $st2 = $conn->prepare("SELECT id FROM device_names WHERE name = ?"); $st2->bind_param("s", $devName); $st2->execute(); $res = $st2->get_result(); if ($res && $row2 = $res->fetch_assoc()) $dnId = $row2['id']; }
                                if ($dnId) $nameMap[$devName] = $dnId;
                            }
                            if (!$coId) {
                                $stmt = $conn->prepare("INSERT IGNORE INTO companies (name) VALUES (?)");
                                $stmt->bind_param("s", $compName);
                                $stmt->execute();
                                $coId = $conn->insert_id;
                                if (!$coId) { $st2 = $conn->prepare("SELECT id FROM companies WHERE name = ?"); $st2->bind_param("s", $compName); $st2->execute(); $res = $st2->get_result(); if ($res && $row2 = $res->fetch_assoc()) $coId = $row2['id']; }
                                if ($coId) $compMap[$compName] = $coId;
                            }
                            if (!$dnId || !$coId) continue;
                            $key = $dnId.'_'.$coId.'_'.$modName;
                            if (isset($seenModels[$key])) { $skipped++; continue; }
                            $stmt = $conn->prepare("INSERT IGNORE INTO device_models (device_name_id, company_id, model_name) VALUES (?, ?, ?)");
                            $stmt->bind_param("iis", $dnId, $coId, $modName);
                            if ($stmt->execute() && $stmt->affected_rows > 0) {
                                $imported++;
                                $seenModels[$key] = 1;
                                if (function_exists('logActivity')) logActivity('add', 'device_models', $conn->insert_id, $modName . ' (استيراد)');
                            } else $skipped++;
                        }
                        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();
                    $devCol = 0; $compCol = 1; $modCol = 2;
                    if (!empty($rows[0]) && count($rows[0]) >= 3) {
                        foreach ($rows[0] as $i => $h) {
                            $h = is_string($h) ? $h : '';
                            if (stripos($h, 'جهاز') !== false || stripos($h, 'اسم الجهاز') !== false) $devCol = $i;
                            elseif (stripos($h, 'شركة') !== false) $compCol = $i;
                            elseif (stripos($h, 'موديل') !== false) $modCol = $i;
                        }
                    }
                    for ($i = 1; $i < count($rows); $i++) {
                        $row = $rows[$i] ?? [];
                        $devName = trim($row[$devCol] ?? $row[0] ?? '');
                        $compName = trim($row[$compCol] ?? $row[1] ?? '');
                        $modName = trim($row[$modCol] ?? $row[2] ?? '');
                        if (empty($devName) || empty($compName) || empty($modName)) continue;
                        if (!isset($nameMap[$devName])) {
                            $stmt = $conn->prepare("INSERT IGNORE INTO device_names (name) VALUES (?)");
                            $stmt->bind_param("s", $devName);
                            $stmt->execute();
                            $nameMap[$devName] = $conn->insert_id;
                            if (!$nameMap[$devName]) { $st2 = $conn->prepare("SELECT id FROM device_names WHERE name = ?"); $st2->bind_param("s", $devName); $st2->execute(); $res = $st2->get_result(); if ($res && $row2 = $res->fetch_assoc()) $nameMap[$devName] = $row2['id']; }
                        }
                        if (!isset($compMap[$compName])) {
                            $stmt = $conn->prepare("INSERT IGNORE INTO companies (name) VALUES (?)");
                            $stmt->bind_param("s", $compName);
                            $stmt->execute();
                            $compMap[$compName] = $conn->insert_id;
                            if (!$compMap[$compName]) { $st2 = $conn->prepare("SELECT id FROM companies WHERE name = ?"); $st2->bind_param("s", $compName); $st2->execute(); $res = $st2->get_result(); if ($res && $row2 = $res->fetch_assoc()) $compMap[$compName] = $row2['id']; }
                        }
                        $dnId = $nameMap[$devName] ?? null;
                        $coId = $compMap[$compName] ?? null;
                        if (!$dnId || !$coId) continue;
                        $key = $dnId.'_'.$coId.'_'.$modName;
                        if (isset($seenModels[$key])) { $skipped++; continue; }
                        $stmt = $conn->prepare("INSERT IGNORE INTO device_models (device_name_id, company_id, model_name) VALUES (?, ?, ?)");
                        $stmt->bind_param("iis", $dnId, $coId, $modName);
                        if ($stmt->execute() && $stmt->affected_rows > 0) {
                            $imported++;
                            $seenModels[$key] = 1;
                            if (function_exists('logActivity')) logActivity('add', 'device_models', $conn->insert_id, $modName . ' (استيراد)');
                        } else $skipped++;
                    }
                    }
                }
                $tab = 'models';
            }
            if (empty($error)) {
                header('Location: device_models.php?tab=' . $tab . '&imported=' . $imported . '&skipped=' . $skipped);
                exit;
            }
        }
    } elseif ($action === 'add_name') {
        $name = trim($_POST['device_name'] ?? '');
        if (empty($name)) {
            $error = 'يرجى إدخال اسم الجهاز';
        } else {
            $stmt = $conn->prepare("INSERT IGNORE INTO device_names (name) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute() && $stmt->affected_rows > 0) {
                if (function_exists('logActivity')) logActivity('add', 'device_names', $conn->insert_id, $name);
                $success = 'تم إضافة اسم الجهاز بنجاح';
                $tab = 'names';
            } else {
                $error = 'الاسم موجود مسبقاً';
            }
        }
    } elseif ($action === 'add_model') {
        $device_name_id = (int)($_POST['device_name_id'] ?? 0);
        $company_id = (int)($_POST['company_id'] ?? 0);
        $model_name = trim($_POST['model_name'] ?? '');
        if (empty($device_name_id) || empty($company_id) || empty($model_name)) {
            $error = 'يرجى تعبئة جميع الحقول';
        } else {
            $stmt = $conn->prepare("INSERT IGNORE INTO device_models (device_name_id, company_id, model_name) VALUES (?, ?, ?)");
            $stmt->bind_param("iis", $device_name_id, $company_id, $model_name);
            if ($stmt->execute() && $stmt->affected_rows > 0) {
                if (function_exists('logActivity')) logActivity('add', 'device_models', $conn->insert_id, $model_name);
                $success = 'تم إضافة الموديل بنجاح';
                $tab = 'models';
            } else {
                $error = 'الموديل موجود مسبقاً لهذا الجهاز والشركة';
            }
        }
    }
}

$search_name = trim($_GET['qn'] ?? '');
$search_model = trim($_GET['qm'] ?? '');
$where_name = $search_name ? " WHERE dn.name LIKE '%" . $conn->real_escape_string($search_name) . "%'" : '';
$where_model = $search_model ? " AND (dn.name LIKE '%" . $conn->real_escape_string($search_model) . "%' OR c.name LIKE '%" . $conn->real_escape_string($search_model) . "%' OR dm.model_name LIKE '%" . $conn->real_escape_string($search_model) . "%')" : '';

$device_names = $conn->query("SELECT dn.*, (SELECT COUNT(*) FROM devices d WHERE d.device_name_id = dn.id) as device_count FROM device_names dn $where_name ORDER BY dn.name");
$companies = $conn->query("SELECT * FROM companies ORDER BY name");
$models = $conn->query("SELECT dm.*, dn.name as device_name, c.name as company_name, 
    (SELECT COUNT(*) FROM devices d WHERE d.device_model_id = dm.id) as device_count
    FROM device_models dm 
    JOIN device_names dn ON dm.device_name_id = dn.id 
    JOIN companies c ON dm.company_id = c.id 
    WHERE 1=1 $where_model
    ORDER BY dn.name, c.name, dm.model_name");

$stats_names = $conn->query("SELECT COUNT(*) c FROM device_names")->fetch_assoc()['c'];
$stats_models = $conn->query("SELECT COUNT(*) c FROM device_models")->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>
        .dm-stat-card { border-radius: 16px; transition: transform 0.2s; }
        .dm-stat-card:hover { transform: translateY(-2px); }
        .dm-tabs .nav-link { border-radius: 10px; font-weight: 500; }
        .dm-tabs .nav-link.active { background: #0f172a; color: #fff !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>
                    <li class="breadcrumb-item"><a href="dashboard.php">الإعدادات</a></li>
                    <li class="breadcrumb-item active">أسماء الأجهزة وموديلاتها</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-collection me-2"></i>أسماء الأجهزة وموديلاتها</h2>
                <div class="d-flex gap-2">
                    <?php if (canExport()): ?>
                    <a href="export.php?type=device_names" class="btn btn-success btn-sm"><i class="bi bi-file-excel me-1"></i>تصدير أسماء</a>
                    <a href="export.php?type=device_models" class="btn btn-success btn-sm"><i class="bi bi-file-excel me-1"></i>تصدير الموديلات</a>
                    <?php endif; ?>
                    <?php if (canEdit()): ?>
                    <button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#importNamesModal"><i class="bi bi-upload me-1"></i>استيراد أسماء</button>
                    <button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#importModelsModal"><i class="bi bi-upload me-1"></i>استيراد موديلات</button>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($success): ?>
            <div class="alert alert-success d-flex align-items-center"><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"><i class="bi bi-exclamation-circle me-2"></i><?= $error ?></div>
            <?php endif; ?>

            <!-- بطاقات الإحصائيات -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-4">
                    <a href="?tab=names" class="text-decoration-none">
                    <div class="card dm-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-3">
                                <i class="bi bi-cpu text-primary fs-5"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats_names ?></h3>
                                <small class="text-primary fw-600">أسماء الأجهزة</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
                <div class="col-6 col-md-4">
                    <a href="?tab=models" class="text-decoration-none">
                    <div class="card dm-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-3">
                                <i class="bi bi-collection text-success fs-5"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats_models ?></h3>
                                <small class="text-success fw-600">موديلات</small>
                            </div>
                        </div>
                    </div>
                    </a>
                </div>
            </div>

            <!-- تبويبات -->
            <ul class="nav dm-tabs gap-2 mb-3">
                <li class="nav-item"><a class="nav-link <?= $tab === 'names' ? 'active' : '' ?>" href="?tab=names"><i class="bi bi-cpu me-1"></i>أسماء الأجهزة</a></li>
                <li class="nav-item"><a class="nav-link <?= $tab === 'models' ? 'active' : '' ?>" href="?tab=models"><i class="bi bi-collection me-1"></i>موديلات الأجهزة</a></li>
            </ul>

            <div class="row g-4">
                <?php if (canEdit()): ?>
                <div class="col-lg-4">
                    <?php if ($tab === 'names'): ?>
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="bi bi-plus-circle me-2"></i>إضافة اسم جهاز</h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="add_name">
                                <div class="mb-3">
                                    <label class="form-label fw-600">اسم الجهاز</label>
                                    <input type="text" name="device_name" class="form-control" placeholder="مثال: جهاز أشعة" required value="<?= htmlspecialchars($_POST['device_name'] ?? '') ?>">
                                </div>
                                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-plus-lg me-1"></i> إضافة</button>
                            </form>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="bi bi-plus-circle me-2"></i>إضافة موديل جديد</h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="add_model">
                                <div class="mb-3">
                                    <label class="form-label fw-600">اسم الجهاز</label>
                                    <select name="device_name_id" class="form-select" required>
                                        <option value="">-- اختر --</option>
                                        <?php $dnList = $conn->query("SELECT * FROM device_names ORDER BY name"); while ($dn = $dnList->fetch_assoc()): ?>
                                        <option value="<?= $dn['id'] ?>"><?= htmlspecialchars($dn['name']) ?></option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-600">الشركة</label>
                                    <select name="company_id" class="form-select" required>
                                        <option value="">-- اختر --</option>
                                        <?php $companies->data_seek(0); while ($c = $companies->fetch_assoc()): ?>
                                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-600">موديل الجهاز</label>
                                    <input type="text" name="model_name" class="form-control" placeholder="اسم الموديل" required>
                                </div>
                                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-plus-lg me-1"></i> إضافة موديل</button>
                            </form>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <div class="col-lg-<?= canEdit() ? 8 : 12 ?>">
                    <?php if ($tab === 'names'): ?>
                    <div class="card">
                        <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2 py-3">
                            <h5 class="mb-0 fw-600"><i class="bi bi-list me-2"></i>قائمة أسماء الأجهزة</h5>
                            <form method="GET" class="d-flex gap-2">
                                <input type="hidden" name="tab" value="names">
                                <input type="text" name="qn" class="form-control form-control-sm" placeholder="بحث..." value="<?= htmlspecialchars($search_name) ?>" style="max-width: 200px;">
                                <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i></button>
                            </form>
                        </div>
                        <div class="card-body p-0 overflow-auto" style="max-height: 50vh;">
                            <table class="table table-hover mb-0">
                                <thead class="table-light"><tr><th>#</th><th>الاسم</th><th>عدد الأجهزة</th><?php if (canEdit() || canDelete()): ?><th>إجراءات</th><?php endif; ?></tr></thead>
                                <tbody>
                                <?php while ($dn = $device_names->fetch_assoc()): 
                                    $dc = (int)($dn['device_count'] ?? 0);
                                    $canDel = $dc === 0;
                                ?>
                                <tr class="align-middle">
                                    <td><?= $dn['id'] ?></td>
                                    <td class="fw-500"><?= htmlspecialchars($dn['name']) ?></td>
                                    <td>
                                        <?php if ($dc > 0): ?>
                                        <a href="devices_list.php?device_name_id=<?= $dn['id'] ?>" class="badge bg-primary text-decoration-none"><?= $dc ?></a>
                                        <?php else: ?><span class="text-muted">0</span><?php endif; ?>
                                    </td>
                                    <?php if (canEdit() || canDelete()): ?><td>
                                        <?php if (canEdit()): ?><button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editNameModal" data-id="<?= $dn['id'] ?>" data-name="<?= htmlspecialchars($dn['name']) ?>"><i class="bi bi-pencil"></i></button><?php endif; ?>
                                        <?php if ($canDel && canDelete()): ?>
                                        <button type="button" class="btn btn-sm btn-outline-danger btn-del-name" data-id="<?= $dn['id'] ?>"><i class="bi bi-trash"></i></button>
                                        <?php elseif (!$canDel): ?><span class="badge bg-secondary">—</span><?php endif; ?>
                                    </td><?php endif; ?>
                                </tr>
                                <?php endwhile; ?>
                                <?php if ($device_names->num_rows === 0): ?>
                                <tr><td colspan="<?= (canEdit() || canDelete()) ? 4 : 3 ?>" class="text-center text-muted py-4">لا توجد أسماء أجهزة</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="card">
                        <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2 py-3">
                            <h5 class="mb-0 fw-600"><i class="bi bi-list me-2"></i>قائمة الموديلات</h5>
                            <form method="GET" class="d-flex gap-2">
                                <input type="hidden" name="tab" value="models">
                                <input type="text" name="qm" class="form-control form-control-sm" placeholder="بحث (جهاز، شركة، موديل)..." value="<?= htmlspecialchars($search_model) ?>" style="max-width: 220px;">
                                <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i></button>
                            </form>
                        </div>
                        <div class="card-body p-0 overflow-auto" style="max-height: 50vh;">
                            <table class="table table-hover mb-0">
                                <thead class="table-light"><tr><th>#</th><th>الجهاز</th><th>الشركة</th><th>الموديل</th><th>أجهزة</th><?php if (canEdit() || canDelete()): ?><th>إجراءات</th><?php endif; ?></tr></thead>
                                <tbody>
                                <?php while ($m = $models->fetch_assoc()): 
                                    $dc = (int)($m['device_count'] ?? 0);
                                    $canDel = $dc === 0;
                                ?>
                                <tr class="align-middle">
                                    <td><?= $m['id'] ?></td>
                                    <td><?= htmlspecialchars($m['device_name']) ?></td>
                                    <td><?= htmlspecialchars($m['company_name']) ?></td>
                                    <td class="fw-500"><?= htmlspecialchars($m['model_name']) ?></td>
                                    <td>
                                        <?php if ($dc > 0): ?>
                                        <a href="devices_list.php?device_model_id=<?= $m['id'] ?>" class="badge bg-primary text-decoration-none"><?= $dc ?></a>
                                        <?php else: ?><span class="text-muted">0</span><?php endif; ?>
                                    </td>
                                    <?php if (canEdit() || canDelete()): ?><td>
                                        <?php if (canEdit()): ?><button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModelModal" 
                                            data-id="<?= $m['id'] ?>" data-name="<?= htmlspecialchars($m['model_name']) ?>" 
                                            data-device="<?= $m['device_name_id'] ?>" data-company="<?= $m['company_id'] ?>"><i class="bi bi-pencil"></i></button><?php endif; ?>
                                        <?php if ($canDel && canDelete()): ?>
                                        <button type="button" class="btn btn-sm btn-outline-danger btn-del-model" data-id="<?= $m['id'] ?>"><i class="bi bi-trash"></i></button>
                                        <?php elseif (!$canDel): ?><span class="badge bg-secondary">—</span><?php endif; ?>
                                    </td><?php endif; ?>
                                </tr>
                                <?php endwhile; ?>
                                <?php if ($models->num_rows === 0): ?>
                                <tr><td colspan="<?= (canEdit() || canDelete()) ? 6 : 5 ?>" class="text-center text-muted py-4">لا توجد موديلات</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- تعديل اسم الجهاز -->
    <!-- استيراد أسماء الأجهزة -->
    <div class="modal fade" id="importNamesModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-upload me-2"></i>استيراد أسماء الأجهزة</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_names">
                    <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=device_names" 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>

    <!-- استيراد الموديلات -->
    <div class="modal fade" id="importModelsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-upload me-2"></i>استيراد موديلات الأجهزة</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_models">
                    <div class="modal-body">
                        <p class="text-muted small">الأعمدة المطلوبة: اسم الجهاز | الشركة | الموديل. إن لم يكن اسم الجهاز أو الشركة موجوداً سيتم إنشاؤه تلقائياً.</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=device_models" 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>

    <div class="modal fade" id="editNameModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">تعديل اسم الجهاز</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" id="edit_name_id">
                    <div class="mb-3"><label class="form-label">الاسم</label><input type="text" id="edit_name_val" class="form-control" required></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary" id="saveNameEdit">حفظ</button>
                </div>
            </div>
        </div>
    </div>

    <!-- تعديل الموديل -->
    <div class="modal fade" id="editModelModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">تعديل الموديل</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" id="edit_model_id">
                    <div class="mb-3"><label class="form-label">اسم الجهاز</label>
                        <select id="edit_model_device" class="form-select"><?php $dnOpts = $conn->query("SELECT * FROM device_names ORDER BY name"); while($dn = $dnOpts->fetch_assoc()): ?><option value="<?= $dn['id'] ?>"><?= htmlspecialchars($dn['name']) ?></option><?php endwhile; ?></select>
                    </div>
                    <div class="mb-3"><label class="form-label">الشركة</label>
                        <select id="edit_model_company" class="form-select"><?php $coOpts = $conn->query("SELECT * FROM companies ORDER BY name"); while($co = $coOpts->fetch_assoc()): ?><option value="<?= $co['id'] ?>"><?= htmlspecialchars($co['name']) ?></option><?php endwhile; ?></select>
                    </div>
                    <div class="mb-3"><label class="form-label">الموديل</label><input type="text" id="edit_model_name" class="form-control" required></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary" id="saveModelEdit">حفظ</button>
                </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('editNameModal')?.addEventListener('show.bs.modal', function(e) {
        const b = e.relatedTarget;
        if (b?.dataset?.id) { document.getElementById('edit_name_id').value = b.dataset.id; document.getElementById('edit_name_val').value = b.dataset.name || ''; }
    });
    document.getElementById('saveNameEdit')?.addEventListener('click', function() {
        const fd = new FormData();
        fd.append('action', 'update');
        fd.append('id', document.getElementById('edit_name_id').value);
        fd.append('name', document.getElementById('edit_name_val').value);
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/device_names.php', { method: 'POST', body: fd }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message||'فشل'); });
    });
    document.querySelectorAll('.btn-del-name').forEach(b=>{ b.onclick=function(){ if(confirm('حذف اسم الجهاز؟')){ const u='api/device_names.php?action=delete&id='+this.dataset.id+(window.csrfToken?'&csrf_token='+window.csrfToken:''); fetch(u).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message); }); } }; });

    document.getElementById('editModelModal')?.addEventListener('show.bs.modal', function(e) {
        const b = e.relatedTarget;
        if (b?.dataset?.id) {
            document.getElementById('edit_model_id').value = b.dataset.id;
            document.getElementById('edit_model_name').value = b.dataset.name || '';
            document.getElementById('edit_model_device').value = b.dataset.device || '';
            document.getElementById('edit_model_company').value = b.dataset.company || '';
        }
    });
    document.getElementById('saveModelEdit')?.addEventListener('click', function() {
        const fd = new FormData();
        fd.append('action', 'update');
        fd.append('id', document.getElementById('edit_model_id').value);
        fd.append('device_name_id', document.getElementById('edit_model_device').value);
        fd.append('company_id', document.getElementById('edit_model_company').value);
        fd.append('model_name', document.getElementById('edit_model_name').value);
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/device_models.php', { method: 'POST', body: fd }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message||'فشل'); });
    });
    document.querySelectorAll('.btn-del-model').forEach(b=>{ b.onclick=function(){ if(confirm('حذف الموديل؟')){ const u='api/device_models.php?action=delete&id='+this.dataset.id+(window.csrfToken?'&csrf_token='+window.csrfToken:''); fetch(u).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message); }); } }; });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
