<?php

namespace App\Http\Controllers\Api;

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

class FreightCompanyApiController extends Controller
{
    public function register(Request $request)
    {
        $payload = $request->validate([
            'company_name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'entity_type' => 'required|in:individual,legal',
            'vehicle_categories' => 'nullable|array',
            'province' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:255',
            'postal_code' => 'nullable|string|max:10',
            'landline' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'company_description' => 'nullable|string',
        ]);

        $company = FreightCompany::create($payload);

        return response()->json([
            'success' => true,
            'message' => 'Freight company registered and pending approval',
            'data' => $company,
        ], 201);
    }

    public function status(int $id)
    {
        $company = FreightCompany::findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => [
                'id' => $company->id,
                'status' => $company->status,
                'rejection_reason' => $company->rejection_reason,
            ],
        ]);
    }

    public function index(Request $request)
    {
        $query = FreightCompany::query();

        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }

        return response()->json([
            'success' => true,
            'data' => $query->latest()->paginate((int) $request->input('per_page', 15)),
        ]);
    }
}
