<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Supplier;
use App\Rules\IndianMobile;
use App\Services\LocationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SupplierController extends Controller
{
    public function __construct(protected LocationService $locationService)
    {
        $this->middleware('auth');
    }

    public function index(): View
    {
        $suppliers = Supplier::query()->latest()->paginate(50);

        return view('admin.suppliers.index', compact('suppliers'));
    }

    public function store(Request $request): RedirectResponse
    {
        $company = Company::primary() ?? $this->locationService->ensureCompanyAndDefaults();
        $request->merge(['phone' => $this->normalizeIndianMobileTo10Digits($request->input('phone'))]);
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50',
            'contact_name' => 'nullable|string|max:255',
            'phone' => ['required', 'string', new IndianMobile()],
            'email' => 'nullable|email',
            'gstin' => 'nullable|string|max:30',
            'address' => 'nullable|string',
        ]);
        $data['company_id'] = $company->id;
        $data['is_active'] = true;
        Supplier::create($data);

        return back()->with('success', 'Supplier created.');
    }

    private function normalizeIndianMobileTo10Digits(?string $mobile): string
    {
        $digits = preg_replace('/\D/', '', (string) $mobile);

        if (strlen($digits) === 12 && str_starts_with($digits, '91')) {
            $digits = substr($digits, 2);
        }

        if (strlen($digits) === 11 && str_starts_with($digits, '0')) {
            $digits = substr($digits, 1);
        }

        if (strlen($digits) > 10) {
            $digits = substr($digits, -10);
        }

        return $digits;
    }
}
