<?php

namespace App\Http\Controllers;

use App\Models\PosChannel;
use Illuminate\Http\Request;

class PosChannelController extends Controller
{
    public function index()
    {
        $userId = request()->query('user_id');
        if (!$userId) {
            return response()->json(['message' => 'User ID required'], 400);
        }
        return response()->json(PosChannel::where('user_id', $userId)->get());
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'desc' => 'nullable|string',
            'url' => 'nullable|string',
            'user_id' => 'required|integer',
        ]);

        $posChannel = PosChannel::create($validated);

        return response()->json($posChannel, 201);
    }

    public function show($id)
    {
        $posChannel = PosChannel::findOrFail($id);

        return response()->json($posChannel->load('posSales'));
    }

    public function update(Request $request, $id)
    {
        $posChannel = PosChannel::findOrFail($id);

        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'desc' => 'nullable|string',
            'url' => 'nullable|string',
        ]);

        $posChannel->update($validated);

        return response()->json($posChannel);
    }

    public function destroy($id)
    {
        $posChannel = PosChannel::findOrFail($id);

        $posChannel->delete();

        return response()->json(null, 204);
    }
}
