@extends('layouts.app')

@section('title', 'Device setup')
@section('heading', 'Device setup')

@section('content')
    @php
        $canManage = auth()->user()->hasPermission('biometric_devices_manage') || auth()->user()->is_superadmin;
        $mode = $device->punch_mode ?: 'both';
        $btnClass = 'inline-flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50';
        $statApplied = (int) ($punchStats['applied'] ?? 0);
        $statPending = (int) ($punchStats['pending'] ?? 0);
        $statError = (int) ($punchStats['error'] ?? 0);
        $statIgnored = (int) ($punchStats['ignored'] ?? 0);
        $statTotal = $statApplied + $statPending + $statError + $statIgnored;
        $monthEnd = \Carbon\Carbon::createFromFormat('Y-m', $syncMonth)->endOfMonth()->toDateString();
    @endphp

    @if(session('success'))
        <div class="mb-4 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">{{ session('success') }}</div>
    @endif

    <div class="mb-6 flex flex-wrap items-start justify-between gap-4">
        <div>
            <nav class="mb-2 flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-slate-400">
                <a href="{{ route('biometric-devices.index') }}" class="hover:text-slate-600">Devices</a>
                <span>/</span>
                <span class="font-mono text-slate-500">{{ $device->terminal_sn }}</span>
            </nav>
            <h1 class="text-2xl font-semibold tracking-tight text-slate-900">Device setup</h1>
            <div class="mt-2 flex flex-wrap items-center gap-2.5">
                @if($device->is_active)
                    <span class="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-700 ring-1 ring-inset ring-emerald-100">
                        <span class="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
                        Active
                    </span>
                @else
                    <span class="inline-flex items-center gap-1.5 rounded-full bg-slate-100 px-2.5 py-1 text-xs font-semibold text-slate-600 ring-1 ring-inset ring-slate-200">
                        Inactive
                    </span>
                @endif
                <span class="text-sm text-slate-500">
                    @if($device->last_seen_at)
                        Synced {{ $device->last_seen_at->diffForHumans() }}
                    @else
                        Not synced yet
                    @endif
                </span>
            </div>
        </div>

        <div class="flex flex-wrap items-center gap-2">
            <a href="{{ route('biometric-devices.index') }}" class="{{ $btnClass }}">
                <i class="bi bi-arrow-left"></i> Back
            </a>
            @if($canManage)
                <a href="{{ route('biometric-devices.edit', $device) }}" class="btn-icon-action btn-icon-action--edit" title="Edit" aria-label="Edit"><i class="bi bi-pencil"></i></a>
                <form action="{{ route('biometric-devices.regenerate', $device) }}" method="POST"
                      onsubmit="return confirm('Regenerate credentials? The device must be updated immediately.');">
                    @csrf
                    <button type="submit" class="{{ $btnClass }}">
                        <i class="bi bi-arrow-repeat"></i> Regenerate credentials
                    </button>
                </form>
                <form action="{{ route('biometric-devices.destroy', $device) }}" method="POST"
                      onsubmit="return confirm('Delete this device?');">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="inline-flex items-center gap-1.5 rounded-xl border border-red-200 bg-white px-3 py-2 text-sm font-medium text-red-600 shadow-sm hover:bg-red-50">
                        <i class="bi bi-trash"></i> Delete
                    </button>
                </form>
            @endif
        </div>
    </div>

    <div class="space-y-5"
         x-data="{
            showPassword: {{ $apiPasswordPlain ? 'true' : 'false' }},
            copied: '',
            async copyText(key, value) {
                try {
                    await navigator.clipboard.writeText(value);
                    this.copied = key;
                    setTimeout(() => { if (this.copied === key) this.copied = ''; }, 1600);
                } catch (e) {}
            }
         }">
        <div class="grid gap-5 lg:grid-cols-5">
            {{-- Device details --}}
            <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6 lg:col-span-2">
                <div class="mb-5">
                    <h2 class="text-base font-semibold text-slate-900">Device</h2>
                    <p class="mt-0.5 text-sm text-slate-500">Registered terminal details.</p>
                </div>

                <dl class="divide-y divide-slate-100 text-sm">
                    <div class="flex items-start justify-between gap-4 py-3 first:pt-0">
                        <dt class="text-slate-500">Alias</dt>
                        <dd class="text-right font-medium text-slate-900">{{ $device->terminal_alias ?: '—' }}</dd>
                    </div>
                    <div class="flex items-start justify-between gap-4 py-3">
                        <dt class="text-slate-500">Serial (SN)</dt>
                        <dd class="text-right font-mono text-xs font-medium text-slate-900 sm:text-sm">{{ $device->terminal_sn }}</dd>
                    </div>
                    <div class="flex items-start justify-between gap-4 py-3">
                        <dt class="text-slate-500">Punch mode</dt>
                        <dd class="text-right font-medium text-slate-900">{{ $device->punchModeLabel() }}</dd>
                    </div>
                    <div class="flex items-start justify-between gap-4 py-3">
                        <dt class="text-slate-500">Location</dt>
                        <dd class="text-right font-medium text-slate-900">{{ $device->location?->name ?: '—' }}</dd>
                    </div>
                    <div class="flex items-start justify-between gap-4 py-3">
                        <dt class="text-slate-500">Last seen</dt>
                        <dd class="text-right font-medium text-slate-900">{{ $device->last_seen_at?->format('Y-m-d H:i:s') ?: '—' }}</dd>
                    </div>
                    <div class="flex items-start justify-between gap-4 py-3 last:pb-0">
                        <dt class="text-slate-500">Status</dt>
                        <dd class="inline-flex items-center gap-1.5 font-medium {{ $device->is_active ? 'text-emerald-700' : 'text-slate-600' }}">
                            <i class="bi {{ $device->is_active ? 'bi-check-circle-fill' : 'bi-dash-circle' }}"></i>
                            {{ $device->is_active ? 'Active' : 'Inactive' }}
                        </dd>
                    </div>
                </dl>

                <div class="mt-5 flex gap-2.5 rounded-xl border border-sky-100 bg-sky-50/80 px-3.5 py-3 text-sm text-slate-600">
                    <i class="bi bi-info-circle mt-0.5 shrink-0 text-sky-600"></i>
                    <p>
                        @if($mode === 'login')
                            Login-only device: every punch is treated as check-in (entry gate).
                        @elseif($mode === 'logout')
                            Logout-only device: every punch is treated as check-out (exit gate).
                        @else
                            Both mode = First IN / Last OUT: every authentication is stored; the first valid punch of the day is IN, the last is OUT, and punches in between are INTERMEDIATE. Rapid repeats within the min gap are DUPLICATE.
                        @endif
                    </p>
                </div>
            </section>

            {{-- Monthly sync --}}
            <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6 lg:col-span-3">
                <div class="mb-5 flex flex-wrap items-start justify-between gap-3">
                    <div class="flex items-start gap-3">
                        <span class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600">
                            <i class="bi bi-arrow-repeat"></i>
                        </span>
                        <div>
                            <h2 class="text-base font-semibold text-slate-900">Monthly punch sync</h2>
                            <p class="mt-0.5 text-sm text-slate-500">
                                @if($mode === 'both')
                                    Recalculate First IN / Last OUT for this device’s punches in the selected month.
                                @else
                                    Reprocess pending / error / ignored punches for this gate device.
                                @endif
                            </p>
                        </div>
                    </div>
                    <a href="{{ route('attendance-punches.index', ['device_id' => $device->id, 'from' => $syncMonth.'-01', 'to' => $monthEnd]) }}"
                       class="text-sm font-medium text-indigo-600 hover:text-indigo-700">
                        View punch log →
                    </a>
                </div>

                <div class="mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5">
                    <div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5">
                        <div class="text-[11px] font-semibold uppercase tracking-wide text-slate-400">Month total</div>
                        <div class="mt-0.5 text-lg font-semibold text-slate-900">{{ $statTotal }}</div>
                    </div>
                    <div class="rounded-xl border border-emerald-100 bg-emerald-50/70 px-3 py-2.5">
                        <div class="text-[11px] font-semibold uppercase tracking-wide text-emerald-600">Applied</div>
                        <div class="mt-0.5 text-lg font-semibold text-emerald-800">{{ $statApplied }}</div>
                    </div>
                    <div class="rounded-xl border border-amber-100 bg-amber-50/70 px-3 py-2.5">
                        <div class="text-[11px] font-semibold uppercase tracking-wide text-amber-600">Pending</div>
                        <div class="mt-0.5 text-lg font-semibold text-amber-800">{{ $statPending }}</div>
                    </div>
                    <div class="rounded-xl border border-red-100 bg-red-50/70 px-3 py-2.5">
                        <div class="text-[11px] font-semibold uppercase tracking-wide text-red-600">Error</div>
                        <div class="mt-0.5 text-lg font-semibold text-red-800">{{ $statError }}</div>
                    </div>
                    <div class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5">
                        <div class="text-[11px] font-semibold uppercase tracking-wide text-slate-400">Ignored</div>
                        <div class="mt-0.5 text-lg font-semibold text-slate-700">{{ $statIgnored }}</div>
                    </div>
                </div>

                @if($canManage)
                    <form method="POST" action="{{ route('biometric-devices.sync-month', $device) }}"
                          class="flex flex-wrap items-end gap-3"
                          onsubmit="return confirm('Reprocess pending/error/ignored punches for {{ $syncMonth }} in chronological order?');">
                        @csrf
                        <div>
                            <label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-slate-500">Month</label>
                            <input type="month" name="month" value="{{ $syncMonth }}"
                                   class="rounded-xl border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-slate-800 shadow-sm"
                                   onchange="window.location='{{ route('biometric-devices.show', $device) }}?month='+this.value">
                        </div>
                        <button type="submit"
                                class="inline-flex items-center gap-1.5 rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500">
                            <i class="bi bi-cloud-download"></i>
                            Sync month
                        </button>
                    </form>
                    <p class="mt-3 text-xs leading-relaxed text-slate-500">
                        Device API logs can show OK while attendance stays empty if Employee ID on the device does not match HRMS
                        <code class="rounded bg-slate-100 px-1">employee_number</code>, or if Check Out arrived before Check In in a batch.
                        Sync month fixes the order issue for stored punches; fix Employee IDs for error rows first.
                    </p>
                @endif

                @if($recentPunches->isNotEmpty())
                    <div class="mt-5 overflow-hidden rounded-xl border border-slate-200">
                        <div class="border-b border-slate-100 bg-slate-50 px-3.5 py-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
                            Recent punches
                        </div>
                        <div class="max-h-64 overflow-auto">
                            <table class="min-w-full text-sm">
                                <thead class="bg-white text-left text-xs uppercase text-slate-400">
                                    <tr>
                                        <th class="px-3.5 py-2 font-medium">When</th>
                                        <th class="px-3.5 py-2 font-medium">Emp</th>
                                        <th class="px-3.5 py-2 font-medium">State</th>
                                        <th class="px-3.5 py-2 font-medium">Status</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-100">
                                    @foreach($recentPunches as $punch)
                                        <tr>
                                            <td class="whitespace-nowrap px-3.5 py-2 text-slate-700">{{ $punch->punch_datetime?->format('Y-m-d H:i') }}</td>
                                            <td class="whitespace-nowrap px-3.5 py-2 font-mono text-slate-800">{{ $punch->emp_code }}</td>
                                            <td class="whitespace-nowrap px-3.5 py-2 text-slate-600">{{ $punch->punch_state ?: '—' }}</td>
                                            <td class="whitespace-nowrap px-3.5 py-2">
                                                <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold
                                                    @if($punch->status === 'applied') bg-emerald-50 text-emerald-700
                                                    @elseif($punch->status === 'error') bg-red-50 text-red-700
                                                    @elseif($punch->status === 'pending') bg-amber-50 text-amber-700
                                                    @else bg-slate-100 text-slate-600 @endif">
                                                    {{ $punch->status }}
                                                </span>
                                                @if($punch->error_message)
                                                    <div class="mt-0.5 max-w-xs truncate text-[11px] text-slate-400" title="{{ $punch->error_message }}">{{ $punch->error_message }}</div>
                                                @endif
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                @endif
            </section>
        </div>

        {{-- API settings --}}
        <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
            <div class="mb-5 flex items-start gap-3">
                <span class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-slate-100 text-slate-600">
                    <i class="bi bi-key"></i>
                </span>
                <div>
                    <h2 class="text-base font-semibold text-slate-900">ZKTeco API settings</h2>
                    <p class="mt-0.5 text-sm text-slate-500">Paste these values into the device configuration form. HTTPS is required in production.</p>
                </div>
            </div>

            <div class="space-y-4">
                <div>
                    <label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-slate-500">API URL</label>
                    <div class="flex items-stretch gap-2">
                        <div class="min-w-0 flex-1 truncate rounded-xl border border-slate-200 bg-slate-50 px-3.5 py-2.5 font-mono text-xs text-slate-800 sm:text-sm">{{ $webhookUrl }}</div>
                        <button type="button" @click="copyText('url', @js($webhookUrl))"
                                class="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-600 hover:bg-slate-50"
                                :title="copied === 'url' ? 'Copied' : 'Copy'">
                            <i class="bi" :class="copied === 'url' ? 'bi-check2 text-emerald-600' : 'bi-clipboard'"></i>
                        </button>
                    </div>
                </div>

                <div>
                    <label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-slate-500">User name</label>
                    <div class="flex items-stretch gap-2">
                        <div class="min-w-0 flex-1 truncate rounded-xl border border-slate-200 bg-slate-50 px-3.5 py-2.5 font-mono text-xs text-slate-800 sm:text-sm">{{ $device->api_username }}</div>
                        <button type="button" @click="copyText('user', @js($device->api_username))"
                                class="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-600 hover:bg-slate-50">
                            <i class="bi" :class="copied === 'user' ? 'bi-check2 text-emerald-600' : 'bi-clipboard'"></i>
                        </button>
                    </div>
                </div>

                <div>
                    <label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-slate-500">Password</label>
                    @if($apiPasswordPlain)
                        <div class="flex items-stretch gap-2">
                            <div class="min-w-0 flex-1 truncate rounded-xl border border-amber-200 bg-amber-50 px-3.5 py-2.5 font-mono text-xs text-amber-950 sm:text-sm"
                                 x-text="showPassword ? @js($apiPasswordPlain) : '••••••••••••••••••••••••'"></div>
                            <button type="button" @click="showPassword = !showPassword"
                                    class="inline-flex items-center rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-600 hover:bg-slate-50">
                                <i class="bi" :class="showPassword ? 'bi-eye-slash' : 'bi-eye'"></i>
                            </button>
                            <button type="button" @click="copyText('pass', @js($apiPasswordPlain))"
                                    class="inline-flex items-center rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-600 hover:bg-slate-50">
                                <i class="bi" :class="copied === 'pass' ? 'bi-check2 text-emerald-600' : 'bi-clipboard'"></i>
                            </button>
                        </div>
                        <p class="mt-1.5 text-xs text-amber-700">Shown once after create/regenerate — copy it into the device now.</p>
                    @else
                        <div class="rounded-xl border border-dashed border-slate-200 bg-slate-50 px-3.5 py-3 text-sm text-slate-500">
                            Hidden. Use <span class="font-medium text-slate-700">Regenerate credentials</span> to issue a new password.
                        </div>
                    @endif
                </div>

                <div>
                    <div class="mb-1.5 flex items-center justify-between gap-2">
                        <label class="text-xs font-semibold uppercase tracking-wide text-slate-500">Data template</label>
                        <button type="button" @click="copyText('tpl', @js($dataTemplate))"
                                class="inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs font-medium text-slate-600 hover:bg-slate-100">
                            <i class="bi" :class="copied === 'tpl' ? 'bi-check2 text-emerald-600' : 'bi-clipboard'"></i>
                            <span x-text="copied === 'tpl' ? 'Copied' : 'Copy template'"></span>
                        </button>
                    </div>
                    <pre class="max-h-44 overflow-auto whitespace-pre-wrap break-all rounded-xl border border-slate-200 bg-slate-50 px-3.5 py-3 font-mono text-[11px] leading-relaxed text-slate-700">{{ $dataTemplate }}</pre>
                </div>
            </div>

            <div class="mt-5 rounded-xl border border-slate-200 bg-slate-50/80 px-3.5 py-3 text-xs leading-relaxed text-slate-600">
                Map device user IDs to the HRMS <span class="font-medium text-slate-800">Employee ID</span> (<code class="rounded bg-white px-1 py-0.5 text-[10px]">employee_number</code>). Interval time ≥ 1 and Enable checked.
            </div>
        </section>
    </div>
@endsection
