<?php

namespace Core\App\Controllers;

use Core\App\Models\Settings;
use Core\App\Services\UploadService;
use Core\System\Response;

class SiteIdentityController
{
    private array $keys = [
        'site_logo', 'favicon', 'preloader', 'dark_logo', 'mobile_logo',
        'admin_logo', 'admin_small_logo', 'footer_logo',
    ];

    private function load(): array
    {
        $settingsModel = new Settings();
        $data = [];
        foreach ($this->keys as $key) {
            $data[$key] = (string) $settingsModel->get($key, '');
        }
        return $data;
    }

    public function index()
    {
        $settings = $this->load();
        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/settings/identity.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function save()
    {
        $settingsModel = new Settings();
        $current = $this->load();
        $uploads = new UploadService(ROOT_PATH . '/uploads', '/uploads');

        foreach ($this->keys as $key) {
            if (!empty($_POST['delete_' . $key])) {
                $uploads->deleteByWebPath($current[$key] ?? null);
                $settingsModel->set($key, '');
                continue;
            }

            if (!empty($_FILES[$key]['name'])) {
                $uploads->deleteByWebPath($current[$key] ?? null);
                try {
                    $settingsModel->set($key, $uploads->storeImage($_FILES[$key], 'site'));
                } catch (\Throwable $e) {
                    $_SESSION['settings_error'] = __('settings.invalid_image', 'Invalid image uploaded');
                }
            }
        }

        $_SESSION['settings_saved'] = true;
        Response::redirect('/admin/site-identity');
    }
}
