<x-app-layout>

@push('styles')
    <link rel="stylesheet" href="{{ asset('css/akunteknisi.css') }}">
    <link rel="stylesheet" href="{{ asset('css/tugas.css') }}">
    <style>
        .akt-inner { max-width: 1400px; }
        /* Custom adjustment for account status cards */
        .pug-stats { grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px; }
    </style>
@endpush

<div class="akt-wrap">
    <div class="akt-inner">

        {{-- ── PAGE HEADER ── --}}
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:30px;">
            <div style="display:flex; align-items:center; gap:15px;">
                <div class="pug-icon-wrap" style="width: 54px; height: 54px; font-size: 22px;">
                    <i class="fas fa-user-shield"></i>
                </div>
                <div>
                    <h1 class="pug-page-title" style="font-size: 24px;">Kelola Akun Teknisi</h1>
                    <p class="pug-page-sub">Manajemen akun & akses aplikasi teknisi lapangan</p>
                </div>
            </div>
            <button onclick="openCreateModal()" class="pug-btn-primary" style="padding: 12px 24px; border-radius: 12px;">
                <i class="fas fa-plus"></i> Tambah Akun Baru
            </button>
        </div>

        {{-- ── STATISTICS CARDS ── --}}
        <div class="pug-stats">
            <div class="pug-stat pug-stat-total" onclick="filterStatus('semua')" style="cursor: pointer;" title="Semua Akun">
                <div class="pug-stat-icon"><i class="fas fa-users"></i></div>
                <div class="pug-stat-label">TOTAL AKUN</div>
                <div class="pug-stat-val" id="stat-semua">{{ $akunTeknisis->count() }}</div>
                <div class="pug-page-sub" style="margin-top: 5px;">Semua akun terdaftar</div>
            </div>
            <div class="pug-stat pug-stat-selesai" onclick="filterStatus('aktif')" style="cursor: pointer;" title="Filter: Aktif">
                <div class="pug-stat-icon" style="background: var(--pug-green-l); color: var(--pug-green);"><i class="fas fa-check-circle"></i></div>
                <div class="pug-stat-label">AKUN AKTIF</div>
                <div class="pug-stat-val" id="stat-aktif">{{ $akunTeknisis->where('status','aktif')->count() }}</div>
                <div class="pug-page-sub" style="margin-top: 5px;">Memiliki akses aplikasi</div>
            </div>
            <div class="pug-stat pug-stat-garansi" onclick="filterStatus('tidak_aktif')" style="cursor: pointer;" title="Filter: Nonaktif">
                <div class="pug-stat-icon" style="background: var(--pug-rose-l); color: var(--pug-rose);"><i class="fas fa-times-circle"></i></div>
                <div class="pug-stat-label">NONAKTIF</div>
                <div class="pug-stat-val" id="stat-tidak_aktif">{{ $akunTeknisis->where('status','tidak_aktif')->count() }}</div>
                <div class="pug-page-sub" style="margin-top: 5px;">Akses akun dicabut</div>
            </div>
        </div>

        {{-- ── ALERT ── --}}
        <div id="akt-alert-msg" class="hidden"></div>

        {{-- ── TOOLBAR ── --}}
        <div class="pug-toolbar" style="margin-bottom: 24px; padding: 18px 24px;">
            <div class="pug-toolbar-form">
                <div class="pug-toolbar-item" style="flex: 1;">
                    <label class="pug-field-label">Cari Teknisi atau Username</label>
                    <div class="pug-input-icon">
                        <i class="fas fa-search"></i>
                        <input type="text" id="searchInput" class="pug-input" 
                               placeholder="Ketik nama atau username untuk memfilter..." 
                               onkeyup="searchTable()">
                    </div>
                </div>
                <div class="pug-toolbar-item item-btn" style="flex: 0 0 auto;">
                    <a href="javascript:void(0)" onclick="location.reload()" class="pug-reset-btn" style="height: 44px;">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </a>
                </div>
            </div>
        </div>

        {{-- ── PANEL TABLE ── --}}
        <div class="pug-panel">
            <div class="pug-panel-head">
                <div class="pug-panel-head-left">
                    <i class="fas fa-table"></i> DAFTAR AKUN TEKNISI
                </div>
                <div class="pug-panel-head-right" id="result-count">
                    Menampilkan {{ $akunTeknisis->count() }} akun terdaftar
                </div>
            </div>

            <div class="table-responsive">
                <table class="pug-table" id="teknisiTable">
                    <thead>
                        <tr>
                            <th width="60">#</th>
                            <th>Nama Teknisi</th>
                            <th>Username</th>
                            <th>Status Akun</th>
                            <th width="120">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($akunTeknisis as $index => $akun)
                        <tr class="table-row" 
                            data-status="{{ $akun->status }}"
                            data-nama="{{ strtolower($akun->teknisi->nama ?? '') }}"
                            data-username="{{ strtolower($akun->username) }}">
                            <td>
                                <span class="pug-rownum row-num">{{ str_pad($index + 1, 2, '0', STR_PAD_LEFT) }}</span>
                            </td>
                            <td>
                                <div style="display:flex; align-items:center; gap:12px;">
                                    <div class="pug-av">
                                        {{ strtoupper(substr($akun->teknisi->nama ?? 'T', 0, 1)) }}
                                    </div>
                                    <div>
                                        <div class="pug-av-name">{{ $akun->teknisi->nama ?? '—' }}</div>
                                        <div class="pug-av-sub">Teknisi Lapangan</div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span style="font-weight: 600; color: var(--pug-t2); background: #f1f5f9; padding: 4px 10px; border-radius: 8px; font-size: 13px;">
                                    <i class="fas fa-at" style="color: var(--pug-primary); margin-right: 4px; font-size: 11px;"></i>{{ $akun->username }}
                                </span>
                            </td>
                            <td>
                                <div style="display:flex; align-items:center; gap: 8px;">
                                    @if($akun->status == 'aktif')
                                        <span class="pug-badge pug-badge-green">
                                            <i class="fas fa-check-circle"></i> Aktif
                                        </span>
                                    @else
                                        <span class="pug-badge pug-badge-rose">
                                            <i class="fas fa-times-circle"></i> Nonaktif
                                        </span>
                                    @endif
                                    <button class="pug-action-btn" style="background: #f1f5f9; color: #64748b; border: none; width: 32px; height: 32px; font-size: 12px;"
                                            onclick="toggleStatus({{ $akun->id_akun_teknisi }}, '{{ $akun->status }}')"
                                            title="Ubah Status">
                                        <i class="fas fa-sync-alt"></i>
                                    </button>
                                </div>
                            </td>
                            <td>
                                <div class="pug-actions">
                                    <button class="pug-action-btn pug-action-view"
                                            onclick="openDetailModal({{ $akun->id_akun_teknisi }})"
                                            title="Detail Akun">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="pug-action-btn pug-action-edit"
                                            onclick="openEditModal({{ $akun->id_akun_teknisi }})"
                                            title="Edit Akun">
                                        <i class="fas fa-pen"></i>
                                    </button>
                                    <button class="pug-action-btn pug-action-del"
                                            onclick="deleteAkun({{ $akun->id_akun_teknisi }})"
                                            title="Hapus Akun">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr id="emptyRow">
                            <td colspan="5">
                                <div class="pug-empty">
                                    <div class="pug-empty-icon"><i class="fas fa-users-slash"></i></div>
                                    <div class="pug-empty-title">Belum Ada Akun Teknisi</div>
                                    <div class="pug-empty-sub">Silakan tambahkan akun untuk akses aplikasi teknisi.</div>
                                </div>
                            </td>
                        </tr>
                        @endforelse
                        <tr id="noResultRow" style="display:none;">
                            <td colspan="5">
                                <div class="pug-empty">
                                    <div class="pug-empty-icon"><i class="fas fa-search"></i></div>
                                    <div class="pug-empty-title">Akun Tidak Ditemukan</div>
                                    <div class="pug-empty-sub">Coba kata kunci atau filter status yang lain.</div>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

