

<?php $__env->startSection('title', 'Edit Device'); ?>

<?php $__env->startSection('content'); ?>
<style>
    .dv-form-card {
        background: #fff;
        border-radius: 14px;
        border: 1px solid rgba(0,0,0,0.06);
        box-shadow: 0 1px 3px rgba(13,43,94,0.06);
        padding: 28px 32px;
        max-width: 720px;
    }

    .dv-form-title {
        font-size: 18px;
        font-weight: 700;
        color: #0D2B5E;
        margin: 0 0 4px 0;
    }

    .dv-form-sub {
        font-size: 12.5px;
        color: rgba(0,0,0,0.45);
        margin: 0 0 24px 0;
    }

    .dv-field { margin-bottom: 16px; }

    .dv-field label {
        display: block;
        font-size: 12px;
        font-weight: 600;
        color: #0D2B5E;
        margin-bottom: 6px;
    }

    .dv-field .dv-hint {
        font-size: 11px;
        color: rgba(0,0,0,0.4);
        margin-top: 4px;
        display: block;
    }

    .dv-field input,
    .dv-field select {
        width: 100%;
        padding: 9px 12px;
        border-radius: 8px;
        border: 1px solid rgba(0,0,0,0.12);
        font-size: 13px;
        font-family: inherit;
        color: rgba(0,0,0,0.8);
        background: #fff;
    }

    .dv-field input:focus,
    .dv-field select:focus {
        outline: none;
        border-color: #0D2B5E;
        box-shadow: 0 0 0 3px rgba(13,43,94,0.08);
    }

    .dv-field input[readonly] {
        background: rgba(13,43,94,0.03);
        color: rgba(0,0,0,0.55);
    }

    .dv-field select:disabled { background: #F7F9FC; color: rgba(0,0,0,0.35); }

    .dv-row { display: flex; gap: 14px; }
    .dv-row .dv-field { flex: 1; }

    .dv-checkbox-row {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 20px;
    }

    .dv-checkbox-row label {
        font-size: 12.5px;
        font-weight: 500;
        color: rgba(0,0,0,0.7);
        margin: 0;
    }

    .dv-alert-error {
        background: #fee2e2;
        color: #dc2626;
        padding: 11px 16px;
        border-radius: 8px;
        font-size: 12.5px;
        margin-bottom: 18px;
    }

    .dv-alert-error ul { margin: 0; padding-left: 18px; }

    .dv-form-actions {
        display: flex;
        gap: 10px;
        margin-top: 24px;
        padding-top: 20px;
        border-top: 1px solid rgba(0,0,0,0.06);
    }

    .dv-btn-primary {
        background: #F5B800;
        color: #0D2B5E;
        font-weight: 700;
        font-size: 12.5px;
        padding: 10px 20px;
        border-radius: 8px;
        border: none;
        cursor: pointer;
    }

    .dv-btn-primary:hover { background: #e0a600; }

    .dv-btn-ghost {
        background: #fff;
        color: rgba(0,0,0,0.55);
        font-weight: 600;
        font-size: 12.5px;
        padding: 10px 20px;
        border-radius: 8px;
        border: 1px solid rgba(0,0,0,0.12);
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        cursor: pointer;
    }

    .dv-btn-ghost:hover { border-color: #0D2B5E; color: #0D2B5E; }
    .dv-btn-ghost:disabled { opacity: 0.5; cursor: not-allowed; }

    .dv-btn-outline {
        margin-top: 6px;
        background: #fff;
        color: #0D2B5E;
        font-weight: 600;
        font-size: 11.5px;
        padding: 6px 12px;
        border-radius: 7px;
        border: 1px solid rgba(13,43,94,0.25);
        cursor: pointer;
        white-space: nowrap;
    }

    .dv-btn-outline:hover { background: rgba(13,43,94,0.05); }
    .dv-btn-outline:disabled { opacity: 0.5; cursor: not-allowed; }

    .dv-cap-box {
        border-radius: 8px;
        padding: 10px 14px;
        font-size: 11.5px;
        margin-top: 8px;
        display: none;
    }

    .dv-cap-box.success {
        background: #ecfdf5;
        color: #059669;
        display: block;
    }

    .dv-cap-box.error {
        background: #fee2e2;
        color: #dc2626;
        display: block;
    }

    .dv-facelib-status {
        display: none;
        margin-top: 6px;
        font-size: 11px;
    }
    .dv-facelib-status.ok { display: block; color: #16a34a; }
    .dv-facelib-status.fail { display: block; color: #dc2626; }
    .dv-facelib-status.loading { display: block; color: rgba(0,0,0,0.45); }
</style>

<div class="dv-form-card">
    <h1 class="dv-form-title">Edit Device: <?php echo e($device->name); ?></h1>
    <p class="dv-form-sub">Perbarui konfigurasi koneksi terminal absensi wajah ini</p>

    <?php if($errors->any()): ?>
        <div class="dv-alert-error">
            <ul>
                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <li><?php echo e($error); ?></li>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </ul>
        </div>
    <?php endif; ?>

    <form action="<?php echo e(route('devices.update', $device)); ?>" method="POST">
        <?php echo csrf_field(); ?>
        <?php echo method_field('PUT'); ?>

        <div class="dv-field">
            <label>Nama Device</label>
            <input type="text" name="name" value="<?php echo e(old('name', $device->name)); ?>" required>
        </div>

        <div class="dv-field">
            <label>Lokasi (opsional)</label>
            <input type="text" name="location" value="<?php echo e(old('location', $device->location)); ?>">
        </div>

        <div class="dv-row">
            <div class="dv-field" style="flex: 2">
                <label>IP Address</label>
                <input type="text" name="ip_address" value="<?php echo e(old('ip_address', $device->ip_address)); ?>" required>
            </div>
            <div class="dv-field">
                <label>Port</label>
                <input type="number" name="port" value="<?php echo e(old('port', $device->port)); ?>" required>
            </div>
        </div>

        <div class="dv-row">
            <div class="dv-field">
                <label>Username Admin</label>
                <input type="text" name="username" value="<?php echo e(old('username', $device->username)); ?>" required>
            </div>
            <div class="dv-field">
                <label>Password Admin</label>
                <input type="password" name="password" placeholder="Kosongkan jika tidak diubah">
            </div>
        </div>

        <div class="dv-row">
            <div class="dv-field">
                <label>FDID (Face Library ID)</label>
                <input type="text" name="fdid" id="fdid" value="<?php echo e(old('fdid', $device->fdid)); ?>" required>
                <button type="button" id="check-fdid-btn" class="dv-btn-outline">Cek dari Device</button>
                <div id="fdid-status" class="dv-facelib-status"></div>
            </div>
            <div class="dv-field">
                <label>Face Lib Type</label>
                <input type="text" name="face_lib_type" id="face_lib_type"
                       value="<?php echo e(old('face_lib_type', $device->face_lib_type)); ?>" required readonly>
                <span class="dv-hint">Diisi otomatis dari device lewat tombol di bawah - bukan pilihan manual, karena device cuma support 1 tipe tertentu.</span>
            </div>
            <div class="dv-field">
                <label>Nomor Pintu (doorNo)</label>
                <input type="number" name="door_no" id="door_no" value="<?php echo e(old('door_no', $device->door_no)); ?>" required>
                <button type="button" id="check-door-btn" class="dv-btn-outline">Cek dari Device</button>
                <div id="door-status" class="dv-facelib-status"></div>
            </div>
        </div>

        <div class="dv-field">
            <button type="button" id="check-device-btn" class="dv-btn-ghost">
                Cek Device &amp; Ambil Face Lib Type
            </button>
            <div id="cap-result" class="dv-cap-box"></div>
        </div>

        <div class="dv-field">
            <label>Mode Device</label>
            <select name="mode" id="mode" required>
                <option value="absen_pintu" <?php echo e(old('mode', $device->mode) === 'absen_pintu' ? 'selected' : ''); ?>>
                    Absen + Buka Pintu (accessControlMode)
                </option>
                <option value="absen_only" <?php echo e(old('mode', $device->mode) === 'absen_only' ? 'selected' : ''); ?>>
                    Absen Saja (passMode)
                </option>
            </select>
            <span class="dv-hint">Kalau mode ini diubah &amp; disimpan, sistem otomatis mengirim perubahan workMode ke device fisiknya.</span>
            <div style="display:flex; gap:8px; margin-top:6px;">
                <button type="button" id="check-workmode-btn" class="dv-btn-outline">Cek dari Device</button>
                <button type="button" id="apply-workmode-btn" class="dv-btn-outline">Terapkan ke Device</button>
            </div>
            <div id="workmode-status" class="dv-facelib-status"></div>
        </div>

        <div class="dv-checkbox-row">
            <input type="checkbox" name="is_active" value="1" id="is_active" <?php echo e($device->is_active ? 'checked' : ''); ?>>
            <label for="is_active">Aktif — dipakai untuk registrasi siswa & pull absensi</label>
        </div>

        <div class="dv-form-actions">
            <button type="submit" class="dv-btn-primary">Simpan Perubahan</button>
            <a href="<?php echo e(route('devices.index')); ?>" class="dv-btn-ghost">Batal</a>
        </div>
    </form>
</div>

<script>
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '<?php echo e(csrf_token()); ?>';

    async function postDeviceCheck(routeUrl) {
        const res = await fetch(routeUrl, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
            },
        });
        return res.json();
    }

    // ================= Cek Device & Ambil Face Lib Type (sudah ada sebelumnya) =================
    document.getElementById('check-device-btn').addEventListener('click', function () {
        const btn = this;
        const resultBox = document.getElementById('cap-result');

        btn.disabled = true;
        btn.textContent = 'Menghubungi device...';
        resultBox.className = 'dv-cap-box';
        resultBox.textContent = '';

        fetch("<?php echo e(route('devices.capabilities', $device)); ?>", {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
            },
        })
            .then(res => res.json().then(data => ({ ok: res.ok, data })))
            .then(({ ok, data }) => {
                btn.disabled = false;
                btn.textContent = 'Cek Device & Ambil Face Lib Type';

                if (!ok || !data.success) {
                    resultBox.className = 'dv-cap-box error';
                    resultBox.textContent = data.message || 'Gagal mengambil kapabilitas device.';
                    return;
                }

                document.getElementById('face_lib_type').value = data.face_lib_type ?? '';

                resultBox.className = 'dv-cap-box success';
                resultBox.textContent = `Face Lib Type: ${data.face_lib_type} · Maks ${data.fd_max_num} library, ${data.fd_record_data_max_num} wajah/library.`;
            })
            .catch(() => {
                btn.disabled = false;
                btn.textContent = 'Cek Device & Ambil Face Lib Type';
                resultBox.className = 'dv-cap-box error';
                resultBox.textContent = 'Gagal terhubung ke server.';
            });
    });

    // ================= Cek FDID =================
    document.getElementById('check-fdid-btn').addEventListener('click', async function () {
        const btn = this;
        const status = document.getElementById('fdid-status');

        btn.disabled = true;
        status.className = 'dv-facelib-status loading';
        status.textContent = 'Menghubungi device...';

        try {
            const data = await postDeviceCheck("<?php echo e(route('devices.fdid', $device)); ?>");

            if (data.success) {
                if (!data.libraries || data.libraries.length === 0) {
                    status.className = 'dv-facelib-status ok';
                    status.textContent = data.message || 'Belum ada FDLib di device ini.';
                } else {
                    const used = data.libraries
                        .map(l => `${l.fdid} (${l.face_lib_type ?? '-'}${l.name ? ', ' + l.name : ''})`)
                        .join(', ');
                    status.className = 'dv-facelib-status ok';
                    status.textContent = `FDID yang sudah dipakai: ${used}.`;
                }
            } else {
                status.className = 'dv-facelib-status fail';
                status.textContent = data.message;
            }
        } catch (e) {
            status.className = 'dv-facelib-status fail';
            status.textContent = 'Gagal menghubungi server: ' + e.message;
        } finally {
            btn.disabled = false;
        }
    });

    // ================= Cek Nomor Pintu (doorNo) =================
    document.getElementById('check-door-btn').addEventListener('click', async function () {
        const btn = this;
        const status = document.getElementById('door-status');
        const doorInput = document.getElementById('door_no');

        btn.disabled = true;
        status.className = 'dv-facelib-status loading';
        status.textContent = 'Menghubungi device...';

        try {
            const data = await postDeviceCheck("<?php echo e(route('devices.door-capabilities', $device)); ?>");

            if (data.success) {
                doorInput.min = data.min;
                doorInput.max = data.max;
                status.className = 'dv-facelib-status ok';
                status.textContent = `Device support pintu: ${data.doors.join(', ')}`;
            } else {
                status.className = 'dv-facelib-status fail';
                status.textContent = data.message;
            }
        } catch (e) {
            status.className = 'dv-facelib-status fail';
            status.textContent = 'Gagal menghubungi server: ' + e.message;
        } finally {
            btn.disabled = false;
        }
    });

    // ================= Cek Mode (workMode) dari device =================
    document.getElementById('check-workmode-btn').addEventListener('click', async function () {
        const btn = this;
        const status = document.getElementById('workmode-status');
        const select = document.getElementById('mode');

        btn.disabled = true;
        status.className = 'dv-facelib-status loading';
        status.textContent = 'Menghubungi device...';

        try {
            const data = await postDeviceCheck("<?php echo e(route('devices.work-mode', $device)); ?>");

            if (data.success && data.mode) {
                select.value = data.mode;
                status.className = 'dv-facelib-status ok';
                status.textContent = `Device saat ini: ${data.device_work_mode}`;
            } else {
                status.className = 'dv-facelib-status fail';
                status.textContent = data.message || 'workMode device tidak dikenali.';
            }
        } catch (e) {
            status.className = 'dv-facelib-status fail';
            status.textContent = 'Gagal menghubungi server: ' + e.message;
        } finally {
            btn.disabled = false;
        }
    });

    // ================= Terapkan mode yang dipilih KE device =================
    document.getElementById('apply-workmode-btn').addEventListener('click', async function () {
        const btn = this;
        const status = document.getElementById('workmode-status');
        const select = document.getElementById('mode');

        if (!confirm(`Terapkan mode "${select.options[select.selectedIndex].text}" ke device sekarang?`)) {
            return;
        }

        btn.disabled = true;
        status.className = 'dv-facelib-status loading';
        status.textContent = 'Menerapkan ke device...';

        try {
            const res = await fetch("<?php echo e(route('devices.apply-work-mode', $device)); ?>", {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
            });

            // Route ini didesain buat redirect back() dengan flash message (bukan JSON murni),
            // jadi paling aman langsung reload halaman biar flash message-nya kebaca normal.
            window.location.reload();
        } catch (e) {
            status.className = 'dv-facelib-status fail';
            status.textContent = 'Gagal menghubungi server: ' + e.message;
            btn.disabled = false;
        }
    });
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH E:\laragon\www\maiadminweb\resources\views/devices/edit.blade.php ENDPATH**/ ?>