<?php

namespace App\Http\Controllers;

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

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

    /** Send to one device or all devices (device_id = 'all') */
    public function send(Request $request)
    {
        $request->validate([
            'mode'      => 'required|in:buka,tutup',
            'device_id' => 'required',
        ]);

        $mode    = $request->input('mode');
        $devId   = $request->input('device_id');
        $devices = $devId === 'all'
            ? Device::where('is_active', true)->get()
            : Device::where('id', $devId)->get();

        if ($devices->isEmpty()) {
            return back()->with('error', 'No devices found.');
        }

        $results = [];
        foreach ($devices as $device) {
            [$ok, $msg, $ms] = HdPlayerService::sendMode($device, $mode);

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

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

            $results[] = [
                'device'  => $device->name,
                'ip'      => $device->ip_address,
                'success' => $ok,
                'message' => $msg,
                'ms'      => $ms,
            ];
        }

        $allOk = collect($results)->every(fn($r) => $r['success']);
        $flash = $allOk ? 'success' : 'warning';
        $label = strtoupper($mode);
        $msg   = $allOk
            ? "Sent $label to " . count($results) . " device(s) successfully."
            : "Sent $label — some devices failed. Check results below.";

        return back()->with($flash, $msg)->with('send_results', $results);
    }

    /** Quick send via AJAX — returns JSON */
    public function quickSend(Request $request, Device $device)
    {
        $mode = $request->validate(['mode' => 'required|in:buka,tutup'])['mode'];

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

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

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

        return response()->json(['success' => $ok, 'message' => $msg, 'duration_ms' => $ms]);
    }
}