{{-- ── MODAL DETAIL AKUN ── --}}
<div id="detailModal" class="pug-overlay">
    <div class="pug-modal" style="max-width: 450px;">
        <div class="pug-modal-header">
            <div class="pug-modal-title"><i class="fas fa-info-circle"></i> DETAIL AKUN TEKNISI</div>
            <button class="pug-close-btn" onclick="closeModal('detailModal')"><i class="fas fa-times"></i></button>
        </div>
        <div id="detailContent" style="padding: 24px;">
            <div style="text-align: center; margin-bottom: 24px;">
                <div id="detAv" class="pug-av" style="width: 70px; height: 70px; font-size: 28px; margin: 0 auto 12px; background: var(--pug-primary-l); color: var(--pug-primary);"></div>
                <h3 id="detNama" style="font-size: 18px; font-weight: 700; color: #1e293b; margin-bottom: 6px;"></h3>
                <div id="detBadge"></div>
            </div>
            
            <div style="display: flex; flex-direction: column; gap: 16px; background: #f8fafc; padding: 20px; border-radius: 16px; border: 1px solid #f1f5f9;">
                <div>
                    <label style="font-size: 11px; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.5px;">Username Akses</label>
                    <div style="display: flex; align-items: center; gap: 8px; margin-top: 4px;">
                        <i class="fas fa-at" style="color: var(--pug-primary); font-size: 14px;"></i>
                        <span id="detUsername" style="font-size: 15px; font-weight: 700; color: #1e293b;"></span>
                    </div>
                </div>
                
                <div>
                    <label style="font-size: 11px; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.5px;">Password</label>
                    <div style="display: flex; align-items: center; gap: 8px; margin-top: 4px; color: #1e293b; font-size: 15px;">
                        <i class="fas fa-key" style="font-size: 13px; color: var(--pug-amber);"></i>
                        <span id="detPassword" style="font-weight: 700;"></span>
                    </div>
                    <p style="font-size: 10px; color: #94a3b8; margin-top: 4px; font-style: italic;">* Gunakan fitur 'Edit' untuk mereset password jika lupa.</p>
                </div>
                
                <div style="height: 1px; background: #f1f5f9;"></div>
                
                <div>
                    <label style="font-size: 11px; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.5px;">Informasi Akun</label>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 8px;">
                        <div>
                            <div style="font-size: 11px; color: #64748b;">ID Akun</div>
                            <div id="detIdAkun" style="font-size: 13px; font-weight: 600; color: #1e293b;"></div>
                        </div>
                        <div>
                            <div style="font-size: 11px; color: #64748b;">ID Teknisi</div>
                            <div id="detIdTek" style="font-size: 13px; font-weight: 600; color: #1e293b;"></div>
                        </div>
                        <div>
                            <div style="font-size: 11px; color: #64748b;">Terdaftar Sejak</div>
                            <div id="detTgl" style="font-size: 13px; font-weight: 600; color: #1e293b;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="pug-modal-footer">
            <button type="button" class="pug-btn-submit" onclick="closeModal('detailModal')" style="width: 100%;">Tutup Detail</button>
        </div>
    </div>
