<?php
/**
 * change_password.php
 *
 * Secure password-change form for RoomZ PMS.
 * Compatible with:
 * - legacy SHA-1 passwords stored in users.password
 * - modern password_hash() passwords
 */

if (session_status() === PHP_SESSION_NONE) {
    session_name('PIONEERS_PMS_SESSION');

    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/rooms/',
        'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    session_start();
}

require_once __DIR__ . '/includes/database_connection.php';
require_once __DIR__ . '/includes/functions.php';

date_default_timezone_set('Africa/Harare');

if (empty($_SESSION['ss_user_id']) && empty($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$userId = (int)($_SESSION['ss_user_id'] ?? $_SESSION['user_id'] ?? 0);

if ($userId <= 0) {
    header('Location: login.php');
    exit;
}

if (!function_exists('cp_e')) {
    function cp_e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('cp_column_exists')) {
    function cp_column_exists(PDO $pdo, string $table, string $column): bool
    {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = :table_name
                  AND COLUMN_NAME = :column_name
            ");
            $stmt->execute([
                ':table_name' => $table,
                ':column_name' => $column,
            ]);

            return (int)$stmt->fetchColumn() > 0;
        } catch (Throwable $e) {
            return false;
        }
    }
}

$error = '';
$success = '';
$appName = function_exists('app_setting')
    ? app_setting($pdo, 'name', 'RoomZ PMS')
    : 'RoomZ PMS';

$stmt = $pdo->prepare("
    SELECT
        id,
        username,
        email,
        firstname,
        lastname,
        password,
        active
    FROM users
    WHERE id = :id
    LIMIT 1
");
$stmt->execute([':id' => $userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || (int)($user['active'] ?? 0) !== 1) {
    session_destroy();
    header('Location: login.php');
    exit;
}

$displayName = trim(
    (string)($user['firstname'] ?? '')
    . ' '
    . (string)($user['lastname'] ?? '')
);

if ($displayName === '') {
    $displayName = (string)($user['username'] ?? 'User');
}

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

    if ($currentPassword === '' || $newPassword === '' || $confirmPassword === '') {
        $error = 'Please complete all password fields.';
    } elseif (strlen($newPassword) < 8) {
        $error = 'The new password must contain at least 8 characters.';
    } elseif (!preg_match('/[A-Za-z]/', $newPassword) || !preg_match('/[0-9]/', $newPassword)) {
        $error = 'The new password must contain at least one letter and one number.';
    } elseif ($newPassword !== $confirmPassword) {
        $error = 'The new password and confirmation do not match.';
    } elseif (hash_equals($currentPassword, $newPassword)) {
        $error = 'The new password must be different from the current password.';
    } else {
        $storedPassword = (string)($user['password'] ?? '');
        $currentValid = false;

        /*
         * Match login.php:
         * - 40-character hexadecimal passwords are legacy SHA-1.
         * - all other values are checked with password_verify().
         */
        if (
            $storedPassword !== ''
            && strlen($storedPassword) === 40
            && ctype_xdigit($storedPassword)
        ) {
            $currentValid = hash_equals(
                strtolower($storedPassword),
                sha1($currentPassword)
            );
        } else {
            $currentValid = password_verify($currentPassword, $storedPassword);
        }

        if (!$currentValid) {
            $error = 'The current password is incorrect.';
        } else {
            try {
                $newHash = password_hash($newPassword, PASSWORD_DEFAULT);

                if ($newHash === false) {
                    throw new RuntimeException('Could not secure the new password.');
                }

                $setParts = ['password = :password'];
                $params = [
                    ':password' => $newHash,
                    ':id' => $userId,
                ];

                foreach ([
                    'password_changed_at',
                    'password_updated_at',
                    'updated_at'
                ] as $dateColumn) {
                    if (cp_column_exists($pdo, 'users', $dateColumn)) {
                        $setParts[] = "`{$dateColumn}` = NOW()";
                        break;
                    }
                }

                /*
                 * Some installations use NextPassWordChangeDate.
                 * Push the next forced-change date 90 days ahead when present.
                 */
                if (cp_column_exists($pdo, 'users', 'NextPassWordChangeDate')) {
                    $setParts[] = "NextPassWordChangeDate = DATE_ADD(CURDATE(), INTERVAL 90 DAY)";
                }

                $update = $pdo->prepare("
                    UPDATE users
                    SET " . implode(', ', $setParts) . "
                    WHERE id = :id
                ");
                $update->execute($params);

                session_regenerate_id(true);

                $success = 'Your password has been changed successfully.';
                $user['password'] = $newHash;
            } catch (Throwable $e) {
                $error = 'The password could not be changed. Please try again.';
                error_log(
                    'RoomZ password change failed for user '
                    . $userId
                    . ': '
                    . $e->getMessage()
                );
            }
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Change Password | <?php echo cp_e($appName); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link
        href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
        rel="stylesheet"
    >
    <link
        href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css"
        rel="stylesheet"
    >

    <style>
        :root {
            --ink: #0f172a;
            --muted: #64748b;
            --brand: #2563eb;
            --brand-two: #38bdf8;
        }

        * {
            box-sizing: border-box;
        }

        body {
            min-height: 100vh;
            margin: 0;
            color: var(--ink);
            background:
                radial-gradient(circle at top right, rgba(37, 99, 235, .18), transparent 32%),
                radial-gradient(circle at bottom left, rgba(56, 189, 248, .16), transparent 30%),
                linear-gradient(135deg, #eef2ff, #f8fafc 46%, #e0f2fe);
            font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }

        .page-shell {
            min-height: 100vh;
            display: grid;
            place-items: center;
            padding: 2rem 1rem;
        }

        .password-card {
            width: 100%;
            max-width: 620px;
            border: 1px solid rgba(255,255,255,.8);
            border-radius: 30px;
            background: rgba(255,255,255,.88);
            backdrop-filter: blur(22px);
            box-shadow: 0 32px 90px rgba(15,23,42,.16);
            overflow: hidden;
        }

        .card-banner {
            position: relative;
            padding: 2rem;
            color: #fff;
            background:
                radial-gradient(circle at 85% 20%, rgba(255,255,255,.18), transparent 26%),
                linear-gradient(135deg, #0f172a, #1e3a8a 62%, #0284c7);
        }

        .icon-box {
            width: 58px;
            height: 58px;
            display: grid;
            place-items: center;
            border-radius: 18px;
            font-size: 1.55rem;
            background: rgba(255,255,255,.14);
            border: 1px solid rgba(255,255,255,.2);
        }

        .card-banner h1 {
            margin: 1rem 0 .35rem;
            font-size: 1.8rem;
            font-weight: 900;
            letter-spacing: -.04em;
        }

        .card-banner p {
            margin: 0;
            color: rgba(255,255,255,.76);
        }

        .card-body-custom {
            padding: 2rem;
        }

        .account-strip {
            display: flex;
            align-items: center;
            gap: .9rem;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border-radius: 18px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
        }

        .avatar {
            width: 44px;
            height: 44px;
            display: grid;
            place-items: center;
            border-radius: 15px;
            color: #fff;
            font-weight: 900;
            background: linear-gradient(135deg, var(--brand), var(--brand-two));
        }

        .account-strip strong {
            display: block;
        }

        .account-strip small {
            color: var(--muted);
        }

        .form-label {
            font-size: .78rem;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: .04em;
        }

        .input-group {
            border-radius: 16px;
            box-shadow: 0 10px 26px rgba(15,23,42,.05);
        }

        .input-group-text,
        .form-control,
        .password-toggle {
            min-height: 52px;
            border-color: #dbe3ee;
        }

        .input-group-text {
            border-radius: 16px 0 0 16px;
            background: #f8fafc;
            color: var(--muted);
        }

        .form-control {
            border-left: 0;
            border-right: 0;
            font-weight: 600;
        }

        .password-toggle {
            min-width: 52px;
            border-radius: 0 16px 16px 0;
            background: #f8fafc;
            color: var(--muted);
        }

        .form-control:focus {
            border-color: #93c5fd;
            box-shadow: none;
        }

        .password-guide {
            padding: .9rem 1rem;
            border-radius: 16px;
            color: #475569;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            font-size: .84rem;
        }

        .btn-save {
            min-height: 54px;
            border: 0;
            border-radius: 17px;
            font-weight: 900;
            background: linear-gradient(135deg, var(--brand), var(--brand-two));
            box-shadow: 0 18px 36px rgba(37,99,235,.24);
        }

        .btn-back {
            min-height: 54px;
            border-radius: 17px;
            font-weight: 800;
        }

        .alert {
            border: 0;
            border-radius: 16px;
        }
    </style>
</head>
<body>
<div class="page-shell">
    <div class="password-card">
        <div class="card-banner">
            <div class="icon-box">
                <i class="bi bi-shield-lock"></i>
            </div>

            <h1>Change your password</h1>
            <p>Protect your Rooms account with a strong, private password.</p>
        </div>

        <div class="card-body-custom">
            <div class="account-strip">
                <div class="avatar">
                    <?php echo cp_e(strtoupper(substr($displayName, 0, 1))); ?>
                </div>
                <div>
                    <strong><?php echo cp_e($displayName); ?></strong>
                    <small>
                        <?php echo cp_e($user['username'] ?? ''); ?>
                        <?php if (!empty($user['email'])): ?>
                            &nbsp;•&nbsp; <?php echo cp_e($user['email']); ?>
                        <?php endif; ?>
                    </small>
                </div>
            </div>

            <?php if ($error !== ''): ?>
                <div class="alert alert-danger d-flex gap-2 align-items-start">
                    <i class="bi bi-exclamation-triangle-fill"></i>
                    <div><?php echo cp_e($error); ?></div>
                </div>
            <?php endif; ?>

            <?php if ($success !== ''): ?>
                <div class="alert alert-success d-flex gap-2 align-items-start">
                    <i class="bi bi-check-circle-fill"></i>
                    <div><?php echo cp_e($success); ?></div>
                </div>
            <?php endif; ?>

            <form method="post" autocomplete="off">
                <div class="mb-3">
                    <label class="form-label">Current password</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="bi bi-key"></i>
                        </span>
                        <input
                            type="password"
                            class="form-control password-field"
                            name="current_password"
                            placeholder="Enter your current password"
                            required
                        >
                        <button
                            class="password-toggle"
                            type="button"
                            aria-label="Show password"
                            tabindex="-1"
                        >
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">New password</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="bi bi-shield-plus"></i>
                        </span>
                        <input
                            type="password"
                            class="form-control password-field"
                            name="new_password"
                            placeholder="Enter a new password"
                            minlength="8"
                            required
                        >
                        <button
                            class="password-toggle"
                            type="button"
                            aria-label="Show password"
                            tabindex="-1"
                        >
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Confirm new password</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="bi bi-shield-check"></i>
                        </span>
                        <input
                            type="password"
                            class="form-control password-field"
                            name="confirm_password"
                            placeholder="Repeat the new password"
                            minlength="8"
                            required
                        >
                        <button
                            class="password-toggle"
                            type="button"
                            aria-label="Show password"
                            tabindex="-1"
                        >
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="password-guide mb-4">
                    <i class="bi bi-info-circle me-1"></i>
                    Use at least 8 characters with at least one letter and one number.
                    Do not reuse your current password.
                </div>

                <div class="row g-2">
                    <div class="col-sm-5">
                        <a
                            href="modules/calendar/calendar.php"
                            class="btn btn-outline-secondary btn-back w-100 d-flex align-items-center justify-content-center"
                        >
                            <i class="bi bi-arrow-left me-2"></i>Back to Rooms
                        </a>
                    </div>
                    <div class="col-sm-7">
                        <button type="submit" class="btn btn-primary btn-save w-100">
                            <i class="bi bi-shield-check me-2"></i>Change Password
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.password-toggle').forEach(function (button) {
    button.addEventListener('click', function () {
        var group = this.closest('.input-group');
        var input = group ? group.querySelector('.password-field') : null;
        var icon = this.querySelector('i');

        if (!input) {
            return;
        }

        if (input.type === 'password') {
            input.type = 'text';
            this.setAttribute('aria-label', 'Hide password');

            if (icon) {
                icon.classList.remove('bi-eye');
                icon.classList.add('bi-eye-slash');
            }
        } else {
            input.type = 'password';
            this.setAttribute('aria-label', 'Show password');

            if (icon) {
                icon.classList.remove('bi-eye-slash');
                icon.classList.add('bi-eye');
            }
        }
    });
});
</script>
</body>
</html>
