<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\Staff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;

class CompanyController extends Controller
{
    public function index(): Response
    {
        $user = Auth::user();

        if (! $user->isSuperAdmin()) {
            abort(403);
        }

        $companies = Company::withCount('staff')
            ->orderBy('name')
            ->get();

        return Inertia::render('Companies/Index', [
            'companies' => $companies,
        ]);
    }

    public function store(Request $request)
    {
        $user = Auth::user();
        if (! $user->isSuperAdmin()) {
            abort(403);
        }

        $data = $request->validate([
            'name'            => 'required|string|max:255',
            'registration_no' => 'nullable|string|max:100',
            'industry'        => 'nullable|string|max:100',
            'address'         => 'nullable|string|max:500',
            'city'            => 'nullable|string|max:100',
            'state'           => 'nullable|string|max:100',
            'postcode'        => 'nullable|string|max:20',
            'phone'           => 'nullable|string|max:50',
            'email'           => 'nullable|email|max:255',
            'website'         => 'nullable|string|max:255',
        ]);

        Company::create($data);

        return redirect()->back()->with('success', 'Company created successfully.');
    }
}
