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

$governorates = $conn->query("SELECT * FROM governorates ORDER BY name_ar");
$sectors_r = @$conn->query("SELECT name FROM sectors WHERE (for_hospitals=1 OR for_hospitals IS NULL) ORDER BY name") ?: @$conn->query("SELECT name FROM sectors ORDER BY name");
$sectors_for_hospitals = [];
if ($sectors_r) { while ($sr = $sectors_r->fetch_assoc()) $sectors_for_hospitals[] = $sr; }
$companies = $conn->query("SELECT * FROM companies ORDER BY name");
// جلب قائمة المستشفيات مباشرة لضمان التحميل في نافذة الاختيار
$hospitals_list = [];
$hr = @$conn->query("SELECT h.*, (SELECT g.name_ar FROM governorates g WHERE g.id = h.governorate_id LIMIT 1) as gov_name FROM hospitals h ORDER BY h.name");
if ($hr) { while ($h = $hr->fetch_assoc()) $hospitals_list[] = $h; }
$engineers = $conn->query("SELECT * FROM engineers ORDER BY name");
$device_names = $conn->query("SELECT * FROM device_names ORDER BY name");

$success = '';
$error = '';
$edit_id = (int)($_GET['id'] ?? 0);
$editDevice = null;
$formData = $_POST;

