<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();

$pageTitle = 'Change password';
$activeNav = 'dashboard';

$forced = isset($_GET['forced']) || !empty($_SESSION['must_change_pw']);
$errors = [];
$done = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid security token. Reload the page and try again.';
    } else {
        $uid = (string) ($_SESSION['user_id'] ?? '');
        $current = (string) ($_POST['current_password'] ?? '');
        $new = (string) ($_POST['new_password'] ?? '');
        $new2 = (string) ($_POST['new_password_confirm'] ?? '');

        if ($uid === '') {
            $errors[] = 'Session expired. Sign in again.';
        } elseif (strlen($new) < 8) {
            $errors[] = 'New password must be at least 8 characters.';
        } elseif (!hash_equals($new, $new2)) {
            $errors[] = 'New password confirmation does not match.';
        } elseif (hash_equals($current, $new)) {
            $errors[] = 'New password must be different from the current password.';
        } else {
            $st = $conn->prepare('SELECT password_hash FROM users WHERE id = ? LIMIT 1');
            if (!$st) {
                $errors[] = 'Database error.';
            } else {
                $st->bind_param('s', $uid);
                $st->execute();
                $row = $st->get_result()->fetch_assoc();
                $st->close();
                $hash = (string) ($row['password_hash'] ?? '');
                if ($hash === '' || !password_verify($current, $hash)) {
                    $errors[] = 'Current password is incorrect.';
                } else {
                    $newHash = password_hash($new, PASSWORD_DEFAULT);
                    $upd = $conn->prepare(
                        'UPDATE users SET password_hash = ?, must_change_password = 0,
                         password_changed_at = NOW(), failed_logins = 0, locked_until = NULL
                         WHERE id = ?'
                    );
                    if (!$upd) {
                        $errors[] = 'Could not update password: ' . $conn->error;
                    } else {
                        $upd->bind_param('ss', $newHash, $uid);
                        if (!$upd->execute()) {
                            $errors[] = 'Could not update password: ' . $upd->error;
                        } else {
                            $_SESSION['must_change_pw'] = false;
                            $ip = iscms_client_ip();
                            $ua = substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500);
                            $payload = json_encode(['event' => 'PASSWORD_CHANGED'], JSON_UNESCAPED_UNICODE);
                            $sessId = (string) ($_SESSION['session_db_id'] ?? '');
                            if ($sessId !== '') {
                                $log = $conn->prepare(
                                    'INSERT INTO audit_logs
                                       (id, user_id, session_id, action, module, entity_type, entity_id, new_values, ip_address, user_agent, request_method, request_path)
                                     VALUES (UUID(), ?, ?, \'PASSWORD_CHANGE\', \'authentication\', \'user\', ?, ?, ?, ?, \'POST\', \'/change_password.php\')'
                                );
                                if ($log) {
                                    $log->bind_param('ssssss', $uid, $sessId, $uid, $payload, $ip, $ua);
                                    $log->execute();
                                    $log->close();
                                }
                            } else {
                                $log = $conn->prepare(
                                    'INSERT INTO audit_logs
                                       (id, user_id, action, module, entity_type, entity_id, new_values, ip_address, user_agent, request_method, request_path)
                                     VALUES (UUID(), ?, \'PASSWORD_CHANGE\', \'authentication\', \'user\', ?, ?, ?, ?, \'POST\', \'/change_password.php\')'
                                );
                                if ($log) {
                                    $log->bind_param('sssss', $uid, $uid, $payload, $ip, $ua);
                                    $log->execute();
                                    $log->close();
                                }
                            }
                            $done = true;
                        }
                        $upd->close();
                    }
                }
            }
        }
    }
}

$csrf = iscms_csrf_token();

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Change password</h1>
        <p>Choose a strong password you do not use elsewhere.</p>
    </div>

    <?php if ($forced && !$done): ?>
    <div class="alert alert-warning mb-4" style="font-size:.88rem">
        <i class="ri-alert-line me-1"></i> You must change your password before continuing.
    </div>
    <?php endif; ?>

    <?php if ($done): ?>
    <div class="alert alert-success mb-4" style="font-size:.88rem">
        Password updated. <a href="index.php">Go to dashboard</a>.
    </div>
    <?php endif; ?>

    <?php if ($errors !== []): ?>
    <div class="alert alert-danger mb-4" style="font-size:.88rem">
        <ul class="mb-0 ps-3"><?php foreach ($errors as $e): ?><li><?= iscms_h($e) ?></li><?php endforeach; ?></ul>
    </div>
    <?php endif; ?>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Related</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="profile.php"><i class="ri-user-line"></i> My profile</a>
            <a class="qa-btn" href="logout.php"><i class="ri-logout-box-r-line"></i> Log out</a>
        </div>
    </div>

    <?php if (!$done): ?>
    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-lock-password-line"></i> Update password</h2>
        </div>
        <div class="p-3">
            <form method="post" action="change_password.php" class="row g-3" style="max-width:28rem" autocomplete="off">
                <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">
                <div class="col-12">
                    <label class="form-label">Current password <span class="text-danger">*</span></label>
                    <input type="password" name="current_password" class="form-control form-control-sm" required autocomplete="current-password">
                </div>
                <div class="col-12">
                    <label class="form-label">New password <span class="text-danger">*</span></label>
                    <input type="password" name="new_password" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
                </div>
                <div class="col-12">
                    <label class="form-label">Confirm new password <span class="text-danger">*</span></label>
                    <input type="password" name="new_password_confirm" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary btn-sm"><i class="ri-save-line me-1"></i>Save password</button>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>
<?php
iscms_render_footer();
