<?php

namespace App\Http\Controllers\WebAdmin;

use App\Enum\MediaTypeEnum;
use App\Http\Controllers\Controller;
use App\Repositories\MediaRepository;
use App\Repositories\SettingRepository;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

/**
 * The safe, per-company replacement for the old global Settings screen —
 * touches only this company's own Company row and Setting row, never the
 * shared .env. Company name lives on Company; the logo lives on Setting,
 * reusing the same Media upload flow SettingRepository already used.
 */
class CompanyProfileController extends Controller
{
    public function index(): View
    {
        $company = currentCompany();
        abort_unless($company, 404);

        return view('setting.company-profile', [
            'company' => $company,
            'setting' => SettingRepository::query()->first(),
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $company = currentCompany();
        abort_unless($company, 404);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'logo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
        ]);

        $company->name = $validated['name'];
        $company->save();

        $setting = SettingRepository::query()->first();

        if ($setting) {
            $logo = $request->hasFile('logo') ? MediaRepository::updateOrCreateByRequest(
                $request->file('logo'),
                'setting/logo',
                $setting->logo,
                MediaTypeEnum::IMAGE
            ) : $setting->logo;

            $setting->update(['logo_id' => $logo?->id]);
        }

        return to_route('company-profile.index')->with('success', __('Company profile updated.'));
    }
}
