<?php

declare(strict_types=1);

namespace App\Modules\Parties\Presentation\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Parties\Application\Services\PartyViewService;

final class PartyViewController
{
    public function __construct(private ?PartyViewService $service = null)
    {
        $this->service ??= new PartyViewService(db());
    }

    public function show(): void
    {
        Auth::requireLogin();
        $this->service->ensureSchema();
        require_view_parties();

        $id = (int) Request::get('id', 0);
        if ($id <= 0) {
            Response::flash('danger', 'طرف غير صالح');
            Response::redirect('/parties');
        }

        $data = $this->service->load($id);
        if (!$data) {
            Response::flash('danger', 'الطرف غير موجود');
            Response::redirect('/parties');
        }

        Response::view('pages/parties/view', $data + [
            'page_title' => 'بيانات طرف',
            'breadcrumbs' => [
                ['label'=>'لوحة التحكم','url'=>'/admin/dashboard'],
                ['label'=>'الأطراف','url'=>$data['back_url']],
                ['label'=>'عرض'],
            ],
        ]);
    }
}