if ($edit_id) {
    $st = $conn->prepare("SELECT * FROM devices WHERE id = ?");
    $st->bind_param("i", $edit_id);
    $st->execute();
    $editDevice = $st->get_result()->fetch_assoc();
    if (!$editDevice) { header('Location: devices_list.php'); exit; }
    $formData = array_merge($editDevice ?: [], $formData);
    $stH = $conn->prepare("SELECT id FROM hospitals WHERE name = ? LIMIT 1");
    $stH->bind_param("s", $editDevice['hospital_name']);
    $stH->execute();
    $hRow = $stH->get_result()->fetch_assoc();
    if ($hRow) $formData['selected_hospital_id'] = $hRow['id'];
    $st2 = $conn->prepare("SELECT id FROM hospitals WHERE name = ? LIMIT 1");
    $st2->bind_param("s", $editDevice['hospital_name']);
    $st2->execute();
    $hr = $st2->get_result()->fetch_assoc();
    if ($hr) $formData['selected_hospital_id'] = $hr['id'];
    // الأرقام التسلسلية: من عمود serial_number (الصيغة الجديدة) أو من device_serials (القديمة)
    $editSerials = [];
    if (!empty($editDevice['serial_number'])) {
        $editSerials = [$editDevice['serial_number']];
    } else {
        $serials_r = $conn->prepare("SELECT serial_number FROM device_serials WHERE device_id = ? ORDER BY id");
        $serials_r->bind_param("i", $edit_id);
        $serials_r->execute();
        $serials_res = $serials_r->get_result();
        while ($sr = $serials_res->fetch_assoc()) $editSerials[] = $sr['serial_number'];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (function_exists('require_csrf')) require_csrf();
    if (!canEdit()) { header('Location: devices.php'); exit; }
    $invoice_number = trim($_POST['invoice_number'] ?? '');
    $customer_id = (int)($_POST['customer_id'] ?? 0);
    $selected_hospital_id = (int)($_POST['selected_hospital_id'] ?? 0);
    // إذا لم يُحدد customer_id ولكن وُجد hospital_id، جلب/إنشاء الزبون من المستشفى
    if (!$customer_id && $selected_hospital_id) {
        $st0 = $conn->prepare("SELECT name, phone, governorate_id FROM hospitals WHERE id = ?");
        $st0->bind_param("i", $selected_hospital_id);
        $st0->execute();
        $h = $st0->get_result()->fetch_assoc();
        if ($h) {
            $name = trim($h['name']);
            $st1 = $conn->prepare("SELECT id FROM customers WHERE name = ? AND (hospital_name = ? OR hospital_name IS NULL) LIMIT 1");
            $st1->bind_param("ss", $name, $name);
            $st1->execute();
            $row = $st1->get_result()->fetch_assoc();
            if ($row) $customer_id = (int)$row['id'];
            else {
                $st = $conn->prepare("INSERT INTO customers (name, hospital_name, phone, governorate_id) VALUES (?, ?, ?, ?)");
                $st->bind_param("sssi", $name, $name, $h['phone'], $h['governorate_id']);
                if ($st->execute()) $customer_id = $conn->insert_id;
            }
        }
    }
    $hospital_name = trim($_POST['hospital_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $governorate_id = (int)($_POST['governorate_id'] ?? 0);
    $device_name_id = (int)($_POST['device_name_id'] ?? 0);
    $device_model_id = (int)($_POST['device_model_id'] ?? 0);
    $company_id = (int)($_POST['company_id'] ?? 0);
    $quantity = max(1, (int)($_POST['quantity'] ?? 1));
    $installation_date = $_POST['installation_date'] ?? '';
    $warranty_months = max(1, (int)($_POST['warranty_months'] ?? 12));
    $engineer_id = (int)($_POST['engineer_id'] ?? 0);
    $visit_type = trim($_POST['visit_type'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $image_path = trim($_POST['job_sheet_image_path'] ?? '');
    
    $serials = [];
    for ($i = 1; $i <= $quantity; $i++) {
        $s = trim($_POST["serial_$i"] ?? '');
        if (!empty($s)) $serials[] = $s;
    }
    
    if (empty($customer_id) || empty($hospital_name) || empty($phone) || 
        empty($governorate_id) || empty($device_name_id) || empty($device_model_id) || empty($company_id) || 
        empty($installation_date) || empty($engineer_id) || empty($visit_type)) {
        $error = 'يرجى تعبئة جميع الحقول المطلوبة';
    } elseif (!preg_match('/^07\d{9}$/', $phone)) {
        $error = 'رقم الهاتف يجب أن يبدأ بـ 07 ويتكون من 11 رقم';
    } else {
        $device_id_post = (int)($_POST['device_id'] ?? 0);
        $is_update = ($device_id_post > 0);
        
        if ($is_update) {
            $first_serial = !empty($serials) ? $serials[0] : '';
            $stmt = $conn->prepare("UPDATE devices SET invoice_number=?, customer_id=?, hospital_name=?, phone=?, governorate_id=?, 
                device_name_id=?, device_model_id=?, company_id=?, quantity=?, serial_number=?, installation_date=?, warranty_months=?, engineer_id=?, visit_type=?, notes=? WHERE id=?");
            $stmt->bind_param("sisssiiissiissii", $invoice_number, $customer_id, $hospital_name, $phone, $governorate_id,
                $device_name_id, $device_model_id, $company_id, $quantity, $first_serial, $installation_date, $warranty_months, $engineer_id, $visit_type, $notes, $device_id_post);
            $ok = $stmt->execute();
            $device_id = $device_id_post;
            if ($ok && function_exists('logActivity')) logActivity('update', 'devices', $device_id, $invoice_number . ' - ' . $hospital_name);
            if ($ok) {
                $conn->query("DELETE FROM device_serials WHERE device_id = " . (int)$device_id);
                if (!empty($image_path)) {
                    $st3 = $conn->prepare("INSERT INTO job_sheet_images (device_id, invoice_number, image_path) VALUES (?, ?, ?)");
                    $st3->bind_param("iss", $device_id, $invoice_number, $image_path);
                    $st3->execute();
                }
                $success = 'تم تحديث الجهاز بنجاح';
                header('Location: devices.php?id=' . $device_id . '&updated=1');
                exit;
            }
        } else {
            // إدراج سطر منفصل لكل رقم تسلسلي - كل سطر فيه نفس المعلومات + رقم تسلسلي واحد
            $rowsToInsert = !empty($serials) ? $serials : [''];
            $serial_val = '';
            $insertStmt = $conn->prepare("INSERT INTO devices (invoice_number, customer_id, hospital_name, phone, governorate_id, 
                device_name_id, device_model_id, company_id, quantity, serial_number, installation_date, warranty_months, engineer_id, visit_type, notes) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?)");
            $insertStmt->bind_param("sissiiiissiiss", $invoice_number, $customer_id, $hospital_name, $phone, $governorate_id,
                $device_name_id, $device_model_id, $company_id, $serial_val, $installation_date, $warranty_months, $engineer_id, $visit_type, $notes);
            
            $inserted = 0;
            foreach ($rowsToInsert as $sn) {
                $serial_val = is_string($sn) && $sn !== '' ? $sn : '';
                if ($insertStmt->execute()) {
                    $device_id = $conn->insert_id;
                    if (function_exists('logActivity')) logActivity('add', 'devices', $device_id, $invoice_number . ' - ' . $hospital_name . ($serial_val !== '' ? ' (' . $serial_val . ')' : ''));
                    if (!empty($image_path)) {
                        $st3 = $conn->prepare("INSERT INTO job_sheet_images (device_id, invoice_number, image_path) VALUES (?, ?, ?)");
                        $st3->bind_param("iss", $device_id, $invoice_number, $image_path);
                        $st3->execute();
                    }
                    $inserted++;
                }
            }
            if ($inserted > 0) {
                $success = 'تم إضافة الجهاز بنجاح' . ($inserted > 1 ? " ($inserted أجهزة)" : '');
                $_POST = [];
            }
        }
        if (empty($success) && empty($error)) $error = 'حدث خطأ أثناء الحفظ';
    }
}
?>
<!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="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.rtl.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid py-4">
            <h2 class="page-title mb-4"><i class="bi bi-cpu"></i> <?= $edit_id ? 'تعديل جهاز' : 'إدخال بيانات الأجهزة' ?></h2>
            
            <?php if ($success || !empty($_GET['updated'])): ?><div class="alert alert-success"><?= $success ?: 'تم تحديث الجهاز بنجاح' ?></div><?php endif; ?>
            <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
            
            <?php if (!canEdit()): ?>
            <div class="alert alert-warning"><i class="bi bi-lock me-2"></i>ليس لديك صلاحية إضافة أجهزة. يمكنك فقط عرض البيانات.</div>
            <?php endif; ?>
            
            <?php if (canEdit()): ?>
            <div class="card">
                <div class="card-body">
                    <form method="POST" action="<?= $edit_id ? '?id=' . $edit_id : '' ?>" id="deviceForm" accept-charset="UTF-8">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <?php if ($edit_id): ?><input type="hidden" name="device_id" value="<?= $edit_id ?>"><?php endif; ?>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">رقم الفاتورة</label>
                                <input type="text" name="invoice_number" class="form-control" 
                                    value="<?= htmlspecialchars($formData['invoice_number'] ?? '') ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">اسم الزبون (المستشفى)</label>
                                <div class="input-group">
                                    <input type="text" id="customer_display" class="form-control" placeholder="اضغط للاختيار المستشفى" readonly 
                                        style="cursor:pointer" data-bs-toggle="modal" data-bs-target="#customerModal" value="<?= htmlspecialchars($formData['hospital_name'] ?? '') ?>">
                                    <input type="hidden" name="customer_id" id="customer_id" value="<?= $formData['customer_id'] ?? '' ?>">
                                    <input type="hidden" name="selected_hospital_id" id="selected_hospital_id" value="<?= $formData['selected_hospital_id'] ?? '' ?>">
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">اسم المستشفى</label>
                                <input type="text" name="hospital_name" id="hospital_name" class="form-control" required 
                                    value="<?= htmlspecialchars($formData['hospital_name'] ?? '') ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">رقم الهاتف (07xxxxxxxx)</label>
                                <input type="tel" name="phone" class="form-control" pattern="07[0-9]{9}" maxlength="11" required 
                                    value="<?= htmlspecialchars($formData['phone'] ?? '') ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">المحافظة</label>
                                <select name="governorate_id" class="form-select select-search" required>
                                    <option value="">اختر المحافظة</option>
                                    <?php $governorates->data_seek(0); while ($g = $governorates->fetch_assoc()): ?>
                                    <option value="<?= $g['id'] ?>" <?= (($formData['governorate_id'] ?? '') == $g['id']) ? 'selected' : '' ?>><?= htmlspecialchars($g['name_ar']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">اسم الجهاز</label>
                                <select name="device_name_id" id="device_name_id" class="form-select select-search" required>
                                    <option value="">-- اختر --</option>
                                    <?php $device_names->data_seek(0); while ($dn = $device_names->fetch_assoc()): ?>
                                    <option value="<?= $dn['id'] ?>" <?= (($formData['device_name_id'] ?? '') == $dn['id']) ? 'selected' : '' ?>><?= htmlspecialchars($dn['name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">الشركة</label>
                                <select name="company_id" id="company_id" class="form-select select-search" required>
                                    <option value=""><?= ($formData['device_name_id'] ?? '') ? 'جاري التحميل...' : 'اختر الجهاز أولاً' ?></option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">موديل الجهاز</label>
                                <select name="device_model_id" id="device_model_id" class="form-select select-search" required>
                                    <option value="">-- اختر الجهاز والشركة أولاً --</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">العدد</label>
                                <input type="number" name="quantity" id="quantity" class="form-control" min="1" value="<?= $formData['quantity'] ?? 1 ?>" required>
                            </div>
                        </div>
                        
                        <div class="row" id="serialNumbersContainer">
                            <div class="col-12 mb-2" id="serialLabelOnce"><label class="form-label">الرقم التسلسلي</label></div>
                            <?php 
                            $qtyInit = (int)($formData['quantity'] ?? 1);
                            $serialsInit = $editSerials ?? [];
                            for ($i = 1; $i <= max(1, $qtyInit); $i++): 
                                $sv = $serialsInit[$i-1] ?? '';
                            ?>
                            <div class="col-12 col-md-6 mb-2" id="serial_<?= $i ?>"><input type="text" name="serial_<?= $i ?>" class="form-control" placeholder="الرقم <?= $i ?>" value="<?= htmlspecialchars($sv) ?>"></div>
                            <?php endfor; ?>
                        </div>
                        
                        <div class="row mt-2">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">تاريخ التنصيب</label>
                                <input type="date" name="installation_date" class="form-control" required value="<?= $formData['installation_date'] ?? '' ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">فترة الضمان (بالأشهر)</label>
                                <input type="number" name="warranty_months" class="form-control" min="1" value="<?= $formData['warranty_months'] ?? 12 ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">المهندس المسؤول</label>
                                <select name="engineer_id" class="form-select select-search" required>
                                    <option value="">-- اختر --</option>
                                    <?php $engineers->data_seek(0); while ($e = $engineers->fetch_assoc()): ?>
                                    <option value="<?= $e['id'] ?>" <?= (($formData['engineer_id'] ?? '') == $e['id']) ? 'selected' : '' ?>><?= htmlspecialchars($e['name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">تفاصيل الزيارة</label>
                                <select name="visit_type" class="form-select" required>
                                    <option value="">-- اختر --</option>
                                    <option value="صيانة" <?= (($formData['visit_type'] ?? '') == 'صيانة') ? 'selected' : '' ?>>صيانة</option>
                                    <option value="تنصيب" <?= (($formData['visit_type'] ?? '') == 'تنصيب') ? 'selected' : '' ?>>تنصيب</option>
                                    <option value="صيانة دورية" <?= (($formData['visit_type'] ?? '') == 'صيانة دورية') ? 'selected' : '' ?>>صيانة دورية</option>
                                    <option value="تدريب" <?= (($formData['visit_type'] ?? '') == 'تدريب') ? 'selected' : '' ?>>تدريب</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">صورة الجوب شيت</label>
                                <div class="input-group">
                                    <input type="file" id="imageInput" class="form-control" accept="image/*">
                                    <input type="hidden" name="job_sheet_image_path" id="job_sheet_image_path">
                                    <span class="input-group-text" id="imageStatus">لم يتم الرفع</span>
                                </div>
                                <small class="text-muted">يتم الحفظ حسب رقم الفاتورة وتاريخ الإدخال</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">الملاحظات</label>
                                <textarea name="notes" class="form-control" rows="2"><?= htmlspecialchars($formData['notes'] ?? '') ?></textarea>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> حفظ</button>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- نافذة اختيار المستشفى (الزبون) -->
    <div class="modal fade" id="customerModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <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="text" id="customerSearch" class="form-control mb-3" placeholder="بحث عن مستشفى...">
                    <div class="list-group overflow-auto" id="customerList" style="max-height:300px"></div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
    function apiUrl(path) { return new URL(path, window.location.href).href; }
    // قائمة المستشفيات محمّلة من السيرفر - تضمن عدم فشل التحميل
    window.HOSPITALS_DATA = <?= json_encode($hospitals_list ?? [], JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?: '[]' ?>;
    window.FORM_DATA = <?= json_encode(['company_id' => $formData['company_id'] ?? '', 'device_model_id' => $formData['device_model_id'] ?? ''], JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
    </script>
    <script>
    document.getElementById('quantity').addEventListener('change', function() {
        const q = parseInt(this.value) || 1;
        const container = document.getElementById('serialNumbersContainer');
        container.querySelectorAll('[id^="serial_"]').forEach(el => el.remove());
        for (let i = 1; i <= q; i++) {
            const col = document.createElement('div');
            col.className = 'col-12 col-md-6 mb-2';
            col.id = 'serial_' + i;
            col.innerHTML = '<input type="text" name="serial_' + i + '" class="form-control" placeholder="رقم ' + i + '">';
            container.appendChild(col);
        }
    });
    
    function loadCompanies() {
        const dn = ($('#device_name_id').val() || '').toString().trim();
        const $sel = $('#company_id');
        if ($sel.data('select2')) $sel.select2('destroy');
        $sel.empty().append('<option value="">اختر الشركة</option>');
        $('#device_model_id').empty().append('<option value="">اختر الجهاز والشركة أولاً</option>');
        if ($('#device_model_id').data('select2')) $('#device_model_id').select2('destroy');
        $('#device_model_id').select2({ theme: 'bootstrap-5', dir: 'rtl', width: '100%', language: { noResults: function() { return 'لا توجد نتائج'; } } });
        if (!dn) {
            $sel.html('<option value="">اختر الجهاز أولاً</option>');
            $sel.select2({ theme: 'bootstrap-5', dir: 'rtl', width: '100%', language: { noResults: function() { return 'لا توجد نتائج'; } } });
            return Promise.resolve();
        }
        $sel.html('<option value="">جاري التحميل...</option>');
        return fetch(apiUrl('api/device_models.php?action=companies&device_name_id=' + encodeURIComponent(dn)))
            .then(r => { if (!r.ok) throw new Error('خطأ ' + r.status); return r.json(); })
            .then(d => {
                $sel.empty().append('<option value="">اختر الشركة</option>');
                (d.data || []).forEach(c => {
                    $sel.append('<option value="' + c.id + '">' + (c.name || '') + '</option>');
                });
                if (!d.data || d.data.length === 0) $sel.html('<option value="">لا توجد شركات لهذا الجهاز - أضف من الإعدادات</option>');
                $sel.select2({ theme: 'bootstrap-5', dir: 'rtl', width: '100%', language: { noResults: function() { return 'لا توجد نتائج'; } } });
            })
            .catch(function(err) { $sel.html('<option value="">فشل التحميل</option>'); $sel.select2({ theme: 'bootstrap-5', dir: 'rtl', width: '100%' }); console.error('loadCompanies:', err); });
    }
    
    function loadModels(selectModelId) {
        const dn = ($('#device_name_id').val() || '').toString().trim();
        const co = ($('#company_id').val() || '').toString().trim();
        const $sel = $('#device_model_id');
        if ($sel.data('select2')) $sel.select2('destroy');
        $sel.empty().append('<option value="">اختر الموديل</option>');
        if (!dn || !co) {
            $sel.html('<option value="">اختر الجهاز والشركة أولاً</option>');
            $sel.select2({ theme: 'bootstrap-5', dir: 'rtl', width: '100%', language: { noResults: function() { return 'لا توجد نتائج'; } } });
            return;
        }
        $sel.html('<option value="">جاري التحميل...</option>');
        fetch(apiUrl('api/device_models.php?device_name_id=' + encodeURIComponent(dn) + '&company_id=' + encodeURIComponent(co)))
            .then(r => { if (!r.ok) throw new Error('خطأ ' + r.status); return r.json(); })
            .then(d => {
                $sel.empty().append('<option value="">اختر الموديل</option>');
                (d.data || []).forEach(m => {
                    $sel.append('<option value="' + m.id + '">' + (m.model_name || '') + '</option>');
                });
                if (!d.data || d.data.length === 0) $sel.html('<option value="">لا يوجد موديلات - أضف من الإعدادات</option>');
                $sel.select2({ theme: 'bootstrap-5', dir: 'rtl', width: '100%', language: { noResults: function() { return 'لا توجد نتائج'; } } });
                var toSelect = selectModelId || (window.SELECT_MODEL_ID ? window.SELECT_MODEL_ID : null);
                if (toSelect) { $sel.val(toSelect).trigger('change'); window.SELECT_MODEL_ID = null; }
            })
            .catch(function(err) { $sel.html('<option value="">فشل التحميل - حاول مرة أخرى</option>'); $sel.select2({ theme: 'bootstrap-5', dir: 'rtl', width: '100%' }); console.error('loadModels:', err); });
    }
    
    $(function() {
        $('.select-search').select2({
            theme: 'bootstrap-5',
            dir: 'rtl',
            width: '100%',
            language: { noResults: function() { return 'لا توجد نتائج'; }, searching: function() { return 'جاري البحث...'; } }
        });
        $('#device_name_id').on('change select2:select', function() {
            loadCompanies();
        });
        $('#company_id').on('change select2:select', function() { loadModels(); });
        var dnVal = $('#device_name_id').val();
        if (dnVal) {
            var fd = window.FORM_DATA || {};
            loadCompanies().then(function() {
                if (fd.company_id) {
                    window.SELECT_MODEL_ID = fd.device_model_id || null;
                    $('#company_id').val(fd.company_id).trigger('change');
                }
            });
        }
    });
    
    // Customer modal - يعرض المستشفيات من البيانات المحمّلة مع الصفحة (لا يعتمد على API)
    function loadHospitalList(q) {
        const listEl = document.getElementById('customerList');
        const data = (window.HOSPITALS_DATA || []);
        const search = (q || '').toLowerCase().trim();
        const filtered = search ? data.filter(h => {
            const name = (h.name || '').toLowerCase();
            const gov = (h.gov_name || '').toLowerCase();
            return name.includes(search) || gov.includes(search);
        }) : data;
        let html = '';
        filtered.forEach(h => {
            html += '<a href="#" class="list-group-item list-group-item-action" data-hospital-id="' + h.id + '" data-name="' + (h.name||'') + '" data-phone="' + (h.phone||'') + '" data-gov="' + (h.governorate_id||'') + '"><i class="bi bi-hospital me-2"></i>' + (h.name || '') + (h.gov_name ? ' - ' + h.gov_name : '') + '</a>';
        });
        listEl.innerHTML = html || '<div class="p-3 text-muted">لا توجد مستشفيات' + (search ? ' مطابقة للبحث' : '') + '</div>';
        listEl.querySelectorAll('.list-group-item-action').forEach(el => {
            el.addEventListener('click', function(e) {
                e.preventDefault();
                const hid = this.dataset.hospitalId;
                const name = this.dataset.name || '';
                const phone = this.dataset.phone || '';
                const gov = this.dataset.gov || '';
                if (!hid) return;
                document.getElementById('selected_hospital_id').value = hid;
                document.getElementById('customer_display').value = name;
                document.querySelector('input[name="hospital_name"]').value = name;
                document.querySelector('input[name="phone"]').value = phone;
                $('select[name="governorate_id"]').val(gov || '').trigger('change');
                document.getElementById('selected_hospital_id').value = hid || '';
                bootstrap.Modal.getInstance(document.getElementById('customerModal')).hide();
                // جلب/إنشاء الزبون للحصول على customer_id
                const doFetch = (url, opts) => fetch(apiUrl(url), Object.assign({ credentials: 'same-origin' }, opts));
                const fd = new FormData();
                fd.append('action', 'get_or_create_from_hospital');
                fd.append('hospital_id', hid);
                if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
                doFetch('api/customers.php', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(res => {
                        if (res.success) {
                            document.getElementById('customer_id').value = res.id;
                        }
                    })
                    .catch(() => {});
                // إذا فشل POST جرّب GET كبديل
                doFetch('api/customers.php?action=get_or_create_from_hospital&hospital_id=' + hid + (window.csrfToken ? '&csrf_token=' + encodeURIComponent(window.csrfToken || '') : ''))
                    .then(r => r.json())
                    .then(res => {
                        if (res.success) document.getElementById('customer_id').value = res.id;
                    })
                    .catch(() => {});
            });
        });
    }
    document.getElementById('customerModal').addEventListener('show.bs.modal', function() {
        document.getElementById('customerSearch').value = '';
        loadHospitalList('');
    });
    document.getElementById('customerSearch').addEventListener('input', function() {
        loadHospitalList(this.value);
    });
    
    // Image upload
    document.getElementById('imageInput').addEventListener('change', function() {
        const file = this.files[0];
        const inv = document.querySelector('input[name="invoice_number"]').value;
        if (!file) return;
        const fd = new FormData();
        fd.append('image', file);
        fd.append('invoice_number', inv || '');
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch(apiUrl('api/upload_image.php'), { method: 'POST', body: fd })
            .then(r => r.json())
            .then(d => {
                if (d.success) {
                    document.getElementById('job_sheet_image_path').value = d.path;
                    document.getElementById('imageStatus').textContent = 'تم الرفع ✓';
                } else alert(d.message || 'فشل الرفع');
            });
    });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
