<?php
require_once __DIR__ . '/bootstrap.php';

$auth->requireLogin();

$userModel = new User();
$error     = null;
$success   = null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!hash_equals(Session::get('csrf_token', ''), $token)) {
        $error = t('msg.error');
    } else {
        $action = $_POST['action'] ?? '';

        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;

            // Pref Oracle : landing page après sélection de base
            // (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;
                }
            }
            // Pref Oracle : format rapports ASH/SQL Monitor
            if ($oraFmt !== null && in_array($oraFmt, ['html', 'active'], true)) {
                $data['oracle_report_format'] = $oraFmt;
            }
            // Pref PostgreSQL : landing page après sélection de base
            $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($currentUser['id'], $data)) {
                // Apply immediately
                if (!empty($data['language'])) {
                    $i18n->setLanguage($data['language']);
                    Session::set('language', $data['language']);
                }
                if (!empty($data['theme'])) {
                    $activeTheme = $data['theme'];
                    Session::set('theme', $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, $currentUser['password_hash'] ?? '')) {
                $error = t('auth.login_error');
            } elseif (strlen($newPass) < 8) {
                $error = 'Password must be at least 8 characters.';
            } else {
                $userModel->update($currentUser['id'], ['password' => $newPass]);
                $success = t('msg.password_changed');
            }
        }
    }

    // Reload user after changes
    $currentUser = $userModel->findById($currentUser['id']);
}

if (!Session::has('csrf_token')) {
    Session::set('csrf_token', bin2hex(random_bytes(32)));
}

$pageTitle = t('nav.profile');
include __DIR__ . '/includes/header.php';
?>

<h1><?= t('nav.profile') ?></h1>
<p><?= t('auth.username') ?>: <strong><?= htmlspecialchars($currentUser['username']) ?></strong>
   · <?= t('user.roles') ?>:
   <?php if (empty($currentUser['roles'])): ?>
       <em>—</em>
   <?php else: foreach ($currentUser['roles'] as $r): ?>
       <span class="badge <?= $r === ROLE_APP_ADMIN ? 'badge-warning' : 'badge-info' ?>"
             style="font-size:.72rem;margin-right:.2rem"><?= htmlspecialchars(t('role.' . $r)) ?></span>
   <?php endforeach; endif; ?>
</p>

<?php if ($error):   echo '<div class="alert alert-error">'   . htmlspecialchars($error)   . '</div>'; endif; ?>
<?php if ($success): echo '<div class="alert alert-success">' . htmlspecialchars($success) . '</div>'; endif; ?>