</div>

    </div>
</div>

{{-- ── MODAL TAMBAH ── --}}
<div id="createModal" class="pug-overlay">
    <div class="pug-modal pug-modal-sm">
        <div class="pug-modal-header">
            <div class="pug-modal-title"><i class="fas fa-user-plus"></i> TAMBAH AKUN TEKNISI</div>
            <button class="pug-close-btn" onclick="closeModal('createModal')"><i class="fas fa-times"></i></button>
        </div>
        <form id="createForm" onsubmit="submitCreate(event)">
            @csrf
            <div class="pug-form-grid" style="padding: 20px;">
                <div class="pug-form-full">
                    <label class="pug-form-label">Teknisi <span class="text-danger">*</span></label>
                    <select id="create_id_teknisi" name="id_teknisi" class="pug-select" required>
                        <option value=""> Pilih Teknisi </option>
                        @foreach($teknisis as $teknisi)
                        <option value="{{ $teknisi->id_teknisi }}">{{ $teknisi->nama }}</option>
                        @endforeach
                    </select>
                    <span class="text-danger small" id="error_create_id_teknisi"></span>
                </div>
                <div class="pug-form-full">
                    <label class="pug-form-label">Username <span class="text-danger">*</span></label>
                    <input type="text" id="create_username" name="username" class="pug-input" required autocomplete="off">
                    <span class="text-danger small" id="error_create_username"></span>
                </div>
                <div class="pug-form-full">
                    <label class="pug-form-label">Password <span class="text-danger">*</span></label>
                    <div style="position:relative;">
                        <input type="password" id="create_password" name="password" class="pug-input" required autocomplete="new-password">
                        <button type="button" onclick="togglePw('create_password', this)" style="position:absolute; right:12px; top:50%; transform:translateY(-50%); background:none; border:none; color:#94a3b8;">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <span class="text-danger small" id="error_create_password"></span>
                </div>
                <div class="pug-form-full">
                    <label class="pug-form-label">Status <span class="text-danger">*</span></label>
                    <select id="create_status" name="status" class="pug-select" required>
                        <option value="aktif">Aktif</option>
                        <option value="tidak_aktif">Tidak Aktif</option>
                    </select>
                </div>
            </div>
            <div class="pug-modal-footer">
                <button type="button" class="pug-btn-cancel" onclick="closeModal('createModal')">Batal</button>
                <button type="submit" class="pug-btn-submit">Simpan Akun</button>
            </div>
        </form>
    </div>
