<?php
@session_start();
include('./includes/config.php');

if(isset($_SESSION['user_id']) && $_SESSION['is_login'] === true) {
    header("Location: admin");
    exit();
}

if(isset($_POST['username']) && !empty($_POST['username'])){
    $u = mysqli_real_escape_string($tng_conn, $_POST['username']);
    $p = $_POST['password']; // Don't escape password for verification

    $q = mysqli_query($tng_conn,"SELECT * FROM users WHERE (phone='$u' OR email='$u')");

    if(mysqli_num_rows($q) == 1){
        $r = mysqli_fetch_assoc($q);

        if(password_verify($p, $r['password'])){
            
            // First check if account is active
            if($r['status'] == 1){
                $f = $r['phone'];
                $domain = $_SERVER['SERVER_NAME'];

                // Check OTP system
                if(XyZ_val('otp_option') == "yes" && $r['otp_system'] == "yes"){
                    $o = rand(100000,999999); // 6-digit OTP
                    $_SESSION['otp'] = $o;
                    $_SESSION['otp_phone'] = $f;
                    $_SESSION['otp_user_id'] = $r['id'];
                    $_SESSION['otp_time'] = time();

                    $MSG = "🔑 Hello {$r['name']}!\n\nYour OTP for login is: $o\n⏱️ It is valid for 5 minutes.\n🌐 Login at: $domain";
                    $SV = $_SERVER['SERVER_NAME'];
                    
                    // Send WhatsApp message
                    if(function_exists('sendWhatsAppMessage')) {
                        sendWhatsAppMessage($f, $MSG, $SV);
                    }
                    
                    // Send email
                    if(function_exists('sendOtpEmail')) {
                        sendOtpEmail($r['email'], $r['name'], $o, $domain);
                    }

                    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                    <script>
                    document.addEventListener("DOMContentLoaded", function(){
                        Swal.fire({
                            title: "OTP Sent",
                            text: "OTP sent to your registered phone and email",
                            input: "text",
                            inputLabel: "Enter 6-digit OTP",
                            inputPlaceholder: "000000",
                            inputAttributes: {
                                maxlength: 6,
                                pattern: "[0-9]{6}"
                            },
                            showCancelButton: true,
                            confirmButtonText: "Verify OTP",
                            cancelButtonText: "Cancel",
                            preConfirm: (otp) => {
                                if (!otp || otp.length !== 6) {
                                    Swal.showValidationMessage("Please enter 6-digit OTP");
                                    return false;
                                }
                                return otp;
                            }
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Verify OTP
                                fetch("verify_otp.php", {
                                    method: "POST",
                                    headers: {
                                        "Content-Type": "application/x-www-form-urlencoded",
                                    },
                                    body: "otp=" + result.value
                                })
                                .then(response => response.text())
                                .then(data => {
                                    if (data === "success") {
                                        Swal.fire({
                                            title: "Success!",
                                            text: "Login Successful!",
                                            icon: "success",
                                            confirmButtonText: "Continue"
                                        }).then(() => {
                                            window.location.href = "admin";
                                        });
                                    } else {
                                        Swal.fire({
                                            title: "Error!",
                                            text: "Invalid OTP",
                                            icon: "error",
                                            confirmButtonText: "Try Again"
                                        });
                                    }
                                });
                            }
                        });
                    });
                    </script>';
                    exit; 

                } else {
                    // Direct login without OTP
                   
                    
                    mysqli_query($tng_conn, "UPDATE users SET login_token='$login_token', login_time='$login_time', is_login=1 WHERE id='".$r['id']."'");

                    $_SESSION['phone'] = $f;
                    $_SESSION['user_id'] = $r['id'];
                    $_SESSION['is_login'] = true;
                    $_SESSION['login_token'] = $login_token;

                    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                    <script>
                    document.addEventListener("DOMContentLoaded", function(){
                        Swal.fire({
                            title: "Success!",
                            text: "Login Successful! Welcome '.$r['name'].'",
                            icon: "success",
                            confirmButtonText: "Continue"
                        }).then(() => {
                            window.location.href = "admin";
                        });
                    });
                    </script>';
                    exit; 
                }

            } else {
                // Account inactive - Show payment option
                $fee = isset($r['type']) ? getRegistrationFee($r['type']) : 0;
$encodedPhone = base64_encode($r['phone']);
echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded", function(){
    Swal.fire({
        title: "Account Inactive",
        html: "Your account is currently inactive.<br>Pay <b>₹'.$fee.'</b> to activate your account",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Pay Now",
        cancelButtonText: "Later",
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33"
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "payment.php?phone='.$encodedPhone.'";
        }
    });
});
</script>';
exit;
            } } else {
            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire({
                    title: "Error!",
                    text: "Incorrect Password",
                    icon: "error",
                    confirmButtonText: "OK",
                    confirmButtonColor: "#d33"
                });
            });
            </script>';
        }
    } else {
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
        document.addEventListener("DOMContentLoaded", function(){
            Swal.fire({
                title: "Error!",
                text: "User not registered",
                icon: "error",
                confirmButtonText: "OK",
                confirmButtonColor: "#d33"
            });
        });
        </script>';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="./template/tngweb/assets/images/favicon-32x32.png" type="image/png" />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <title><?php echo XyZ_val('brand'); ?> | <?php echo XyZ_val('title'); ?></title>
    <link href="./template/tngweb/assets/css/newlogin-extended.css" rel="stylesheet">

</head>

<body>
    <!-- Alert Container for PHP messages -->
    <?php if (isset($show_alert) && $show_alert): ?>
    <div class="alert-container">
        <div class="alert alert-<?php echo $alert_type; ?>">
            <?php echo $alert_message; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Navigation -->
    <nav class="navbar">
        <div class="nav-container">
            <a href="index.php" class="logo">
                <img src="<?php echo XyZ_val('logo'); ?>" alt="Logo">
                <?php echo XyZ_val('brand'); ?>
            </a>
            
            <button class="mobile-toggle" id="mobileToggle">
                <i class='bx bx-menu'></i>
            </button>
            
            <ul class="nav-links" id="navLinks">
                <li><a href="index.php" class="active">Home</a></li>
                <?php if (XyZ_val('register_status') === 'active'): ?>
                <li><a href="register.php">Register</a></li>
                <?php endif; ?>
                <li><a href="Forgot-password.php">Forgot Password</a></li>
                <li><a href="contact.php">Contact</a></li>
            </ul>
        </div>
    </nav>

    <!-- Login Content -->
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h1>Welcome Back</h1>
                <p>Sign in to access your account</p>
            </div>
            
            <div class="login-body">
                <form method="POST" action="" id="loginForm">
                    <div class="form-group">
                        <label for="username" class="form-label">Email or Phone *</label>
                        <input type="text" name="username" id="username" class="form-control" placeholder="Enter your email or phone" required value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="password" class="form-label">Password *</label>
                        <div class="password-input">
                            <input type="password" name="password" id="password" class="form-control" placeholder="Enter your password" required>
                            <button type="button" class="toggle-password" id="togglePassword">
                                <i class='bx bx-hide'></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="form-options">
                        <div class="remember-me">
                            <input type="checkbox" id="remember" name="remember" checked>
                            <label for="remember">Remember me</label>
                        </div>
                        <a href="Forgot-password.php" class="forgot-password">Forgot Password?</a>
                    </div>
                    
                    <button type="submit" class="login-btn" id="submitBtn">
                        <i class='bx bxs-lock-open'></i> Sign In
                    </button>
                    
                    <?php if (XyZ_val('register_status') === 'active'): ?>
                    <div class="register-link">
                        Don't have an account? <a href="register.php">Sign up here</a>
                    </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> <?php echo strtoupper($_SERVER['SERVER_NAME']); ?>. All rights reserved.</p>
        </div>
    </footer>

    <script>
        // Mobile menu toggle
        document.getElementById('mobileToggle').addEventListener('click', function() {
            document.getElementById('navLinks').classList.toggle('active');
        });
        
        // Password visibility toggle
        document.getElementById('togglePassword').addEventListener('click', function() {
            const passwordInput = document.getElementById('password');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('bx-hide');
                icon.classList.add('bx-show');
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('bx-show');
                icon.classList.add('bx-hide');
            }
        });
        
        // Close mobile menu when clicking outside
        document.addEventListener('click', function(event) {
            const navLinks = document.getElementById('navLinks');
            const mobileToggle = document.getElementById('mobileToggle');
            
            if (!mobileToggle.contains(event.target) && !navLinks.contains(event.target)) {
                navLinks.classList.remove('active');
            }
        });
        
        // Form submission handling
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.innerHTML;
            
            // Show loading state
            submitBtn.innerHTML = '<i class="bx bx-loader-alt bx-spin"></i> Signing In...';
            submitBtn.disabled = true;
            
            // Allow form to submit normally
        });
        
        // Auto-hide alerts after 5 seconds
        window.addEventListener('load', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                setTimeout(() => {
                    alert.style.animation = 'slideIn 0.3s ease reverse';
                    setTimeout(() => {
                        alert.style.display = 'none';
                    }, 300);
                }, 5000);
            });
        });
    </script>
</body>
</html>