<div class="card-grid">

    <!-- Preferences -->
    <div class="card">
        <h2><?= t('user.language') ?> &amp; <?= t('user.theme') ?></h2>
        <form method="post" action="/profile.php">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(Session::get('csrf_token')) ?>">
            <input type="hidden" name="action"     value="preferences">

            <div class="form-group">
                <label for="language"><?= t('user.language') ?></label>
                <select id="language" name="language">
                    <option value=""><?= t('settings.default_lang') ?> (<?= t('lang.' . $i18n->getLanguage()) ?>)</option>
                    <?php foreach (LANGUAGES as $code): ?>
                    <option value="<?= $code ?>"
                        <?= ($currentUser['language'] === $code) ? 'selected' : '' ?>>
                        <?= t('lang.' . $code) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="theme"><?= t('user.theme') ?></label>
                <select id="theme" name="theme">
                    <option value=""><?= t('settings.default_theme') ?></option>
                    <?php foreach (THEMES as $themeKey): ?>
                    <option value="<?= $themeKey ?>"
                        <?= ($currentUser['theme'] === $themeKey) ? 'selected' : '' ?>>
                        <?= t('theme.' . $themeKey) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <?php
            /* ── Préférences Oracle ────────────────────────────────────────
             *   Affichées seulement si l'utilisateur a au moins un rôle Oracle
             *   (sinon les paramètres sont inutiles pour lui).            */
            // Modules supprimables (admin > Modules) : ne pas fataler si absent.
            $_oraUrls   = WEBROOT_PATH . '/modules/oracle/lib/OracleUrls.php';
            $_userRoles = $currentUser['roles'] ?? [];
            $_hasOracle = is_file($_oraUrls) && (
                          in_array(ROLE_APP_ADMIN, $_userRoles, true)
                       || in_array('oracle_admin', $_userRoles, true)
                       || in_array('oracle_user',  $_userRoles, true));
            if ($_hasOracle):
                require_once $_oraUrls;
                $_curLanding = (string)($currentUser['oracle_landing']        ?? '');
                $_curFormat  = (string)($currentUser['oracle_report_format']  ?? 'html');
                if ($_curFormat === '') $_curFormat = 'html';
            ?>
            <hr style="margin:1rem 0;border:0;border-top:1px solid var(--color-border)">
            <h3 style="margin:0 0 .5rem;font-size:.92rem;color:var(--color-text-muted)">
                <?= t('user.oracle_prefs') ?>
            </h3>

            <div class="form-group">
                <label for="oracle_landing"><?= t('user.oracle_landing') ?></label>
                <select id="oracle_landing" name="oracle_landing">
                    <?php foreach (oracle_landing_pages() as $_path => $_labelKey): ?>
                    <option value="<?= htmlspecialchars($_path) ?>"
                        <?= ($_curLanding === $_path) ? 'selected' : '' ?>>
                        <?= htmlspecialchars(t($_labelKey)) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <small style="display:block;color:var(--color-text-muted);margin-top:.25rem;font-size:.78rem">
                    <?= t('user.oracle_landing_hint') ?>
                </small>
            </div>

            <div class="form-group">
                <label for="oracle_report_format"><?= t('user.oracle_report_format') ?></label>
                <select id="oracle_report_format" name="oracle_report_format">
                    <option value="html"   <?= $_curFormat === 'html'   ? 'selected' : '' ?>>
                        <?= t('user.oracle_format_html') ?>
                    </option>
                    <option value="active" <?= $_curFormat === 'active' ? 'selected' : '' ?>>
                        <?= t('user.oracle_format_active') ?>
                    </option>
                </select>
                <small style="display:block;color:var(--color-text-muted);margin-top:.25rem;font-size:.78rem">
                    <?= t('user.oracle_format_hint') ?>
                </small>
            </div>
            <?php endif; ?>

            <?php
            /* ── Préférences PostgreSQL ────────────────────────────────────
             *   Page d'accueil après le choix d'une base — réglable aussi en
             *   un clic via le bouton flottant des pages de rapport.     */
            $_pgUrls = WEBROOT_PATH . '/modules/postgresql/lib/PostgresUrls.php';
            $_hasPg  = is_file($_pgUrls) && (
                       in_array(ROLE_APP_ADMIN, $_userRoles, true)
                    || in_array('postgresql_admin', $_userRoles, true)
                    || in_array('postgresql_user',  $_userRoles, true));
            if ($_hasPg):
                require_once $_pgUrls;
                $_curPgLanding = (string)($currentUser['postgresql_landing'] ?? '');
            ?>
            <hr style="margin:1rem 0;border:0;border-top:1px solid var(--color-border)">
            <h3 style="margin:0 0 .5rem;font-size:.92rem;color:var(--color-text-muted)">
                <?= t('user.postgresql_prefs') ?>
            </h3>

            <div class="form-group">
                <label for="postgresql_landing"><?= t('user.postgresql_landing') ?></label>
                <select id="postgresql_landing" name="postgresql_landing">
                    <?php foreach (pg_landing_pages() as $_path => $_labelKey): ?>
                    <option value="<?= htmlspecialchars($_path) ?>"
                        <?= ($_curPgLanding === $_path) ? 'selected' : '' ?>>
                        <?= htmlspecialchars(t($_labelKey)) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <small style="display:block;color:var(--color-text-muted);margin-top:.25rem;font-size:.78rem">
                    <?= t('user.postgresql_landing_hint') ?>
                </small>
            </div>
            <?php endif; ?>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary"><?= t('user.save') ?></button>
            </div>
        </form>
    </div>

    <!-- Password change (only for local accounts) -->
    <?php if ($currentUser['auth_method'] === AUTH_LOCAL): ?>
    <div class="card">
        <h2><?= t('auth.password') ?></h2>
        <form method="post" action="/profile.php">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(Session::get('csrf_token')) ?>">
            <input type="hidden" name="action"     value="password">

            <div class="form-group">
                <label for="current_password"><?= t('auth.password') ?> *</label>
                <input type="password" id="current_password" name="current_password"
                       required autocomplete="current-password">
            </div>

            <div class="form-group">
                <label for="new_password"><?= t('auth.password_new') ?> *</label>
                <input type="password" id="new_password" name="new_password"
                       required minlength="8" autocomplete="new-password">
            </div>

            <div class="form-group">
                <label for="confirm_password"><?= t('auth.password_conf') ?> *</label>
                <input type="password" id="confirm_password" name="confirm_password"
                       required minlength="8" autocomplete="new-password">
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-secondary"><?= t('msg.password_changed') ?></button>
            </div>
        </form>
    </div>
    <?php endif; ?>

</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
