<?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\CommunicationService;
use Throwable;

final class CommunicationSettingsController
{
    public function handle(): void
    {
        Auth::requireLogin();
        require_permission('admin.comms.edit');
        $service = new CommunicationService(DB::pdo());
        $settings = $service->settings();
        $errors = [];

        if (Request::isPost()) {
            try {
                Csrf::verify();
                $service->save(Request::all());
                Response::flash('success', 'تم حفظ إعدادات البريد والواتساب.');
                Response::redirect('/admin/communication-settings');
                return;
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
                $settings = array_merge($settings, Request::all());
            }
        }

        Response::view('pages/admin/communication_settings', [
            'settings' => $settings,
            'errors' => $errors,
            'page_title' => 'إعدادات البريد والواتساب',
            'breadcrumbs' => [
                ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                ['label' => 'الإدارة'],
                ['label' => 'إعدادات البريد والواتساب'],
            ],
        ]);
    }
}
