<?php
require_once __DIR__ . "/config.inc.php";
require_user_login();

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        user_check_csrf();
    } catch (Throwable $e) {
        $errors[] = "Invalid CSRF token. Refresh and try again.";
    }

    $current = $_POST['current_password'] ?? '';
    $new     = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    if ($current === '') {
        $errors[] = "Current password is required.";
    }
    if (!valid_new_password($new)) {
        $errors[] = "New password must be at least 8 characters.";
    }
    if ($new !== $confirm) {
        $errors[] = "New password and confirmation do not match.";
    }
    if ($current !== '' && $new !== '' && hash_equals($current, $new)) {
        $errors[] = "New password must be different from your current password.";
    }

    if (!$errors) {
        $db = db();

        $stmt = $db->prepare("SELECT password_hash FROM users WHERE id = ? LIMIT 1");
        $uid = (int)$_SESSION['user_id'];
        $stmt->bind_param("i", $uid);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$row || !password_verify($current, $row['password_hash'])) {
            $errors[] = "Current password is incorrect.";
        } else {
            $hash = password_hash($new, PASSWORD_DEFAULT);
            $stmt = $db->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
            $stmt->bind_param("si", $hash, $uid);
            $stmt->execute();
            $stmt->close();

            // Invalidate any outstanding forgot-password links.
            $stmt = $db->prepare("DELETE FROM password_resets WHERE user_id = ?");
            $stmt->bind_param("i", $uid);
            $stmt->execute();
            $stmt->close();

            session_regenerate_id(true);
            $success = "Your password has been changed successfully.";
        }
    }
}

require_once __DIR__ . "/partials/header.php";
?>
<div class="row justify-content-center">
    <div class="col-md-6 col-lg-5">
        <div class="card shadow-sm">
            <div class="card-body">
                <h4 class="mb-3">Change Password</h4>

                <?php if ($success): ?>
                    <div class="alert alert-success"><?= e($success) ?></div>
                <?php endif; ?>

                <?php if ($errors): ?>
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            <?php foreach ($errors as $er): ?>
                                <li><?= e($er) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <form method="post" class="row g-3">
                    <input type="hidden" name="csrf_token" value="<?= e(user_csrf()) ?>">

                    <div class="col-12">
                        <label class="form-label">Current Password</label>
                        <input class="form-control" type="password" name="current_password" required autocomplete="current-password">
                    </div>

                    <div class="col-12">
                        <label class="form-label">New Password</label>
                        <input class="form-control" type="password" name="new_password" minlength="8" required autocomplete="new-password">
                        <div class="form-text">Minimum 8 characters.</div>
                    </div>

                    <div class="col-12">
                        <label class="form-label">Confirm New Password</label>
                        <input class="form-control" type="password" name="confirm_password" minlength="8" required autocomplete="new-password">
                    </div>

                    <div class="col-12 d-grid">
                        <button class="btn btn-primary" type="submit">Change Password</button>
                    </div>

                    <div class="col-12 text-center">
                        <a href="index.php">Back to account</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . "/partials/footer.php"; ?>
