<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Supplier;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SupplierController extends Controller
{
    /**
     * GET /api/suppliers
     */
    public function index(Request $request)
    {
        $suppliers = Supplier::with('user:id,name,email')
            ->when($request->search, fn($q) => $q->search($request->search))
            ->when($request->has('is_active'), fn($q) => $q->where('is_active', $request->boolean('is_active')))
            ->latest()
            ->paginate(20);

        return response()->json($suppliers->through(fn($s) => $this->format($s)));
    }

    /**
     * POST /api/suppliers
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'code'           => ['required', 'string', 'max:20', 'unique:suppliers'],
            'name'           => ['required', 'string', 'max:255'],
            'contact_person' => ['nullable', 'string', 'max:255'],
            'email'          => ['nullable', 'email', 'max:255'],
            'phone'          => ['nullable', 'string', 'max:30'],
            'address'        => ['nullable', 'string'],
            'create_account' => ['nullable', 'boolean'],
            'account_password' => ['required_if:create_account,true', 'string', 'min:6'],
        ]);

        // Validate email uniqueness in users table when creating account
        if (!empty($data['create_account']) && !empty($data['email'])) {
            $request->validate([
                'email' => ['unique:users,email'],
            ], [
                'email.unique' => 'Email ini sudah digunakan oleh akun lain.',
            ]);
        }

        return DB::transaction(function () use ($data) {
            $userId = null;

            // Create user account for supplier portal if requested
            if (!empty($data['create_account']) && !empty($data['email'])) {
                $user = User::create([
                    'name'      => $data['name'],
                    'email'     => $data['email'],
                    'password'  => $data['account_password'],
                    'is_active' => true,
                ]);
                $user->syncRoles(['supplier']);
                $userId = $user->id;
            }

            $supplier = Supplier::create([
                'code'           => $data['code'],
                'name'           => $data['name'],
                'contact_person' => $data['contact_person'] ?? null,
                'email'          => $data['email'] ?? null,
                'phone'          => $data['phone'] ?? null,
                'address'        => $data['address'] ?? null,
                'user_id'        => $userId,
            ]);

            return response()->json($this->format($supplier->load('user')), 201);
        });
    }

    /**
     * GET /api/suppliers/{supplier}
     */
    public function show(Supplier $supplier)
    {
        $supplier->load('user:id,name,email');

        return response()->json($this->format($supplier));
    }

    /**
     * PUT /api/suppliers/{supplier}
     */
    public function update(Request $request, Supplier $supplier)
    {
        $data = $request->validate([
            'name'           => ['sometimes', 'string', 'max:255'],
            'contact_person' => ['nullable', 'string', 'max:255'],
            'email'          => ['nullable', 'email', 'max:255'],
            'phone'          => ['nullable', 'string', 'max:30'],
            'address'        => ['nullable', 'string'],
            'is_active'      => ['sometimes', 'boolean'],
        ]);

        $supplier->update($data);

        // Sync active status to linked user account
        if (isset($data['is_active']) && $supplier->user_id) {
            User::where('id', $supplier->user_id)->update(['is_active' => $data['is_active']]);
        }

        return response()->json($this->format($supplier->load('user')));
    }

    /**
     * DELETE /api/suppliers/{supplier}
     */
    public function destroy(Supplier $supplier)
    {
        if ($supplier->purchases()->whereNotIn('status', ['received', 'cancelled'])->exists()) {
            return response()->json(['message' => 'Supplier masih memiliki PO aktif.'], 422);
        }

        $supplier->update(['is_active' => false]);
        $supplier->delete();

        // Deactivate linked user
        if ($supplier->user_id) {
            User::where('id', $supplier->user_id)->update(['is_active' => false]);
        }

        return response()->json(['message' => 'Supplier berhasil dihapus.']);
    }

    /**
     * GET /api/suppliers/search — lightweight search for dropdowns
     */
    public function search(Request $request)
    {
        $suppliers = Supplier::active()
            ->search($request->q)
            ->select('id', 'code', 'name', 'contact_person', 'phone')
            ->limit(20)
            ->get();

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

    private function format(Supplier $supplier): array
    {
        return [
            'id'             => $supplier->id,
            'code'           => $supplier->code,
            'name'           => $supplier->name,
            'contact_person' => $supplier->contact_person,
            'email'          => $supplier->email,
            'phone'          => $supplier->phone,
            'address'        => $supplier->address,
            'is_active'      => $supplier->is_active,
            'has_account'    => (bool) $supplier->user_id,
            'user_email'     => $supplier->user?->email,
            'total_orders'   => $supplier->purchases()->count(),
            'created_at'     => $supplier->created_at->toISOString(),
        ];
    }
}
