<?php
class Controller
{
    protected array $viewData = [];
    protected string $viewFile = '';

    protected function view(string $view, array $data = []): void
    {
        $config = require __DIR__ . '/../../config/config.php';
        $data['baseUrl'] = rtrim($config['app']['url'], '/');
        $data['siteSettings'] = $this->loadSiteSettings();
        $this->viewData = $data;
        $this->viewFile = __DIR__ . '/../views/' . str_replace('.', '/', $view) . '.php';
        extract($data);
        require __DIR__ . '/../views/layouts/main.php';
    }

    protected function loadSiteSettings(): array
    {
        $settings = [];
        try {
            $settingModel = new Setting();
            $settingModel->createTableIfNotExists();
            foreach ($settingModel->all() as $item) {
                $settings[$item['setting_key']] = $item['setting_value'];
            }
        } catch (Throwable $e) {
            // Ignore if settings table is not yet available.
        }
        return $settings;
    }

    protected function renderViewContent(): void
    {
        extract($this->viewData);
        if (file_exists($this->viewFile)) {
            require $this->viewFile;
        }
    }

    protected function redirect(string $url): void
    {
        if (!preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) {
            $config = require __DIR__ . '/../../config/config.php';
            $baseUrl = rtrim($config['app']['url'], '/');
            if (str_starts_with($url, '/')) {
                $url = $baseUrl . $url;
            } else {
                $url = $baseUrl . '/' . ltrim($url, '/');
            }
        }
        header('Location: ' . $url, true, 302);
        exit;
    }

    protected function isPost(): bool
    {
        return $_SERVER['REQUEST_METHOD'] === 'POST';
    }

    protected function setFlash(string $type, string $message): void
    {
        $_SESSION['flash'] = [
            'type' => $type,
            'message' => $message,
        ];
    }

    protected function getFlash(): ?array
    {
        if (!empty($_SESSION['flash'])) {
            $flash = $_SESSION['flash'];
            unset($_SESSION['flash']);
            return $flash;
        }
        return null;
    }

    protected function inputOld(string $key, string $default = ''): string
    {
        $source = $_POST[$key] ?? $_GET[$key] ?? $default;
        return is_string($source) ? $source : $default;
    }

    protected function jsonResponse(array $payload, int $statusCode = 200): void
    {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($payload);
        exit;
    }
}
