<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CompanyRequest;
use App\Models\Company;
use App\Models\Country;
use App\Models\Currency;
use App\Services\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class CompanyController extends Controller
{
    public function index(): View
    {
        $companies = Company::with(['country', 'currency'])->latest()->get();

        return view('admin.companies.index', compact('companies'));
    }

    public function create(): View
    {
        return view('admin.companies.create', [
            'company' => new Company(['distance_unit' => 'mi', 'timezone' => 'UTC', 'is_active' => true]),
            'countries' => Country::orderBy('name')->get(),
            'currencies' => Currency::where('is_active', true)->orderBy('name')->get(),
        ]);
    }

    public function store(CompanyRequest $request, ActivityLogger $activity): RedirectResponse
    {
        $data = $request->validated();
        $data['is_active'] = $request->boolean('is_active');
        $data['feature_flags'] = $this->normalizeFeatureFlags($request);

        $company = Company::create($data);
        $activity->created($company);

        return redirect()->route('admin.companies.index')->with('success', 'Company created.');
    }

    public function edit(Company $company): View
    {
        return view('admin.companies.edit', [
            'company' => $company,
            'countries' => Country::orderBy('name')->get(),
            'currencies' => Currency::where('is_active', true)->orderBy('name')->get(),
        ]);
    }

    public function update(CompanyRequest $request, Company $company, ActivityLogger $activity): RedirectResponse
    {
        $data = $request->validated();
        $data['is_active'] = $request->boolean('is_active');
        $data['feature_flags'] = $this->normalizeFeatureFlags($request);

        $company->update($data);
        $activity->updated($company, $company->getChanges());

        return redirect()->route('admin.companies.index')->with('success', 'Company updated.');
    }

    public function destroy(Company $company, ActivityLogger $activity): RedirectResponse
    {
        $company->delete();
        $activity->deleted($company);

        return redirect()->route('admin.companies.index')->with('success', 'Company deleted.');
    }

    public static function suggestSlug(string $name): string
    {
        return Str::slug($name);
    }

    /**
     * HTML checkboxes only appear in the request body when checked, so an
     * unchecked "off" flag is indistinguishable from one the form never
     * showed — this fills in every known feature key explicitly rather
     * than trusting the request's own array shape.
     */
    private function normalizeFeatureFlags(CompanyRequest $request): array
    {
        $submitted = $request->input('feature_flags', []);

        return collect(Company::FEATURES)
            ->keys()
            ->mapWithKeys(fn ($key) => [$key => (bool) ($submitted[$key] ?? false)])
            ->all();
    }
}
