<?php

class ProfileController extends Controller
{
    public function show(): void
    {
        $this->requireLogin();
        $this->ensureCsrf();

        $error   = null;
        $success = null;

        if ($this->isPost()) {
            [$error, $success] = $this->handlePost();
            $this->currentUser = (new User())->findById($this->currentUser['id']);
        }

        $this->view(WEBROOT_PATH . '/views/profile.php', [
            'error'   => $error,
            'success' => $success,
        ]);
    }

    private function handlePost(): array
    {
        $error = $success = null;

        if (!$this->verifyCsrf()) {
            return [t('msg.error'), null];
        }

        $action    = $_POST['action'] ?? '';
        $userModel = new User();

        if ($action === 'preferences') {
            $lang    = $_POST['language']             ?? null;
            $theme   = $_POST['theme']                ?? null;
            $landing = $_POST['oracle_landing']       ?? null;
            $oraFmt  = $_POST['oracle_report_format'] ?? null;
            $pgLand  = $_POST['postgresql_landing']   ?? null;

            $data = [];
            if ($lang  && in_array($lang, LANGUAGES))  $data['language'] = $lang;
            if ($theme && in_array($theme, THEMES))     $data['theme']    = $theme;

            // Modules supprimables : ne pas fataler si le fichier a disparu.
            $oraUrls = WEBROOT_PATH . '/modules/oracle/lib/OracleUrls.php';
            if ($landing !== null && is_file($oraUrls)) {
                require_once $oraUrls;
                $validLandings = array_keys(oracle_landing_pages());
                if (in_array($landing, $validLandings, true)) {
                    $data['oracle_landing'] = $landing;
                }
            }
            if ($oraFmt !== null && in_array($oraFmt, ['html', 'active'], true)) {
                $data['oracle_report_format'] = $oraFmt;
            }
            $pgUrls = WEBROOT_PATH . '/modules/postgresql/lib/PostgresUrls.php';
            if ($pgLand !== null && is_file($pgUrls)) {
                require_once $pgUrls;
                if (in_array($pgLand, array_keys(pg_landing_pages()), true)) {
                    $data['postgresql_landing'] = $pgLand;
                }
            }

            if ($userModel->update($this->currentUser['id'], $data)) {
                if (!empty($data['language'])) {
                    $this->i18n->setLanguage($data['language']);
                    Session::set('language', $data['language']);
                }
                if (!empty($data['theme'])) {
                    $this->activeTheme = $data['theme'];
                    Session::set('theme', $this->activeTheme);
                }
                $success = t('msg.saved');
            } else {
                $error = t('msg.error');
            }

        } elseif ($action === 'password') {
            $current  = $_POST['current_password']  ?? '';
            $newPass  = $_POST['new_password']       ?? '';
            $confPass = $_POST['confirm_password']   ?? '';

            if (empty($current) || empty($newPass) || empty($confPass)) {
                $error = t('msg.required_fields');
            } elseif ($newPass !== $confPass) {
                $error = t('msg.passwords_mismatch');
            } elseif (!password_verify($current, $this->currentUser['password_hash'] ?? '')) {
                $error = t('auth.login_error');
            } elseif (strlen($newPass) < 8) {
                $error = t('auth.password_too_short');
            } else {
                $userModel->update($this->currentUser['id'], ['password' => $newPass]);
                $success = t('msg.password_changed');
            }
        }

        return [$error, $success];
    }
}
