<?php
/**
 * actions/password-change.php — POST handler: change own password
 * Both roles. POST only. Requires current password verification.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/audit.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(base_url('pages/profile.php'));
}

require_login();
csrf_verify();

$user_id         = current_user_id();
$current_password = $_POST['current_password'] ?? '';
$new_password     = $_POST['new_password'] ?? '';
$new_confirm      = $_POST['new_password_confirm'] ?? '';

// ── Validation ────────────────────────────────────────────────────────────────

$errors = [];

// Load current hash from DB
$stmt = db()->prepare('SELECT password_hash FROM users WHERE id = ?');
$stmt->execute([$user_id]);
$row = $stmt->fetch();

if (!$row || !password_verify($current_password, $row['password_hash'])) {
    $errors[] = 'Current password is incorrect.';
}

if ($new_password === '') {
    $errors[] = 'New password is required.';
} elseif (strlen($new_password) < 8) {
    $errors[] = 'New password must be at least 8 characters.';
} elseif ($new_password !== $new_confirm) {
    $errors[] = 'New passwords do not match.';
}

if ($errors) {
    set_flash('error', implode(' ', $errors));
    redirect(base_url('pages/profile.php'));
}

// ── Save ──────────────────────────────────────────────────────────────────────

$new_hash = password_hash($new_password, PASSWORD_BCRYPT);

$upd = db()->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
$upd->execute([$new_hash, $user_id]);

audit_log('user.password_change', 'Changed own password', $user_id, 'user');
set_flash('success', 'Password changed successfully.');
redirect(base_url('pages/profile.php'));
