<?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)
    {
        $data = $request->validate([
            'enabled'               => 'boolean',
            'weekday_green_start_1' => 'required|date_format:H:i',
            'weekday_green_end_1'   => 'required|date_format:H:i',
            'weekday_green_start_2' => 'required|date_format:H:i',
            'weekday_green_end_2'   => 'required|date_format:H:i',
            'weekend_green_start'   => 'required|date_format:H:i',
            'weekend_green_end'     => 'required|date_format:H:i',
            'repush_hours'          => 'required|integer|min:1|max:24',
        ]);
        $data['enabled'] = $request->boolean('enabled');

        $device->schedule()->updateOrCreate(
            ['device_id' => $device->id],
            $data
        );

        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"
        );
    }
}
