@extends('layouts.app')
@section('title', 'Schedule')

@push('scripts')
<script>
const DAY_LABELS = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

// Per-device window state keyed by device id
const windowState = {};

function initDevice(deviceId, windows) {
    windowState[deviceId] = JSON.parse(JSON.stringify(windows));
    renderWindows(deviceId);
}

function renderWindows(deviceId) {
    const container = document.getElementById('windows-' + deviceId);
    const windows   = windowState[deviceId];
    container.innerHTML = '';

    windows.forEach((w, idx) => {
        const html = `
        <div class="window-row mb-3 p-3" style="background:#0d1117;border:1px solid #1e2433;border-radius:8px">
            <div class="d-flex align-items-center justify-content-between mb-2">
                <input type="text" class="form-control form-control-sm me-2" style="max-width:160px"
                       placeholder="Label" value="${escHtml(w.label)}"
                       onchange="updateWindow(${deviceId},${idx},'label',this.value)">
                <button type="button" class="btn btn-outline-danger btn-sm py-0 px-2"
                        onclick="removeWindow(${deviceId},${idx})" title="Remove window">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
            <div class="mb-2">
                <div class="text-secondary mb-1" style="font-size:.75rem">Days</div>
                <div class="d-flex flex-wrap gap-1">
                ${DAY_LABELS.map((d,i) => `
                    <label class="btn btn-sm py-0 px-2 ${w.days.includes(i) ? 'btn-primary' : 'btn-outline-secondary'}"
                           style="font-size:.75rem;cursor:pointer">
                        <input type="checkbox" class="d-none" ${w.days.includes(i) ? 'checked' : ''}
                               onchange="toggleDay(${deviceId},${idx},${i},this.checked)">
                        ${d}
                    </label>`).join('')}
                </div>
            </div>
            <div class="d-flex gap-2 align-items-center">
                <div>
                    <div class="text-secondary mb-1" style="font-size:.75rem">BUKA from</div>
                    <input type="time" class="form-control form-control-sm" value="${w.start}"
                           onchange="updateWindow(${deviceId},${idx},'start',this.value)">
                </div>
                <div class="mt-3 text-secondary">to</div>
                <div>
                    <div class="text-secondary mb-1" style="font-size:.75rem">until</div>
                    <input type="time" class="form-control form-control-sm" value="${w.end}"
                           onchange="updateWindow(${deviceId},${idx},'end',this.value)">
                </div>
            </div>
        </div>`;
        container.insertAdjacentHTML('beforeend', html);
    });
}

