<?php

namespace Core\App\Controllers;

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

class SettingsIdentityController
{
    private array $imageKeys = [
        'site_logo', 'favicon', 'preloader', 'dark_logo', 'mobile_logo',
        'admin_logo', 'admin_small_logo', 'footer_logo', 'seo_default_image',
    ];

    public function index()
    {
        $settingsModel = new Settings();
        $settings = $settingsModel->getAll();
        $identityImages = [];
        foreach ($this->imageKeys as $key) {
            if (!empty($settings[$key])) {
                $identityImages[$key] = $settings[$key];
            }
        }

        extract([
            'settings'       => $settings,
            'identityImages' => $identityImages,
        ]);

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/settings/site_identity.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function deleteImage()
    {
        $key = (string)($_POST['delete_key'] ?? '');
        if ($key === '' || !in_array($key, $this->imageKeys, true)) {
            Response::redirect('/admin/settings/identity');
        }

        $settingsModel = new Settings();
        $settings = $settingsModel->getAll();
        (new UploadService(ROOT_PATH . '/uploads', '/uploads'))->deleteByWebPath($settings[$key] ?? null);
        $settingsModel->set($key, '');

        Response::redirect('/admin/settings/identity');
    }

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

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

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

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