<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Response;
use App\Core\Session;
use App\Services\SettingsService;
use InvalidArgumentException;

final class SettingsController extends Controller
{
    public function __construct(private ?SettingsService $service = null)
    {
        $this->service ??= new SettingsService();
    }

    public function index(): Response
    {
        $settings = $this->service->get();
        $logoPreview = '';
        $logoFile = (string) ($settings['business.logo']['value'] ?? '');
        if ($logoFile !== '') {
            $safe = basename($logoFile);
            $path = dirname(__DIR__, 2) . '/storage/branding/' . $safe;
            if (is_file($path)) {
                $mime = str_ends_with(strtolower($safe), '.png') ? 'image/png' : 'image/jpeg';
                $logoPreview = 'data:' . $mime . ';base64,' . base64_encode((string) file_get_contents($path));
            }
        }
        return $this->view('settings/index', [
            'pageTitle' => 'Business & System Settings',
            'pageDescription' => 'Manage business identity, regional preferences, tax and document numbering.',
            'settings' => $settings,
            'logoPreview' => $logoPreview,
            'csrf' => Csrf::token(),
            'message' => Session::pull('settings_message'),
            'error' => Session::pull('settings_error'),
            'form' => Session::pull('settings_form'),
        ]);
    }

    public function update(): Response
    {
        Csrf::verify((string) ($_POST['_csrf'] ?? ''));
        $form = $_POST;
        try {
            $this->service->save($form, Auth::id() ?? 0);
            Session::put('settings_message', 'Settings saved successfully.');
        } catch (InvalidArgumentException $e) {
            Session::put('settings_error', $e->getMessage());
            Session::put('settings_form', $form);
        }
        return Response::redirect('/crm/public/settings');
    }

    public function uploadLogo(): Response
    {
        Csrf::verify((string) ($_POST['_csrf'] ?? ''));
        try {
            $this->service->saveLogo($_FILES['logo'] ?? [], Auth::id() ?? 0);
            Session::put('settings_message', 'Logo uploaded successfully.');
        } catch (InvalidArgumentException $e) {
            Session::put('settings_error', $e->getMessage());
        }
        return Response::redirect('/crm/public/settings');
    }
}
