<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/session.php';
require_once __DIR__ . '/config/otp-helper.php';
require_once __DIR__ . '/config/mailer.php';

$resetError = '';
$resetSuccess = '';
$activeStep = 'request';
$resetEmail = '';

if (isset($_SESSION['password_reset']['email'])) {
    $sessionEmail = trim((string)$_SESSION['password_reset']['email']);
    if ($sessionEmail !== '' && filter_var($sessionEmail, FILTER_VALIDATE_EMAIL)) {
        $resetEmail = $sessionEmail;
        $activeStep = !empty($_SESSION['password_reset']['otp_verified']) ? 'reset' : 'verify';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['reset_action'] ?? '';

    if ($action === 'request_otp') {
        $email = trim((string)($_POST['reset_email'] ?? ''));
        $resetEmail = $email;

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $resetError = 'Please enter a valid email address.';
            $activeStep = 'request';
        } else {
            $stmt = $conn->prepare("SELECT first_name FROM users WHERE email = ? AND is_active = 1 LIMIT 1");
            if ($stmt) {
                $stmt->bind_param('s', $email);
                $stmt->execute();
                $user = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                if (!$user) {
                    $resetError = 'No active account found for this email.';
                    $activeStep = 'request';
                } else {
                    $firstName = trim((string)($user['first_name'] ?? 'User'));
                    if ($firstName === '') {
                        $firstName = 'User';
                    }

                    $otp = generateOTP(6);
                    $otpStored = storeOTP($email, $otp, 'password_reset');
                    $otpSent = $otpStored ? sendOTPEmail($email, $firstName, $otp, 'password_reset') : false;

                    if ($otpStored && $otpSent) {
                        $_SESSION['password_reset'] = [
                            'email' => $email,
                            'first_name' => $firstName,
                            'otp_verified' => false,
                            'requested_at' => time()
                        ];
                        $resetSuccess = 'OTP sent to ' . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . '.';
                        $activeStep = 'verify';
                    } else {
                        $resetError = 'Unable to send OTP right now. Please try again.';
                        $activeStep = 'request';
                    }
                }
            } else {
                $resetError = 'Unable to process this request.';
                $activeStep = 'request';
            }
        }
    } elseif ($action === 'verify_otp') {
        $email = trim((string)($_POST['verify_email'] ?? ''));
        $otp = trim((string)($_POST['verify_otp'] ?? ''));
        $resetEmail = $email;

        if ($email === '' || $otp === '') {
            $resetError = 'Please enter the OTP.';
            $activeStep = 'verify';
        } elseif (!isset($_SESSION['password_reset']['email'])) {
            $resetError = 'Session expired. Please request OTP again.';
            $activeStep = 'request';
        } elseif (strcasecmp((string)$_SESSION['password_reset']['email'], $email) !== 0) {
            $resetError = 'Email mismatch. Please use the same email address.';
            $activeStep = 'verify';
            $resetEmail = (string)$_SESSION['password_reset']['email'];
        } else {
            $verifyResult = verifyOTP($email, $otp, 'password_reset');
            if ($verifyResult['success']) {
                $_SESSION['password_reset']['otp_verified'] = true;
                $_SESSION['password_reset']['verified_at'] = time();
                $resetSuccess = 'OTP verified. Set your new password.';
                $activeStep = 'reset';
            } else {
                $resetError = $verifyResult['message'];
                $activeStep = 'verify';
            }
        }
    } elseif ($action === 'resend_otp') {
        if (!isset($_SESSION['password_reset']['email'])) {
            $resetError = 'Session expired. Please request OTP again.';
            $activeStep = 'request';
        } else {
            $email = (string)$_SESSION['password_reset']['email'];
            $firstName = (string)($_SESSION['password_reset']['first_name'] ?? 'User');
            $resetEmail = $email;

            $otp = generateOTP(6);
            $otpStored = storeOTP($email, $otp, 'password_reset');
            $otpSent = $otpStored ? sendOTPEmail($email, $firstName, $otp, 'password_reset') : false;

            if ($otpStored && $otpSent) {
                $_SESSION['password_reset']['otp_verified'] = false;
                $_SESSION['password_reset']['requested_at'] = time();
                $resetSuccess = 'A new OTP has been sent to your email.';
            } else {
                $resetError = 'Unable to resend OTP right now. Please try again.';
            }
            $activeStep = 'verify';
        }
    } elseif ($action === 'update_password') {
        $email = trim((string)($_POST['reset_email_confirm'] ?? ''));
        $newPassword = (string)($_POST['new_password'] ?? '');
        $confirmPassword = (string)($_POST['confirm_password'] ?? '');
        $resetEmail = $email;

        if (!isset($_SESSION['password_reset']['email']) || empty($_SESSION['password_reset']['otp_verified'])) {
            $resetError = 'Please verify OTP before setting a new password.';
            $activeStep = 'request';
        } elseif (strcasecmp((string)$_SESSION['password_reset']['email'], $email) !== 0) {
            $resetError = 'Email mismatch. Please restart password reset.';
            $activeStep = 'request';
        } elseif ($newPassword === '' || $confirmPassword === '') {
            $resetError = 'Please enter and confirm your new password.';
            $activeStep = 'reset';
        } elseif (strlen($newPassword) < 6) {
            $resetError = 'Password must be at least 6 characters.';
            $activeStep = 'reset';
        } elseif ($newPassword !== $confirmPassword) {
            $resetError = 'Password and confirm password do not match.';
            $activeStep = 'reset';
        } else {
            $passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
            $updateStmt = $conn->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE email = ? AND is_active = 1");

            if ($updateStmt) {
                $updateStmt->bind_param('ss', $passwordHash, $email);
                $updated = $updateStmt->execute();
                $rows = $updateStmt->affected_rows;
                $updateStmt->close();

                if ($updated && $rows >= 0) {
                    unset($_SESSION['password_reset']);
                    $resetSuccess = 'Password reset successful. You can now log in.';
                    $activeStep = 'done';
                    $resetEmail = '';
                } else {
                    $resetError = 'Unable to update password. Please try again.';
                    $activeStep = 'reset';
                }
            } else {
                $resetError = 'Unable to update password. Please try again.';
                $activeStep = 'reset';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Forgot Password | Zemaraim Hotel Booking</title>
    <link rel="icon" href="images/icon.webp" type="image/gif" sizes="16x16">
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta content="Reset your password for Zemaraim hotel booking account." name="description">
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" id="bootstrap">
    <link href="css/plugins.css" rel="stylesheet" type="text/css">
    <link href="css/style.css" rel="stylesheet" type="text/css">
    <link href="css/coloring.css" rel="stylesheet" type="text/css">
    <link id="colors" href="css/colors/scheme-01.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div id="wrapper">
        <a href="#" id="back-to-top"></a>
        <div id="de-loader"></div>

        <section class="auth-page-section">
            <div class="container">
                <div class="auth-shell js-auth-shell is-ready">
                    <div class="auth-grid">
                        <aside class="auth-brand">
                            <div class="auth-brand-content auth-brand-login">
                                <h2>Reset Password</h2>
                                <p>Recover your account in 3 steps: request OTP, verify OTP, set new password.</p>
                                <ul class="auth-brand-list">
                                    <li><i class="icofont-check-circled"></i>OTP sent to your registered email</li>
                                    <li><i class="icofont-check-circled"></i>10-minute secure verification code</li>
                                    <li><i class="icofont-check-circled"></i>Password update after OTP confirmation</li>
                                </ul>
                            </div>
                        </aside>

                        <div class="auth-panel auth-single-panel">
                            <div class="auth-single-wrap">
                                <h3>Forgot your password?</h3>

                                <?php if ($resetError !== ''): ?>
                                    <div class="alert alert-danger mt-3" role="alert"><?php echo htmlspecialchars($resetError, ENT_QUOTES, 'UTF-8'); ?></div>
                                <?php endif; ?>
                                <?php if ($resetSuccess !== ''): ?>
                                    <div class="alert alert-success mt-3" role="alert"><?php echo htmlspecialchars($resetSuccess, ENT_QUOTES, 'UTF-8'); ?></div>
                                <?php endif; ?>

                                <?php if ($activeStep === 'request'): ?>
                                    <p>Enter your registered email to receive a password reset OTP.</p>
                                    <form class="auth-form" action="" method="post">
                                        <input type="hidden" name="reset_action" value="request_otp">
                                        <div class="row">
                                            <div class="col-12">
                                                <input type="email" name="reset_email" class="form-control" placeholder="Enter your email address" value="<?php echo htmlspecialchars($resetEmail, ENT_QUOTES, 'UTF-8'); ?>" required>
                                            </div>
                                        </div>
                                        <div class="mt-3">
                                            <button type="submit" class="btn-main">Send OTP</button>
                                        </div>
                                    </form>
                                <?php elseif ($activeStep === 'verify'): ?>
                                    <p>Enter the OTP sent to <strong><?php echo htmlspecialchars($resetEmail, ENT_QUOTES, 'UTF-8'); ?></strong>.</p>
                                    <form class="auth-form" action="" method="post">
                                        <input type="hidden" name="reset_action" value="verify_otp">
                                        <input type="hidden" name="verify_email" value="<?php echo htmlspecialchars($resetEmail, ENT_QUOTES, 'UTF-8'); ?>">
                                        <div class="row">
                                            <div class="col-12">
                                                <input type="text" name="verify_otp" class="form-control form-control-lg text-center" placeholder="000000" maxlength="6" required>
                                            </div>
                                        </div>
                                        <div class="mt-3">
                                            <button type="submit" class="btn-main">Verify OTP</button>
                                        </div>
                                    </form>
                                    <form action="" method="post" class="mt-2">
                                        <input type="hidden" name="reset_action" value="resend_otp">
                                        <button type="submit" class="btn-link">Didn't receive OTP? Resend</button>
                                    </form>
                                <?php elseif ($activeStep === 'reset'): ?>
                                    <p>OTP verified. Enter your new password for <strong><?php echo htmlspecialchars($resetEmail, ENT_QUOTES, 'UTF-8'); ?></strong>.</p>
                                    <form class="auth-form" action="" method="post">
                                        <input type="hidden" name="reset_action" value="update_password">
                                        <input type="hidden" name="reset_email_confirm" value="<?php echo htmlspecialchars($resetEmail, ENT_QUOTES, 'UTF-8'); ?>">
                                        <div class="row">
                                            <div class="col-12">
                                                <input type="password" name="new_password" class="form-control" placeholder="New password" required>
                                            </div>
                                            <div class="col-12">
                                                <input type="password" name="confirm_password" class="form-control" placeholder="Confirm new password" required>
                                            </div>
                                        </div>
                                        <div class="mt-3">
                                            <button type="submit" class="btn-main">Update Password</button>
                                        </div>
                                    </form>
                                <?php else: ?>
                                    <p>Your password has been reset successfully.</p>
                                    <div class="mt-3">
                                        <a href="login.php" class="btn-main">Go to Login</a>
                                    </div>
                                <?php endif; ?>

                                <div class="auth-help mt-3">
                                    <a href="login.php">Back to Login</a>
                                    <a href="register.php">Create New Account</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <script src="js/plugins.js"></script>
    <script src="js/designesia.js"></script>
    <script src="js/auth-transition.js"></script>
</body>
</html>
