<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/session.php';

function sanitizeLoginRedirect(string $redirect): string
{
    $redirect = trim($redirect);
    if ($redirect === '') {
        return 'index.php';
    }
    if (preg_match('/^[A-Za-z0-9._\/-]+(\?[A-Za-z0-9._~=&%-]*)?$/', $redirect) !== 1) {
        return 'index.php';
    }
    if (strpos($redirect, '://') !== false || strpos($redirect, '..') !== false) {
        return 'index.php';
    }
    return $redirect;
}

$authError = '';
$authSuccess = '';
$activeView = 'login';
$redirectAfterLogin = sanitizeLoginRedirect((string)($_REQUEST['redirect'] ?? 'index.php'));
$pendingVerificationEmail = '';

if (isset($_SESSION['pending_registration']['email'])) {
    $sessionPendingEmail = trim((string)$_SESSION['pending_registration']['email']);
    if ($sessionPendingEmail !== '' && filter_var($sessionPendingEmail, FILTER_VALIDATE_EMAIL)) {
        $pendingVerificationEmail = $sessionPendingEmail;
    }
}

if (isLoggedIn()) {
    header('Location: ' . $redirectAfterLogin);
    exit();
}

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

    if ($action === 'login') {
        $email = trim((string)($_POST['login_email'] ?? ''));
        $password = (string)($_POST['login_password'] ?? '');

        if ($email === '' || $password === '') {
            $authError = 'Please enter both email and password.';
        } else {
            $stmt = $conn->prepare("SELECT id, first_name, last_name, email, password, user_type, is_active FROM users WHERE email = ? LIMIT 1");
            if ($stmt) {
                $stmt->bind_param('s', $email);
                $stmt->execute();
                $result = $stmt->get_result();
                $user = $result ? $result->fetch_assoc() : null;
                $stmt->close();

                if ($user && (int)$user['is_active'] === 1 && password_verify($password, $user['password'])) {
                    loginUser((int)$user['id'], $user['email'], $user['first_name'], $user['last_name'], $user['user_type']);

                    $updateLogin = $conn->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                    if ($updateLogin) {
                        $userId = (int)$user['id'];
                        $updateLogin->bind_param('i', $userId);
                        $updateLogin->execute();
                        $updateLogin->close();
                    }

                    header('Location: ' . $redirectAfterLogin);
                    exit();
                }
            }

            $authError = 'Invalid email or password.';
        }
    } elseif ($action === 'register') {
        $activeView = 'register';
        $firstName = trim((string)($_POST['register_first_name'] ?? ''));
        $lastName = trim((string)($_POST['register_last_name'] ?? ''));
        $email = trim((string)($_POST['register_email'] ?? ''));
        $password = (string)($_POST['register_password'] ?? '');
        $confirmPassword = (string)($_POST['register_confirm_password'] ?? '');

        if ($firstName === '' || $lastName === '' || $email === '' || $password === '' || $confirmPassword === '') {
            $authError = 'Please complete all registration fields.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $authError = 'Please enter a valid email address.';
        } elseif (strlen($password) < 6) {
            $authError = 'Password must be at least 6 characters.';
        } elseif ($password !== $confirmPassword) {
            $authError = 'Password and confirm password do not match.';
        } else {
            $checkStmt = $conn->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
            if ($checkStmt) {
                $checkStmt->bind_param('s', $email);
                $checkStmt->execute();
                $exists = $checkStmt->get_result()->fetch_assoc();
                $checkStmt->close();

                if ($exists) {
                    $authError = 'Email is already registered.';
                } else {
                    $_SESSION['pending_registration'] = [
                        'first_name' => $firstName,
                        'last_name' => $lastName,
                        'email' => $email,
                        'password_hash' => password_hash($password, PASSWORD_DEFAULT)
                    ];

                    require_once __DIR__ . '/config/otp-helper.php';
                    require_once __DIR__ . '/config/mailer.php';

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

                    if ($otpStored && $otpSent) {
                        $pendingVerificationEmail = $email;
                        $authSuccess = 'Verification code sent to ' . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . '. Please check your email.';
                        $activeView = 'verify';
                    } else {
                        unset($_SESSION['pending_registration']);
                        $authError = 'Unable to send verification code. Please try again.';
                        $activeView = 'register';
                    }
                }
            } else {
                $authError = 'Unable to validate account email.';
            }
        }
    } elseif ($action === 'verify_otp') {
        $email = trim((string)($_POST['verify_email'] ?? ''));
        $otp = trim((string)($_POST['verify_otp'] ?? ''));

        if ($email === '' || $otp === '') {
            $authError = 'Please enter verification code.';
            $activeView = 'verify';
            $pendingVerificationEmail = $email;
        } elseif (!isset($_SESSION['pending_registration']['email'])) {
            $authError = 'Session expired. Please register again.';
            $activeView = 'register';
        } elseif (strcasecmp((string)$_SESSION['pending_registration']['email'], $email) !== 0) {
            $authError = 'Email mismatch. Please verify the email used during registration.';
            $activeView = 'verify';
            $pendingVerificationEmail = (string)$_SESSION['pending_registration']['email'];
        } else {
            require_once __DIR__ . '/config/otp-helper.php';

            $result = verifyOTP($email, $otp, 'verification');

            if ($result['success']) {
                if (isset($_SESSION['pending_registration']) && $_SESSION['pending_registration']['email'] === $email) {
                    $regData = $_SESSION['pending_registration'];

                    $insertStmt = $conn->prepare("INSERT INTO users (first_name, last_name, email, password, user_type, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, 'guest', 1, NOW(), NOW())");

                    if ($insertStmt) {
                        $insertStmt->bind_param('ssss', $regData['first_name'], $regData['last_name'], $regData['email'], $regData['password_hash']);
                        if ($insertStmt->execute()) {
                            unset($_SESSION['pending_registration']);
                            $authSuccess = 'Account verified successfully. You can now log in.';
                            $activeView = 'login';
                        } else {
                            $authError = 'Unable to create account. Please try again.';
                            $activeView = 'verify';
                        }
                        $insertStmt->close();
                    } else {
                        $authError = 'Unable to process registration.';
                        $activeView = 'verify';
                    }
                } else {
                    $authError = 'Session expired. Please register again.';
                    $activeView = 'register';
                }
            } else {
                $authError = $result['message'];
                $activeView = 'verify';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Login | 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="Login and register access for Zemaraim hotel booking." 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 data-default-view="<?php echo htmlspecialchars($activeView, ENT_QUOTES, 'UTF-8'); ?>">
    <div id="wrapper">
        <a href="#" id="back-to-top"></a>
        <div id="de-loader"></div>
        <?php include 'header.php'; ?>

        <section class="auth-page-section">
            <div class="container">
                <div class="auth-shell js-auth-shell">
                    <div class="auth-grid">
                        <aside class="auth-brand">
                            <div class="auth-brand-content auth-brand-state auth-brand-login">
                                <h2>Welcome to Zemaraim</h2>
                                <p>Book rooms, track your reservations, and get exclusive offers with one account.</p>
                                <ul class="auth-brand-list">
                                    <li><i class="icofont-check-circled"></i>Fast reservation checkout</li>
                                    <li><i class="icofont-check-circled"></i>Booking history in one place</li>
                                    <li><i class="icofont-check-circled"></i>Members-only seasonal offers</li>
                                </ul>
                            </div>
                            <div class="auth-brand-content auth-brand-state auth-brand-register">
                                <h2>Sign in to Hotel Booking</h2>
                                <p>Already have an account? Sign in and continue your reservation in seconds.</p>
                                <ul class="auth-brand-list">
                                    <li><i class="icofont-check-circled"></i>View your current bookings</li>
                                    <li><i class="icofont-check-circled"></i>Update guest and stay details</li>
                                    <li><i class="icofont-check-circled"></i>Access exclusive member offers</li>
                                </ul>
                                <div class="mt-3">
                                    <button type="button" class="btn-main btn-line js-auth-switch" data-switch="login">Back to Login</button>
                                </div>
                            </div>
                        </aside>
                        <div class="auth-panel">
                            <div class="auth-switch">
                                <button type="button" class="auth-switch-btn js-auth-switch" data-switch="login">Login</button>
                                <button type="button" class="auth-switch-btn js-auth-switch" data-switch="register">Register</button>
                            </div>
                            <?php if ($authError !== ''): ?>
                                <div class="alert alert-danger mt-3" role="alert"><?php echo htmlspecialchars($authError, ENT_QUOTES, 'UTF-8'); ?></div>
                            <?php endif; ?>
                            <?php if ($authSuccess !== ''): ?>
                                <div class="alert alert-success mt-3" role="alert"><?php echo htmlspecialchars($authSuccess, ENT_QUOTES, 'UTF-8'); ?></div>
                            <?php endif; ?>
                            <div class="auth-forms-track">
                                <div class="auth-forms-inner">
                                    <div class="auth-form-wrap">
                                        <h3>Welcome back</h3>
                                        <p>Sign in to continue booking your stay.</p>
                                        <form class="auth-form" action="" method="post">
                                            <input type="hidden" name="auth_action" value="login">
                                            <input type="hidden" name="redirect" value="<?php echo htmlspecialchars($redirectAfterLogin, ENT_QUOTES, 'UTF-8'); ?>">
                                            <div class="row">
                                                <div class="col-12">
                                                    <input type="email" name="login_email" class="form-control" placeholder="Email address" required>
                                                </div>
                                                <div class="col-12">
                                                    <input type="password" name="login_password" class="form-control" placeholder="Password" required>
                                                </div>
                                            </div>
                                            <div class="auth-help">
                                                <label><input type="checkbox"> Remember me</label>
                                                <a href="forgot-password.php">Forgot password?</a>
                                            </div>
                                            <button type="submit" class="btn-main">Login</button>
                                            <div class="auth-divider">or continue with</div>
                                            <div class="auth-alt-actions">
                                                <a href="#" class="btn-main btn-line">Google</a>
                                                <a href="#" class="btn-main btn-line">Facebook</a>
                                            </div>
                                        </form>
                                    </div>
                                    <div class="auth-form-wrap">
                                        <h3>Create account</h3>
                                        <p>Register once and book faster on every device.</p>
                                        <form class="auth-form" action="" method="post">
                                            <input type="hidden" name="auth_action" value="register">
                                            <input type="hidden" name="redirect" value="<?php echo htmlspecialchars($redirectAfterLogin, ENT_QUOTES, 'UTF-8'); ?>">
                                            <div class="row">
                                                <div class="col-12 col-md-6">
                                                    <input type="text" name="register_first_name" class="form-control" placeholder="First name" required>
                                                </div>
                                                <div class="col-12 col-md-6">
                                                    <input type="text" name="register_last_name" class="form-control" placeholder="Last name" required>
                                                </div>
                                                <div class="col-12">
                                                    <input type="email" name="register_email" class="form-control" placeholder="Email address" required>
                                                </div>
                                                <div class="col-12 col-md-6">
                                                    <input type="password" name="register_password" class="form-control" placeholder="Password" required>
                                                </div>
                                                <div class="col-12 col-md-6">
                                                    <input type="password" name="register_confirm_password" class="form-control" placeholder="Confirm password" required>
                                                </div>
                                            </div>
                                            <div class="auth-help">
                                                <label><input type="checkbox" required> I agree to terms</label>
                                                <a href="#">Privacy policy</a>
                                            </div>
                                            <button type="submit" class="btn-main">Create Account</button>
                                        </form>
                                    </div>
                                    <div class="auth-form-wrap">
                                        <h3>Verify Email</h3>
                                        <p>Enter the verification code sent to your email.</p>
                                        <form class="auth-form" action="" method="post">
                                            <input type="hidden" name="auth_action" value="verify_otp">
                                            <div class="row">
                                                <div class="col-12">
                                                    <input type="hidden" name="verify_email" id="verifyEmail" value="<?php echo htmlspecialchars($pendingVerificationEmail, ENT_QUOTES, 'UTF-8'); ?>">
                                                    <label class="form-label">Verification Code</label>
                                                    <input type="text" name="verify_otp" class="form-control form-control-lg text-center" placeholder="000000" maxlength="6" required>
                                                    <small class="form-text text-muted">6-digit code sent to your email</small>
                                                </div>
                                            </div>
                                            <button type="submit" class="btn-main">Verify &amp; Create Account</button>
                                            <div class="auth-help">
                                                <button type="button" class="btn-link" id="resendOtpBtn">Didn't receive code? Resend</button>
                                            </div>
                                        </form>
                                    </div>
                                </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>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const verifyEmail = document.getElementById('verifyEmail');
            const resendOtpBtn = document.getElementById('resendOtpBtn');
            const registerEmail = document.querySelector('input[name="register_email"]');
            const registerFirstName = document.querySelector('input[name="register_first_name"]');

            document.addEventListener('authSwitched', function(e) {
                if (e.detail === 'verify' && registerEmail && verifyEmail) {
                    verifyEmail.value = registerEmail.value;
                }
            });

            if (resendOtpBtn) {
                resendOtpBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    resendOTP();
                });
            }

            function resendOTP() {
                if (!verifyEmail || !resendOtpBtn) {
                    return;
                }

                const email = verifyEmail.value;
                const firstName = registerFirstName ? registerFirstName.value : 'User';

                if (!email) {
                    alert('Email address not found. Please register again.');
                    return;
                }

                const formData = new FormData();
                formData.append('action', 'resend_otp');
                formData.append('email', email);
                formData.append('first_name', firstName);
                formData.append('purpose', 'verification');

                resendOtpBtn.disabled = true;
                resendOtpBtn.textContent = 'Sending...';

                fetch('api/send-otp.php', {
                    method: 'POST',
                    body: formData
                })
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    if (data.success) {
                        alert('Verification code resent to ' + data.email);
                        startResendCooldown();
                    } else {
                        alert('Error: ' + (data.message || 'Failed to resend OTP'));
                        resendOtpBtn.disabled = false;
                        resendOtpBtn.textContent = 'Didn\'t receive code? Resend';
                    }
                })
                .catch(function(error) {
                    console.error('Error:', error);
                    alert('Failed to resend verification code');
                    resendOtpBtn.disabled = false;
                    resendOtpBtn.textContent = 'Didn\'t receive code? Resend';
                });
            }

            function startResendCooldown() {
                if (!resendOtpBtn) {
                    return;
                }
                let countdown = 60;
                const originalText = 'Didn\'t receive code? Resend';

                const timer = setInterval(function() {
                    resendOtpBtn.textContent = 'Resend in ' + countdown + 's';
                    countdown--;

                    if (countdown < 0) {
                        clearInterval(timer);
                        resendOtpBtn.disabled = false;
                        resendOtpBtn.textContent = originalText;
                    }
                }, 1000);
            }
        });
    </script>
</body>

</html>

<?php include 'footer.php'; ?>
