<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Supplier\StoreSupplierRequest;
use App\Http\Requests\Supplier\UpdateSupplierRequest;
use App\Http\Resources\SupplierResource;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class SupplierController extends ApiController
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $companyId = $this->currentCompanyId($request);
        $search = $request->string('search')->toString();

        $suppliers = Supplier::query()
            ->where('company_id', $companyId)
            ->when($search !== '', function ($query) use ($search) {
                $query->where(function ($inner) use ($search) {
                    $inner->where('name', 'like', "%{$search}%")
                        ->orWhere('contact_person', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%")
                        ->orWhere('phone', 'like', "%{$search}%");
                });
            })
            ->latest('id')
            ->paginate((int) $request->integer('per_page', 15));

        return SupplierResource::collection($suppliers);
    }

    public function store(StoreSupplierRequest $request): SupplierResource
    {
        $supplier = Supplier::create([
            ...$request->validated(),
            'company_id' => $this->currentCompanyId($request),
            'balance' => 0,
        ]);

        return new SupplierResource($supplier);
    }

    public function show(Request $request, Supplier $supplier): SupplierResource
    {
        $this->ensureCompanyScoped($supplier, $this->currentCompanyId($request));
        
        return new SupplierResource($supplier);
    }

    public function update(UpdateSupplierRequest $request, Supplier $supplier): SupplierResource
    {
        $this->ensureCompanyScoped($supplier, $this->currentCompanyId($request));
        $supplier->update($request->validated());

        return new SupplierResource($supplier);
    }

    public function destroy(Request $request, Supplier $supplier): \Illuminate\Http\JsonResponse
    {
        $this->ensureCompanyScoped($supplier, $this->currentCompanyId($request));
        
        $supplier->delete();

        return response()->json(['message' => 'Supplier deleted successfully']);
    }
}
