<?php
/**
 * Admin account action — update or remove admin password.
 *
 * Actions:
 *   POST (default)       — set/change the PHP admin password
 *   POST action=remove_credentials — remove the password from DB
 */

require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
require_once __DIR__ . '/../../../src/Database.php';

AdminAuth::requireLogin();

// ── CSRF ──────────────────────────────────────────────────────────────────────
if (empty($_SESSION['csrf_token']) || ($_POST['csrf_token'] ?? '') !== $_SESSION['csrf_token']) {
    http_response_code(403);
    die('Invalid CSRF token.');
}

$hasPassword     = AdminAuth::hasPassword();
$action          = $_POST['action'] ?? 'change_password';

// ── Remove credential ────────────────────────────────────────────────────────
if ($action === 'remove_credentials') {
    $backUrl = $_POST['redirect'] ?? '/admin/parametres.php';
    if (!preg_match('#^/admin/#', $backUrl)) { $backUrl = '/admin/parametres.php'; }

    if (!$hasPassword) {
        App::flash('error', 'Aucun mot de passe à supprimer.');
        header('Location: ' . $backUrl);
        exit;
    }

    AdminAuth::removePasswordHash();
    // Destroy session so the user is forced to re-authenticate.
    AdminAuth::logout();
    header('Location: /admin/login.php');
    exit;
}

// ── Change / set password ─────────────────────────────────────────────────────

// 1. If a password is already set, verify the current one.
$backUrl = $_POST['redirect'] ?? '/admin/parametres.php';
if (!preg_match('#^/admin/#', $backUrl)) { $backUrl = '/admin/parametres.php'; }

if ($hasPassword) {
    $currentPassword = $_POST['current_password'] ?? '';
    if (!AdminAuth::login($currentPassword)) {
        App::flash('error', 'Mot de passe actuel incorrect.');
        header('Location: ' . $backUrl);
        exit;
    }
}

// 2. Validate new password.
$newPassword     = $_POST['new_password']     ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';

if (strlen($newPassword) < 12) {
    App::flash('error', 'Le nouveau mot de passe doit contenir au moins 12 caractères.');
    header('Location: ' . $backUrl);
    exit;
}

if ($newPassword !== $confirmPassword) {
    App::flash('error', 'Les mots de passe ne correspondent pas.');
    header('Location: ' . $backUrl);
    exit;
}

// 3. Generate bcrypt hash (cost 12).
$hash = password_hash($newPassword, PASSWORD_BCRYPT, ['cost' => 12]);
if ($hash === false) {
    App::flash('error', 'Erreur lors du hachage du mot de passe.');
    header('Location: ' . $backUrl);
    exit;
}

// 4. Store hash in DB.
AdminAuth::setPasswordHash($hash);

// 5. Regenerate session (password changed — invalidate old sessions).
session_regenerate_id(true);
$_SESSION['admin_authenticated'] = true;

App::flash('success', $hasPassword
    ? 'Mot de passe mis à jour avec succès.'
    : 'Mot de passe défini avec succès. L\'authentification PHP est maintenant active.');

header('Location: ' . $backUrl);
exit;
