<?php
require_once __DIR__ . '/includes/config.php';
$user = require_login('any');   // both internal staff AND client-portal users must be able to change their password

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $current = (string) input('current_password');
    $new     = (string) input('password');
    $confirm = (string) input('password_confirmation');

    // Re-fetch full user with hash for verification
    $stmt = db()->prepare('SELECT password FROM users WHERE id = ?');
    $stmt->execute([$user['id']]);
    $row = $stmt->fetch();

    if (!$row || !password_verify($current, $row['password'])) {
        $errors[] = 'Current password is incorrect.';
    }
    if ($new !== $confirm) {
        $errors[] = 'New password and confirmation do not match.';
    }
    if (!$errors) {
        $errs = password_policy_errors($new);
        $errors = array_merge($errors, $errs);
    }
    if (!$errors && password_verify($new, $row['password'])) {
        $errors[] = 'New password must differ from the current one.';
    }

    if (!$errors) {
        $hash = password_hash($new, PASSWORD_BCRYPT, ['cost' => 12]);
        db()->prepare(
            'UPDATE users SET password=?, must_change_password=0, password_changed_at=NOW(), updated_at=NOW() WHERE id=?'
        )->execute([$hash, $user['id']]);
        $_SESSION['must_change_pw'] = false;
        audit_log('user.password.change', 'user', (int) $user['id']);
        flash('success', 'Password updated successfully.');
        if (($user['user_type'] ?? '') === 'client') {            // client users → their branded portal, not the staff dashboard
            $slug = db()->prepare('SELECT login_slug FROM client_branding WHERE client_id=?');
            $slug->execute([(int) ($user['client_id'] ?? 0)]); $slug = (string) $slug->fetchColumn();
            redirect('/client/overall.php' . ($slug !== '' ? '?slug=' . urlencode($slug) : ''));
        }
        redirect('/dashboard.php');
    }
}

$pageTitle = 'Change password';
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title><?= e($pageTitle) ?> &mdash; <?= e(APP_NAME) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/@tabler/core@1.0.0-beta20/dist/css/tabler.min.css" rel="stylesheet"/>
    <link href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@2.47.0/tabler-icons.min.css" rel="stylesheet"/>
    <style>:root { --tblr-primary: #206bc4; } body { background: linear-gradient(135deg,#f5f7fb 0%,#eef1f7 100%); }</style>
    <?php require __DIR__ . '/includes/compact-css.php'; ?>
</head>
<body class="d-flex flex-column">
<div class="page page-center">
    <div class="container container-tight py-4">
        <div class="text-center mb-4">
            <span class="d-inline-flex align-items-center fs-2 fw-bold" style="color: var(--tblr-primary)">
                <i class="ti ti-key me-2 fs-1"></i><?= e(APP_NAME) ?>
            </span>
        </div>
        <div class="card card-md">
            <div class="card-body">
                <h2 class="h3 text-center mb-3">Set a new password</h2>
                <p class="text-secondary">
                    Minimum <?= (int) PASSWORD_MIN_LENGTH ?> characters.
                    Must include upper + lower case letters, a number and a symbol.
                </p>
                <?php if ($errors): ?>
                    <div class="alert alert-danger">
                        <?php foreach ($errors as $e): ?><div><?= e($e) ?></div><?php endforeach; ?>
                    </div>
                <?php endif; ?>
                <form method="POST" autocomplete="off">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label class="form-label">Current password</label>
                        <input type="password" name="current_password" class="form-control" required autofocus/>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">New password</label>
                        <input type="password" name="password" class="form-control" required/>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirm new password</label>
                        <input type="password" name="password_confirmation" class="form-control" required/>
                    </div>
                    <div class="form-footer">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="ti ti-check me-2"></i>Save new password
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>
