<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Services\CompanyProfileService;
use Throwable;

final class CompanyProfileController
{
    public function handle(): void
    {
        Auth::requireLogin();
        require_permission('admin.company.edit');
        $service = new CompanyProfileService(DB::pdo());

        if (!$service->tableReady()) {
            Response::flash('danger', 'يجب تشغيل ملف التحديث: sql/migrate_v1_28_company_profile.sql');
            Response::view('pages/admin/company_profile', ['profile' => []]);
            return;
        }

        $profile = $service->profile();
        if (Request::isPost()) {
            try {
                Csrf::verify();
                $service->save(Request::all(), $_FILES, $profile);
                Response::flash('success', 'تم حفظ بيانات الشركة بنجاح.');
                Response::redirect('/admin/company-profile');
                return;
            } catch (Throwable $e) {
                Response::flash('danger', $e->getMessage());
                $profile = array_merge($profile, Request::all());
            }
        }

        Response::view('pages/admin/company_profile', ['profile' => $service->profile() ?: $profile]);
    }
}