</div>

{{-- ── MODAL EDIT ── --}}
<div id="editModal" class="pug-overlay">
    <div class="pug-modal pug-modal-sm">
        <div class="pug-modal-header">
            <div class="pug-modal-title"><i class="fas fa-user-edit"></i> EDIT AKUN TEKNISI</div>
            <button class="pug-close-btn" onclick="closeModal('editModal')"><i class="fas fa-times"></i></button>
        </div>
        <form id="editForm" onsubmit="submitEdit(event)">
            @csrf @method('PUT')
            <input type="hidden" id="edit_id" name="id">
            <input type="hidden" id="edit_id_teknisi" name="id_teknisi">
            <div class="pug-form-grid" style="padding: 20px;">
                <div class="pug-form-full">
                    <label class="pug-form-label">Teknisi (Tidak dapat diubah)</label>
                    <input type="text" id="edit_nama_display" class="pug-input" disabled style="background:#f8fafc;">
                </div>
                <div class="pug-form-full">
                    <label class="pug-form-label">Username <span class="text-danger">*</span></label>
                    <input type="text" id="edit_username" name="username" class="pug-input" required>
                    <span class="text-danger small" id="error_edit_username"></span>
                </div>
                <div class="pug-form-full">
                    <label class="pug-form-label">Password <span class="text-muted">(Kosongkan jika tidak diubah)</span></label>
                    <div style="position:relative;">
                        <input type="password" id="edit_password" name="password" class="pug-input" autocomplete="new-password">
                        <button type="button" onclick="togglePw('edit_password', this)" style="position:absolute; right:12px; top:50%; transform:translateY(-50%); background:none; border:none; color:#94a3b8;">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                <div class="pug-form-full">
                    <label class="pug-form-label">Status <span class="text-danger">*</span></label>
                    <select id="edit_status" name="status" class="pug-select" required>
                        <option value="aktif">Aktif</option>
                        <option value="tidak_aktif">Tidak Aktif</option>
                    </select>
                </div>
            </div>
            <div class="pug-modal-footer">
                <button type="button" class="pug-btn-cancel" onclick="closeModal('editModal')">Batal</button>
                <button type="submit" class="pug-btn-submit">Simpan Perubahan</button>
            </div>
        </form>
    </div>
</div>

<script>
const appUrl = "{{ url('/') }}";
let currentFilter = 'semua';

function showAlert(message, type = 'success') {
    const el = document.getElementById('akt-alert-msg');
    el.className = type === 'success' ? 'akt-alert akt-alert-ok' : 'akt-alert akt-alert-err';
    el.innerHTML = `<i class="fas ${type==='success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i><span>${message}</span>`;
    el.classList.remove('hidden'); el.style.opacity = '1';
    setTimeout(() => { el.style.opacity = '0'; setTimeout(() => el.classList.add('hidden'), 400); }, 4500);
}

function togglePw(id, btn) {
    const inp = document.getElementById(id);
    const isText = inp.type === 'text';
    inp.type = isText ? 'password' : 'text';
    btn.querySelector('i').className = isText ? 'fas fa-eye' : 'fas fa-eye-slash';
}

function searchTable() {
    const q = document.getElementById('searchInput').value.toLowerCase();
    const rows = document.querySelectorAll('#teknisiTable .table-row');
    let vis = 0;
    rows.forEach(r => {
        const match = (r.dataset.nama.includes(q) || r.dataset.username.includes(q))
                   && (currentFilter === 'semua' || r.dataset.status === currentFilter);
        r.style.display = match ? '' : 'none';
        if (match) { vis++; r.querySelector('.row-num').textContent = (vis < 10 ? '0' : '') + vis; }
    });
    document.getElementById('noResultRow').style.display = vis === 0 ? '' : 'none';
    document.getElementById('result-count').textContent = 'Menampilkan ' + vis + ' akun ditemukan';
}

function filterStatus(status) {
    currentFilter = status;
    document.querySelectorAll('.pug-stat').forEach(b => b.classList.remove('active'));
    // Visual cue for active card filter
    const activeCard = document.querySelector(`.pug-stat[onclick*="${status}"]`);
    if(activeCard) activeCard.style.boxShadow = "0 10px 20px rgba(0,0,0,0.05), inset 0 -4px 0 var(--pug-primary)";
    searchTable();
}

function openModal(id)  { document.getElementById(id).classList.add('show'); }
function closeModal(id) { document.getElementById(id).classList.remove('show'); }

