<?php

namespace App\Http\Controllers\Api;

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

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

        // Search
        if ($request->has('search') && $request->input('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('company', 'like', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->filled('is_active') || $request->input('is_active') === '0') {
            $query->where('is_active', (bool) $request->input('is_active'));
        }

        $suppliers = $query->latest()->get();

        return response()->json(['data' => $suppliers]);
    }

    public function store(Request $request)
    {
        $this->authorize('create-suppliers');

        $orgId = app('current_organization_id');

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => ['nullable', 'email', Rule::unique('suppliers', 'email')->where('organization_id', $orgId)],
            'phone' => 'required|string',
            'address' => 'nullable|string',
            'company' => 'nullable|string',
            'tax_number' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $supplier = Supplier::create($validated);

        return response()->json(['data' => $supplier], 201);
    }

    public function show(Supplier $supplier)
    {
        return response()->json(['data' => $supplier->load('purchases')]);
    }

    public function update(Request $request, Supplier $supplier)
    {
        $this->authorize('edit-suppliers');

        $orgId = app('current_organization_id');

        $validated = $request->validate([
            'name' => 'string|max:255',
            'email' => ['nullable', 'email', Rule::unique('suppliers', 'email')->where('organization_id', $orgId)->ignore($supplier->id)],
            'phone' => 'string',
            'address' => 'nullable|string',
            'company' => 'nullable|string',
            'tax_number' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $supplier->update($validated);

        return response()->json(['data' => $supplier]);
    }

    public function destroy(Supplier $supplier)
    {
        $this->authorize('delete-suppliers');

        if ($supplier->purchases()->count() > 0) {
            return response()->json([
                'message' => 'Cannot delete supplier with existing purchases'
            ], 422);
        }

        $supplier->delete();

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