function escHtml(str) {
    return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

function updateWindow(deviceId, idx, key, val) {
    windowState[deviceId][idx][key] = val;
}

function toggleDay(deviceId, idx, day, checked) {
    const days = windowState[deviceId][idx].days;
    if (checked && !days.includes(day)) days.push(day);
    if (!checked) windowState[deviceId][idx].days = days.filter(d => d !== day);
    windowState[deviceId][idx].days.sort((a,b) => a-b);
    renderWindows(deviceId); // re-render to sync checkboxes
}

function addWindow(deviceId) {
    windowState[deviceId].push({ label: 'New Window', days: [1,2,3,4,5], start: '08:00', end: '12:00' });
    renderWindows(deviceId);
}

function removeWindow(deviceId, idx) {
    windowState[deviceId].splice(idx, 1);
    renderWindows(deviceId);
}

function saveSchedule(deviceId, formEl) {
    // Inject hidden JSON input before submit
    let hidden = formEl.querySelector('input[name=schedule_windows]');
    if (!hidden) {
        hidden = document.createElement('input');
        hidden.type = 'hidden';
        hidden.name = 'schedule_windows';
        formEl.appendChild(hidden);
    }
    hidden.value = JSON.stringify(windowState[deviceId]);
}
</script>
@endpush

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <h5 class="mb-0 fw-bold">Automatic Schedule</h5>
    <div class="text-secondary" style="font-size:.8rem">
        <i class="bi bi-clock me-1"></i>Server time: {{ now()->format('H:i') }} MYT (UTC+8)
    </div>
</div>

<div class="row g-3">
@foreach($devices as $device)
@php $sch = $device->schedule; @endphp
<div class="col-xl-6">
<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between">
        <div>
            <span class="fw-semibold">{{ $device->name }}</span>
            <code class="ms-2" style="font-size:.75rem;color:#7dd3fc">{{ $device->ip_address }}</code>
        </div>
        <div class="d-flex align-items-center gap-2">
            @if($sch && $sch->enabled)
                <span class="badge bg-success">Enabled</span>
                <span class="badge badge-{{ $sch->currentMode() }}">Now: {{ strtoupper($sch->currentMode()) }}</span>
            @else
                <span class="badge bg-secondary">Disabled</span>
            @endif
        </div>
    </div>
    <div class="card-body">
        <form method="POST" action="{{ route('lis.schedule.update', $device) }}"
              onsubmit="saveSchedule({{ $device->id }}, this)">
            @csrf @method('PUT')

            {{-- Enable toggle --}}
            <div class="form-check form-switch mb-3">
                <input class="form-check-input" type="checkbox" name="enabled"
                       id="en{{ $device->id }}" {{ $sch?->enabled ? 'checked' : '' }}>
                <label class="form-check-label text-secondary" for="en{{ $device->id }}">
                    Enable automatic schedule
                </label>
            </div>

            {{-- Windows --}}
            <div class="d-flex align-items-center justify-content-between mb-2">
                <div class="text-secondary" style="font-size:.8rem;text-transform:uppercase;letter-spacing:.6px">
                    <i class="bi bi-calendar-week me-1"></i>BUKA Windows
                </div>
                <button type="button" class="btn btn-outline-primary btn-sm py-0 px-2"
                        onclick="addWindow({{ $device->id }})">
                    <i class="bi bi-plus me-1"></i>Add Window
                </button>
            </div>

            <div id="windows-{{ $device->id }}">{{-- rendered by JS --}}</div>

            {{-- Re-push interval --}}
            <div class="mb-3">
                <label class="form-label text-secondary" style="font-size:.8rem">Re-push interval (hours)</label>
                <input type="number" name="repush_hours" class="form-control form-control-sm"
                       style="max-width:100px"
                       value="{{ $sch?->repush_hours ?? 6 }}" min="1" max="24">
                <div class="text-secondary mt-1" style="font-size:.75rem">
                    Outside BUKA windows → TUTUP.
                    Last auto: {{ $sch?->last_auto_sent_at?->diffForHumans() ?? 'Never' }}
                </div>
            </div>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary btn-sm px-3">
                    <i class="bi bi-floppy me-1"></i>Save
                </button>
            </div>
        </form>

        <form id="run-form-{{ $device->id }}" method="POST"
              action="{{ route('lis.schedule.run', $device) }}" class="d-none">@csrf</form>
        <button type="button" class="btn btn-outline-secondary btn-sm mt-2"
                onclick="if(confirm('Run schedule now for {{ addslashes($device->name) }}?')) document.getElementById('run-form-{{ $device->id }}').submit()">
            <i class="bi bi-play-fill me-1"></i>Run Now
        </button>
    </div>
</div>
</div>

<script>
initDevice({{ $device->id }}, {!! json_encode($sch ? $sch->getWindows() : [
    ['label'=>'Morning Peak','days'=>[1,2,3,4,5],'start'=>'06:00','end'=>'10:00'],
    ['label'=>'Evening Peak','days'=>[1,2,3,4,5],'start'=>'16:00','end'=>'20:00'],
    ['label'=>'Weekend','days'=>[0,6],'start'=>'10:00','end'=>'22:00'],
]) !!});
</script>

@endforeach

@if($devices->isEmpty())
<div class="col-12">
    <div class="card">
        <div class="card-body text-center py-5 text-secondary">
            No active devices. <a href="{{ route('lis.devices.create') }}">Add a device first →</a>
        </div>
    </div>
</div>
@endif
</div>
@endsection
