<?php

namespace App\Http\Controllers;

use App\Models\PosCustomer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

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

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

        $posCustomer = PosCustomer::create($validated);

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

    public function show($id)
    {
        $posCustomer = PosCustomer::findOrFail($id);

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

    public function update(Request $request, $id)
    {
        $posCustomer = PosCustomer::findOrFail($id);

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

        $posCustomer->update($validated);

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

    public function destroy($id)
    {
        $posCustomer = PosCustomer::findOrFail($id);

        $posCustomer->delete();

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