<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Machine\Machine;
use App\Models\Machine\RemoteCommand;
use Illuminate\Support\Facades\Auth;

class RemoteController extends Controller
{
    /**
     * 遠端管理指揮中心
     */
    public function index(Request $request)
    {
        $machines = Machine::withCount(['slots'])->orderBy('name')->get();
        $selectedMachine = null;

        if ($request->has('machine_id')) {
            $selectedMachine = Machine::with(['slots.product', 'commands' => function($query) {
                $query->latest()->limit(10);
            }])->find($request->machine_id);
        }

        return view('admin.remote.index', [
            'machines' => $machines,
            'selectedMachine' => $selectedMachine,
        ]);
    }

    /**
     * 儲存遠端指令
     */
    public function storeCommand(Request $request)
    {
        $validated = $request->validate([
            'machine_id' => 'required|exists:machines,id',
            'command_type' => 'required|string|in:reboot,reboot_card,checkout,lock,unlock,change,dispense',
            'amount' => 'nullable|integer|min:0',
            'slot_no' => 'nullable|string',
            'note' => 'nullable|string|max:255',
        ]);

        $payload = [];
        if ($validated['command_type'] === 'change') {
            $payload['amount'] = $validated['amount'];
        } elseif ($validated['command_type'] === 'dispense') {
            $payload['slot_no'] = $validated['slot_no'];
        }

        RemoteCommand::create([
            'machine_id' => $validated['machine_id'],
            'command_type' => $validated['command_type'],
            'payload' => $payload,
            'status' => 'pending',
            'note' => $validated['note'] ?? null,
        ]);

        return redirect()->back()->with('success', __('Command has been queued successfully.'));
    }

    /**
     * 機台庫存管理 (現有功能保留)
     */
    public function stock(Request $request)
    {
        $machines = Machine::withCount([
            'slots as slots_count',
            'slots as low_stock_count' => function ($query) {
                $query->where('stock', '<=', 5); 
            }
        ])->orderBy('name')->get();
        
        $selectedMachine = null;
        if ($request->has('machine_id')) {
            $selectedMachine = Machine::with('slots.product')->find($request->machine_id);
        }

        return view('admin.remote.stock', [
            'machines' => $machines,
            'selectedMachine' => $selectedMachine,
        ]);
    }
}
