<?php

namespace App\Http\Controllers\Api\V1\App;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Machine\Machine;
use App\Jobs\Machine\ProcessHeartbeat;
use App\Jobs\Machine\ProcessTimerStatus;
use App\Jobs\Machine\ProcessCoinInventory;
use Illuminate\Support\Facades\Validator;

class MachineController extends Controller
{
    /**
     * B010: Machine Heartbeat & Status Update (Asynchronous)
     */
    public function heartbeat(Request $request)
    {
        $machine = $request->get('machine');
        $data = $request->all();

        // 異步處理狀態更新
        ProcessHeartbeat::dispatch($machine->serial_no, $data);

        // 取出待處理指令
        $command = \App\Models\Machine\RemoteCommand::where('machine_id', $machine->id)
            ->pending()
            ->first();

        $status = '49'; // 預設 49 (OK / No Command)
        $message = 'OK';

        if ($command) {
            switch ($command->command_type) {
                case 'reboot':
                    $status = '51';
                    $message = 'reboot';
                    break;
                case 'reboot_card':
                    $status = '60';
                    $message = 'reboot card machine';
                    break;
                case 'checkout':
                    $status = '61';
                    $message = 'checkout';
                    break;
                case 'lock':
                    $status = '71';
                    $message = 'lock';
                    break;
                case 'unlock':
                    $status = '70';
                    $message = 'unlock';
                    break;
                case 'change':
                    $status = '82';
                    $message = $command->payload['amount'] ?? '0';
                    break;
                case 'dispense':
                    $status = '85';
                    $message = $command->payload['slot_no'] ?? '';
                    break;
                case 'reload_stock':
                    $status = '49';
                    $message = 'reload B017';
                    break;
            }
            // 標記為已發送 (sent)
            $command->update(['status' => 'sent', 'executed_at' => now()]);
        }

        return response()->json([
            'success' => true,
            'code' => 200,
            'message' => $message,
            'status' => $status
        ], 202); // 202 Accepted
    }

    /**
     * B018: Record Machine Restock/Setup Report (Asynchronous)
     */
    public function recordRestock(Request $request)
    {
        $machine = $request->get('machine');
        $data = $request->all();
        $data['serial_no'] = $machine->serial_no;

        \App\Jobs\Machine\ProcessRestockReport::dispatch($data);

        return response()->json([
            'success' => true,
            'code' => 200,
            'message' => 'Restock report accepted',
            'status' => '49'
        ], 202);
    }

    /**
     * B017: Get Slot Info & Stock (Synchronous)
     */
    public function getSlots(Request $request)
    {
        $machine = $request->get('machine');
        $slots = $machine->slots()->with('product')->get();

        return response()->json([
            'success' => true,
            'code' => 200,
            'data' => $slots->map(function ($slot) {
                return [
                    'slot_no' => $slot->slot_no,
                    'product_id' => $slot->product_id,
                    'stock' => $slot->stock,
                    'capacity' => $slot->capacity,
                    'price' => $slot->price,
                    'status' => $slot->status,
                    'expiry_date' => $slot->expiry_date,
                    'batch_no' => $slot->batch_no,
                ];
            })
        ]);
    }

    /**
     * B710: Sync Timer status (Asynchronous)
     */
    public function syncTimer(Request $request)
    {
        $machine = $request->get('machine');
        $data = $request->all();

        ProcessTimerStatus::dispatch($machine->serial_no, $data);

        return response()->json(['success' => true], 202);
    }

    /**
     * B220: Sync Coin Inventory (Asynchronous)
     */
    public function syncCoinInventory(Request $request)
    {
        $machine = $request->get('machine');
        $data = $request->all();

        ProcessCoinInventory::dispatch($machine->serial_no, $data);

        return response()->json(['success' => true], 202);
    }

    /**
     * B650: Verify Member Code/Barcode (Synchronous)
     */
    public function verifyMember(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'code' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => 'Invalid code'], 400);
        }

        $code = $request->input('code');

        // 搜尋會員 (barcode 或特定驗證碼)
        $member = \App\Models\Member\Member::where('barcode', $code)
            ->orWhere('id', $code) // 暫時支援 ID
            ->first();

        if (!$member) {
            return response()->json([
                'success' => false,
                'code' => 404,
                'message' => 'Member not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'code' => 200,
            'data' => [
                'member_id' => $member->id,
                'name' => $member->name,
                'points' => $member->points,
                'wallet_balance' => $member->wallet_balance ?? 0,
            ]
        ]);
    }
}
