<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use App\Services\ActionNotificationService;

class CompanyController extends Controller
{
    /**
     * Show company creation form (only if no company).
     */
    public function create(): View
    {
        if (auth()->user()?->company_id) {
            return redirect()->route('dashboard');
        }

        return view('companies.create');
    }

    /**
     * Store new company and assign to owner.
     */
    public function store(Request $request, ActionNotificationService $notifications): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'mc_number' => 'required|string|max:50',
            'dot_number' => 'required|string|max:50',
            'address' => 'required|string|max:500',
            'phone' => 'required|string|max:20',
        ]);

$company = Company::create(array_merge($validated, [
            'created_by' => auth()->id(),
        ]));

        // Assign to user
        auth()->user()?->update([
            'company_id' => $company->id,
            'role' => 'owner',
        ]);

        $notifications->notifyAction(
            'Company Created',
            auth()->user(),
            [
                'channel' => 'web',
                'company_id' => $company->id,
                'company_name' => $company->name,
            ],
            [$company->email]
        );

        return redirect()->route('dashboard')->with('success', 'Company created successfully!');
    }
}

