<?php
// /edenrms/pages/change_password.php
declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';
ec_require_login();

$db = ec_db();
if (!$db instanceof mysqli) {
    die('DB connection failed');
}

$ACTIVE = 'profile';

if (!function_exists('h')) {
    function h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

function cp_table_exists(mysqli $db, string $table): bool {
    if (function_exists('table_exists')) {
        return table_exists($db, $table);
    }
    $table = $db->real_escape_string($table);
    $rs = $db->query("SHOW TABLES LIKE '{$table}'");
    return $rs && $rs->num_rows > 0;
}

function cp_col_exists(mysqli $db, string $table, string $col): bool {
    if (function_exists('col_exists')) {
        return col_exists($db, $table, $col);
    }
    $table = $db->real_escape_string($table);
    $col   = $db->real_escape_string($col);
    $rs = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
    return $rs && $rs->num_rows > 0;
}

function cp_csrf_token(): string {
    if (empty($_SESSION['cp_csrf_token'])) {
        $_SESSION['cp_csrf_token'] = bin2hex(random_bytes(32));
    }
    return (string)$_SESSION['cp_csrf_token'];
}

function cp_password_strength_errors(string $password): array {
    $errors = [];

    if (strlen($password) < 8) {
        $errors[] = 'New password must be at least 8 characters.';
    }

    if (!preg_match('/[A-Z]/', $password)) {
        $errors[] = 'New password must contain at least one uppercase letter.';
    }

    if (!preg_match('/[a-z]/', $password)) {
        $errors[] = 'New password must contain at least one lowercase letter.';
    }

    if (!preg_match('/[0-9]/', $password)) {
        $errors[] = 'New password must contain at least one number.';
    }

    return $errors;
}

$current = ec_user();
$userId = (int)($current['id'] ?? 0);

if ($userId <= 0) {
    die('Invalid logged-in user. Please logout and login again.');
}

if (!cp_table_exists($db, 'users')) {
    die('Users table not found.');
}

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

$st = $db->prepare("SELECT id, name, email, password_hash FROM users WHERE id = ? LIMIT 1");
$st->bind_param('i', $userId);
$st->execute();
$user = $st->get_result()->fetch_assoc();
$st->close();

if (!$user) {
    die('User not found.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = (string)($_POST['csrf_token'] ?? '');
    $currentPassword = (string)($_POST['current_password'] ?? '');
    $newPassword = (string)($_POST['new_password'] ?? '');
    $confirmPassword = (string)($_POST['confirm_password'] ?? '');

    if (!hash_equals(cp_csrf_token(), $token)) {
        $errors[] = 'Security token expired. Please refresh the page and try again.';
    }

    if ($currentPassword === '') {
        $errors[] = 'Current password is required.';
    }

    if ($newPassword === '') {
        $errors[] = 'New password is required.';
    }

    if ($newPassword !== $confirmPassword) {
        $errors[] = 'New password and confirm password do not match.';
    }

    if (!$errors && !password_verify($currentPassword, (string)$user['password_hash'])) {
        $errors[] = 'Current password is incorrect.';
    }

    if (!$errors) {
        $errors = array_merge($errors, cp_password_strength_errors($newPassword));
    }

    if (!$errors && password_verify($newPassword, (string)$user['password_hash'])) {
        $errors[] = 'New password cannot be the same as the current password.';
    }

    if (!$errors) {
        $hash = password_hash($newPassword, PASSWORD_DEFAULT);

        $sets = ['password_hash = ?'];
        if (cp_col_exists($db, 'users', 'updated_at')) {
            $sets[] = 'updated_at = NOW()';
        }

        $sql = "UPDATE users SET " . implode(', ', $sets) . " WHERE id = ? LIMIT 1";
        $st = $db->prepare($sql);

        if (!$st) {
            $errors[] = 'Password update failed: ' . $db->error;
        } else {
            $st->bind_param('si', $hash, $userId);
            $ok = $st->execute();
            $st->close();

            if ($ok) {
                unset($_SESSION['cp_csrf_token']);
                $success = 'Password changed successfully.';
            } else {
                $errors[] = 'Password update failed.';
            }
        }
    }
}

$csrf = cp_csrf_token();

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<main class="ec-main">
    <div class="container-fluid py-4">

        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4">
            <div>
                <h4 class="mb-1 fw-bold">Change Password</h4>
                <div class="text-muted small">Update your RMS login password.</div>
            </div>
            <a href="profile.php" class="btn btn-light border rounded-pill px-4">
                <i class="bi bi-arrow-left me-1"></i> Back to Profile
            </a>
        </div>

        <div class="row justify-content-center">
            <div class="col-lg-7 col-xl-6">

                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <?= h($success) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

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

                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-body p-4 p-lg-5">
                        <div class="text-center mb-4">
                            <div class="mx-auto rounded-circle bg-dark text-white d-flex align-items-center justify-content-center mb-3"
                                 style="width:64px;height:64px;">
                                <i class="bi bi-shield-lock fs-3"></i>
                            </div>
                            <h5 class="fw-bold mb-1">Secure Your Account</h5>
                            <div class="text-muted small">Use a strong password with letters and numbers.</div>
                        </div>

                        <form method="post" autocomplete="off">
                            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">

                            <div class="mb-3">
                                <label class="form-label fw-semibold">Current Password</label>
                                <div class="input-group">
                                    <input type="password" name="current_password" id="current_password"
                                           class="form-control rounded-start-3" required>
                                    <button type="button" class="btn btn-outline-secondary rounded-end-3"
                                            onclick="togglePass('current_password', this)">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label fw-semibold">New Password</label>
                                <div class="input-group">
                                    <input type="password" name="new_password" id="new_password"
                                           class="form-control rounded-start-3" required minlength="8">
                                    <button type="button" class="btn btn-outline-secondary rounded-end-3"
                                            onclick="togglePass('new_password', this)">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                                <div class="form-text">
                                    Minimum 8 characters, uppercase, lowercase and number.
                                </div>
                            </div>

                            <div class="mb-4">
                                <label class="form-label fw-semibold">Confirm New Password</label>
                                <div class="input-group">
                                    <input type="password" name="confirm_password" id="confirm_password"
                                           class="form-control rounded-start-3" required minlength="8">
                                    <button type="button" class="btn btn-outline-secondary rounded-end-3"
                                            onclick="togglePass('confirm_password', this)">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>

                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary rounded-pill py-2">
                                    <i class="bi bi-check2-circle me-1"></i> Update Password
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="alert alert-light border mt-4 rounded-4 small text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    After changing your password, use the new password from your next login.
                </div>

            </div>
        </div>

    </div>
</main>
</div>

<script>
function togglePass(id, btn) {
    const input = document.getElementById(id);
    const icon = btn.querySelector('i');
    if (!input) return;

    if (input.type === 'password') {
        input.type = 'text';
        if (icon) icon.className = 'bi bi-eye-slash';
    } else {
        input.type = 'password';
        if (icon) icon.className = 'bi bi-eye';
    }
}
</script>

</body>
</html>