<?php
ob_start();
require_once("../config/session.php");
require_once("../config/function.php");
$site_data = site_data();
$is_otp = isset($_SESSION["is_otp"]) && $_SESSION["is_otp"]; // Dynamic OTP status check
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Login | <?=$site_data['brand']?></title>
    <meta name="author" content="HKB WEB">
    <meta property="og:locale" content="en_US">
    <link rel="icon" href="<?=$site_data['logo']?>" type="image/*" sizes="16x16">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/open-iconic/1.1.1/font/css/open-iconic-bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../layouts/members/assets/stylesheets/theme.min.css">
    <link rel="stylesheet" href="../layouts/members/assets/stylesheets/custom.css">
    <style>
        .logo {
            max-width: 100%;
            height: 100px;
        }
    </style>
</head>
<body>
<main class="auth">
    <header id="auth-header" class="auth-header" style="background-image: url(../layouts/members/assets/images/illustration/img-1.png);">
        <h1>
            <img src="<?=$site_data['logo']?>" class="logo">	
            <span class="sr-only">Sign In</span>
        </h1>
        <p>Welcome back, please login to your account.</p>
    </header>

    <form class="auth-form" method="POST" action="">
        <?php
        
        // Handling login submission
        if (isset($_POST['login'])) {
            $username = strip_tags($_POST['username']);
            $password = strip_tags($_POST['password']);

            if (!empty($username) && !empty($password)) {
                $login = login($username, $password);
                if ($login['status']) {
                    $_SESSION["login_token"] = $login['login_token'];
                    if ($login['is_otp'] === "YES") {
                        
                        $_SESSION["is_otp"] = true;
                        header("Location: " . $_SERVER['PHP_SELF']); // Reload for OTP
                        exit();
                    } else {
                        alert_msg("Login Successfull !", 'success');
                        $_SESSION["is_login"] = true;
                        redirect("dashboard", 0);
                        exit();
                    }
                } else {
                    alert_msg($login['message'], 'danger');
                }
            } else {
                alert_msg("Please fill in all fields!", 'danger');
            }
        }

        // Handling OTP verification submission
        if (isset($_POST['login_verify'])) {
            $otp = $_POST['otp'];
            $login_token = $_SESSION["login_token"] ?? null;

            if (!empty($otp) && !empty($login_token) && is_numeric($otp)) {
                $verify = login_otp_verify($login_token, (int)$otp);
                if ($verify['status']) {
                    $_SESSION["is_login"] = true;
                    $_SESSION["is_otp"] = false; // Clear OTP session
                    $_SESSION["login_token"] = $verify['login_token'];
                    redirect("dashboard", 0);
                    exit();
                } else {
                    alert_msg("Invalid OTP! Please try again.", 'danger');
                }
            } else {
                alert_msg("Please enter a valid OTP!", 'danger');
            }
        }
        
        // Handle Resend OTP
        if (isset($_POST['resend_otp'])) {
            $login_token = $_SESSION["login_token"] ?? null;

            if ($login_token) {
                $result = resend_login_otp($login_token);
                alert_msg($result['message'], $result['status'] ? 'success' : 'danger');
                header("Location: " . $_SERVER['PHP_SELF']); // Reload for OTP
            } else {
                alert_msg("Session expired. Please login again.", 'danger');
            }
        }
        // Handling Go Back button click
         if (isset($_POST['go_back'])) {
             session_destroy(); // Destroy the session
             header("Location: " . $_SERVER['PHP_SELF']); // Redirect back to login
             exit();
         }

        ?>

        <?php if (!$is_otp): ?>
            <!-- Login Form -->
            <div class="form-group">
                <div class="form-label-group">
                    <input type="number" name="username" class="form-control" placeholder="Mobile Number" autofocus onkeypress="if(this.value.length==10) return false;" required>
                    <label for="inputUser">Mobile Number</label>
                </div>
            </div>
            <div class="form-group position-relative">
                <div class="form-label-group">
                    <input type="password" name="password" class="form-control" id="passwordInput" placeholder="Password" required oninput="this.value=this.value.replace(/\s/g,'');">
                    <label for="passwordInput">Password</label>
                    <button type="button" class="btn btn-sm btn-light position-absolute" style="top: 50%; right: 10px; transform: translateY(-50%);" onclick="togglePassword()">
                        <i class="fa fa-eye" id="toggleIcon"></i>
                    </button>
                </div>
            </div>
            <div class="form-group">
                <button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Login</button>
            </div>
        <?php else: ?>
            <!-- OTP Verification Form -->
            <div class="form-group">
                <div class="form-label-group"> 
                <label for="inputOtp">One-Time Password</label>
                  <input type="text" name="otp" class="form-control" id="otpInput" placeholder="One-Time Password" maxlength="6" pattern="\d{6}" oninput="this.value=this.value.replace(/[^0-9]/g,'').slice(0,6);">
                </div>
                <small class="form-text text-muted">The OTP is valid for 5 minutes.</small>
            </div>
           <div class="form-group d-flex justify-content-between">
               <button class="btn btn-lg btn-primary" type="submit" name="login_verify">Verify OTP</button>
               <button class="btn btn-lg btn-warning" type="submit" name="resend_otp">Resend OTP</button>
               <button class="btn btn-lg btn-danger" type="submit" name="go_back">Go Back</button>
           </div>

        <?php endif; ?>

        <div class="text-center pt-3">
            <a href="forgotpassword" class="link">Forgot Password?</a> 
            <span class="mx-2"></span> 
            <a href="createaccount" class="link">Create Account?</a>
        </div>
    </form>

    <footer class="auth-footer">Copyright <?=date("Y")?> <?=$site_data['brand']?>. All Rights Reserved.</footer>
</main>
<script>
function togglePassword() {
    const input = document.getElementById("passwordInput");
    const icon = document.getElementById("toggleIcon");
    if (input.type === "password") {
        input.type = "text";
        icon.classList.remove("fa-eye");
        icon.classList.add("fa-eye-slash");
    } else {
        input.type = "password";
        icon.classList.remove("fa-eye-slash");
        icon.classList.add("fa-eye");
    }
}
document.querySelector('.auth-form').addEventListener('submit', function (e) {
    const submitter = document.activeElement; // which button was clicked
    const otpInput = document.getElementById('otpInput');

    if (submitter && submitter.name === 'login_verify') {
        if (!otpInput.value.trim()) {
            e.preventDefault();
            otpInput.focus();
            alert('Please enter a valid OTP!');
        }
    }
});
</script>
<script src="../layouts/members/assets/vendor/jquery/jquery.min.js"></script>
<script src="../layouts/members/assets/vendor/popper.js/umd/popper.min.js"></script>
<script src="../layouts/members/assets/vendor/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
