<?php

namespace App\Http\Controllers\Api;

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

class SupplierController extends Controller
{
    public function index(Request $request)
    {
        $query = Supplier::with('creator');

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

        // Default sort
        $query->orderBy('name');

        if ($request->has('per_page')) {
            return $query->paginate($request->per_page);
        }

        return $query->get();
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required',
            'phone' => 'required|unique:suppliers,phone',
            'gst_no' => 'nullable|unique:suppliers,gst_no',
            'address' => 'required',
            'is_active' => 'boolean'
        ]);

        $data['is_active'] = $data['is_active'] ?? true;

        $supplier = Supplier::create($data);
        return response()->json($supplier, 201);
    }

    public function update(Request $request, string $id)
    {
        $supplier = Supplier::findOrFail($id);

        $data = $request->validate([
            'name' => 'required',
            'phone' => 'required|unique:suppliers,phone,' . $id,
            'gst_no' => 'nullable|unique:suppliers,gst_no,' . $id,
            'address' => 'required',
            'is_active' => 'boolean'
        ]);

        $supplier->update($data);
        return response()->json($supplier);
    }

    public function destroy(string $id)
    {
        $supplier = Supplier::findOrFail($id);
        $supplier->delete();
        return response()->json(['message' => 'Supplier deleted successfully']);
    }
}
