<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Models\DeviceSchedule;
use App\Models\SendLog;
use App\Services\HdPlayerService;
use Illuminate\Http\Request;

class ScheduleController extends Controller
{
    public function index()
    {
        $devices = Device::with('schedule')->where('is_active', true)->get();
        return view('schedules.index', compact('devices'));
    }

    public function update(Request $request, Device $device)
    {
        $request->validate([
            'enabled'          => 'boolean',
            'schedule_windows' => 'required|string',
            'repush_hours'     => 'required|integer|min:1|max:24',
        ]);

        // Validate JSON structure
        $windows = json_decode($request->input('schedule_windows'), true);
        if (!is_array($windows)) {
            return back()->withErrors(['schedule_windows' => 'Invalid schedule data.']);
        }

        foreach ($windows as &$w) {
            $w['days']  = array_map('intval', (array) ($w['days'] ?? []));
            $w['start'] = substr($w['start'] ?? '00:00', 0, 5);
            $w['end']   = substr($w['end']   ?? '00:00', 0, 5);
            $w['label'] = substr(trim($w['label'] ?? 'Window'), 0, 50);
        }

        $device->schedule()->updateOrCreate(
            ['device_id' => $device->id],
            [
                'enabled'          => $request->boolean('enabled'),
                'schedule_windows' => json_encode(array_values($windows)),
                'repush_hours'     => (int) $request->input('repush_hours'),
            ]
        );

        return back()->with('success', "Schedule for \"{$device->name}\" saved.");
    }

    /** Run schedule now: evaluate current time and send appropriate mode */
    public function runNow(Device $device)
    {
        $schedule = $device->schedule;
        if (!$schedule || !$schedule->enabled) {
            return back()->with('warning', "Schedule is disabled for \"{$device->name}\".");
        }

        $mode            = $schedule->currentMode();
        [$ok, $msg, $ms] = HdPlayerService::sendMode($device, $mode);

        SendLog::create([
            'device_id'    => $device->id,
            'mode'         => $mode,
            'success'      => $ok,
            'message'      => $msg,
            'duration_ms'  => $ms,
            'triggered_by' => 'schedule',
        ]);

        if ($ok) {
            $device->update(['last_sent_mode' => $mode, 'last_sent_at' => now()]);
            $schedule->update(['last_auto_sent_at' => now()]);
        }

        $label = strtoupper($mode);
        return back()->with(
            $ok ? 'success' : 'danger',
            "Schedule run for \"{$device->name}\": $label — $msg"
        );
    }
}