function openCreateModal() { document.getElementById('createForm').reset(); clearErrors('create'); openModal('createModal'); }

function openEditModal(id) {
    clearErrors('edit');
    fetch(`${appUrl}/akun-teknisi/${id}/edit`)
        .then(r => {
            if(!r.ok) throw new Error('Gagal mengambil data');
            return r.json();
        })
        .then(data => {
            document.getElementById('edit_id').value = data.id_akun_teknisi;
            document.getElementById('edit_id_teknisi').value = data.id_teknisi;
            document.getElementById('edit_nama_display').value = data.teknisi ? data.teknisi.nama : '—';
            document.getElementById('edit_username').value = data.username;
            document.getElementById('edit_status').value = data.status;
            document.getElementById('edit_password').value = '';
            openModal('editModal');
        })
        .catch(err => {
            console.error(err);
            alert('Gagal memuat data akun: ' + err.message);
        });
}

function openDetailModal(id) {
    // Gunakan route /show agar relasi teknisi terpanggil
    fetch(`${appUrl}/akun-teknisi/${id}`)
        .then(r => {
            if(!r.ok) throw new Error('Gagal mengambil detail');
            return r.json();
        })
        .then(data => {
            const nama = data.teknisi ? data.teknisi.nama : 'N/A';
            document.getElementById('detAv').textContent = nama.charAt(0).toUpperCase();
            document.getElementById('detNama').textContent = nama;
            document.getElementById('detUsername').textContent = data.username;
            document.getElementById('detPassword').textContent = data.password_plain || '—';
            document.getElementById('detIdAkun').textContent = '#' + data.id_akun_teknisi;
            document.getElementById('detIdTek').textContent = '#' + (data.id_teknisi || '—');
            
            const tgl = new Date(data.created_at).toLocaleDateString('id-ID', { day:'2-digit', month:'long', year:'numeric' });
            document.getElementById('detTgl').textContent = tgl;
            
            const badge = document.getElementById('detBadge');
            if(data.status === 'aktif') {
                badge.innerHTML = '<span class="pug-badge pug-badge-green"><i class="fas fa-check-circle"></i> Aktif</span>';
            } else {
                badge.innerHTML = '<span class="pug-badge pug-badge-rose"><i class="fas fa-times-circle"></i> Nonaktif</span>';
            }
            
            openModal('detailModal');
        })
        .catch(err => {
            console.error(err);
            alert('Gagal memuat detail: ' + err.message);
        });
}

function clearErrors(prefix) { document.querySelectorAll(`[id^="error_${prefix}"]`).forEach(el => el.textContent = ''); }

function showErrors(errors, prefix) {
    Object.keys(errors).forEach(k => {
        const el = document.getElementById(`error_${prefix}_${k}`);
        if (el) el.textContent = errors[k][0];
    });
}

function submitCreate(e) {
    e.preventDefault(); clearErrors('create');
    fetch('{{ route("akun-teknisi.store") }}', {
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
        body: new FormData(e.target)
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { showAlert(data.message); setTimeout(() => location.reload(), 1000); }
        else { if (data.errors) showErrors(data.errors, 'create'); showAlert(data.message || 'Gagal menyimpan', 'error'); }
    });
}

function submitEdit(e) {
    e.preventDefault(); clearErrors('edit');
    const id = document.getElementById('edit_id').value;
    fetch(`${appUrl}/akun-teknisi/${id}`, {
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
        body: new FormData(e.target)
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { showAlert(data.message); setTimeout(() => location.reload(), 1000); }
        else { if (data.errors) showErrors(data.errors, 'edit'); showAlert(data.message || 'Gagal update', 'error'); }
    });
}

function toggleStatus(id, cur) {
    const ns = cur === 'aktif' ? 'tidak_aktif' : 'aktif';
    if (!confirm(`Ubah status akun menjadi ${ns === 'aktif' ? 'AKTIF' : 'NONAKTIF'}?`)) return;
    fetch(`${appUrl}/akun-teknisi/${id}/update-status`, {
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ status: ns })
    })
    .then(r => r.json())
    .then(data => { if (data.success) { showAlert(data.message); setTimeout(() => location.reload(), 1000); } });
}

function deleteAkun(id) {
    if (!confirm('Hapus akun teknisi ini?')) return;
    fetch(`${appUrl}/akun-teknisi/${id}`, {
        method: 'DELETE',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
    })
    .then(r => r.json())
    .then(data => { if (data.success) { showAlert(data.message); setTimeout(() => location.reload(), 1000); } });
}
</script>

</x-app-layout>