<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $shopId = $user->type_id === 1 ? $request->query('shop_id') : $user->shop_id;

        $query = Customer::query();
        if ($shopId) {
            $query->where('shop_id', $shopId);
        }

        if ($search = $request->query('q')) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        return $query->orderBy('name')->limit(20)->get();
    }

    public function store(Request $request)
    {
        $user = $request->user();
        $shopId = $user->type_id === 1 ? $request->input('shop_id') : $user->shop_id;

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'address' => 'nullable|string',
        ]);

        $validated['shop_id'] = $shopId;

        return response()->json(Customer::create($validated), 201);
    }
}
