<?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>
    
    <!-- ========== ENHANCED MODERN CSS (preserves all original classes) ========== -->
    <style>
        /* Reset & Base */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            position: relative;
            overflow-x: hidden;
        }
        /* Animated Background Shapes */
        .bg-shape {
            position: fixed;
            filter: blur(80px);
            opacity: 0.35;
            z-index: 0;
            border-radius: 50%;
            animation: floatBg 18s infinite ease-in-out;
            pointer-events: none;
        }
        .shape-1 { top: -150px; left: -150px; width: 400px; height: 400px; background: radial-gradient(circle, #00ffff, #0080ff); }
        .shape-2 { bottom: -120px; right: -120px; width: 500px; height: 500px; background: radial-gradient(circle, #ff00ff, #ff0080); animation-delay: -6s; }
        .shape-3 { top: 40%; left: -80px; width: 300px; height: 300px; background: radial-gradient(circle, #ffd700, #ff6600); animation-delay: -12s; }
        @keyframes floatBg {
            0% { transform: translate(0, 0) scale(1); }
            50% { transform: translate(40px, 30px) scale(1.1); }
            100% { transform: translate(0, 0) scale(1); }
        }
        
        /* Navbar - original classes, upgraded look */
        .navbar {
            position: relative;
            z-index: 100;
            background: rgba(15, 12, 41, 0.7);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid rgba(255,255,255,0.1);
            padding: 1rem 2rem;
        }
        .nav-container {
            max-width: 1300px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
            text-decoration: none;
            letter-spacing: -0.5px;
        }
        .logo img {
            height: 40px;
            width: auto;
            filter: drop-shadow(0 2px 5px rgba(0,0,0,0.2));
        }
        .mobile-toggle {
            display: none;
            background: none;
            border: none;
            color: white;
            font-size: 1.8rem;
            cursor: pointer;
        }
        .nav-links {
            display: flex;
            gap: 2rem;
            list-style: none;
            align-items: center;
        }
        .nav-links li a {
            color: rgba(255,255,255,0.85);
            text-decoration: none;
            font-weight: 500;
            transition: 0.2s;
            font-size: 0.95rem;
            padding: 0.5rem 0;
        }
        .nav-links li a:hover {
            color: white;
            text-shadow: 0 0 6px rgba(255,255,255,0.5);
        }
        .nav-links li a.active {
            color: #c084fc;
            border-bottom: 2px solid #c084fc;
        }
        @media (max-width: 768px) {
            .navbar { padding: 0.8rem 1.2rem; }
            .mobile-toggle { display: block; }
            .nav-links {
                display: none;
                width: 100%;
                flex-direction: column;
                gap: 1rem;
                padding: 1.2rem 0 0.5rem;
            }
            .nav-links.active {
                display: flex;
            }
            .nav-links li a {
                display: block;
                padding: 0.5rem;
                text-align: center;
            }
        }
        
        /* Login Container & Card - enhanced glassmorphism */
        .login-container {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem 1.5rem;
            position: relative;
            z-index: 10;
        }
        .login-card {
            background: rgba(255, 255, 255, 0.07);
            backdrop-filter: blur(14px);
            border-radius: 2rem;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 25px 45px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255,255,255,0.1);
            padding: 2rem;
            width: 100%;
            max-width: 460px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        .login-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 30px 55px rgba(0, 0, 0, 0.4);
        }
        /* Shine effect on card */
        .login-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.12), transparent);
            transition: left 0.5s;
            pointer-events: none;
        }
        .login-card:hover::before {
            left: 100%;
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 1.8rem;
        }
        .login-header h1 {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(135deg, #fff, #c084fc);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            margin-bottom: 0.3rem;
        }
        .login-header p {
            color: rgba(255,255,255,0.7);
            font-size: 0.85rem;
        }
        
        .login-body {
            /* no extra styles needed */
        }
        
        .form-group {
            margin-bottom: 1.3rem;
        }
        .form-label {
            display: block;
            color: rgba(255,255,255,0.9);
            font-weight: 500;
            font-size: 0.8rem;
            margin-bottom: 0.5rem;
            letter-spacing: 0.5px;
        }
        .form-control {
            width: 100%;
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 1.2rem;
            padding: 0.85rem 1rem;
            font-size: 0.9rem;
            color: white;
            font-weight: 500;
            transition: 0.2s;
            outline: none;
            font-family: 'Poppins', sans-serif;
        }
        .form-control:focus {
            border-color: rgba(255,255,255,0.6);
            background: rgba(255,255,255,0.15);
            box-shadow: 0 0 10px rgba(255,255,255,0.15);
        }
        .form-control::placeholder {
            color: rgba(255,255,255,0.4);
        }
        /* Password input wrapper */
        .password-input {
            position: relative;
            display: flex;
            align-items: center;
        }
        .password-input .form-control {
            padding-right: 2.8rem;
        }
        .toggle-password {
            position: absolute;
            right: 1rem;
            background: none;
            border: none;
            color: rgba(255,255,255,0.6);
            cursor: pointer;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            transition: 0.2s;
        }
        .toggle-password:hover {
            color: white;
        }
        
        .form-options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 1.2rem 0 1.5rem;
            font-size: 0.8rem;
        }
        .remember-me {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: rgba(255,255,255,0.8);
        }
        .remember-me input {
            accent-color: #7c3aed;
            width: 1rem;
            height: 1rem;
        }
        .forgot-password {
            color: #a78bfa;
            text-decoration: none;
            font-weight: 500;
        }
        .forgot-password:hover {
            color: white;
        }
        
        .login-btn {
            width: 100%;
            background: linear-gradient(95deg, #7c3aed, #a855f7);
            border: none;
            border-radius: 1.8rem;
            padding: 0.85rem;
            font-weight: 700;
            font-size: 0.95rem;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            cursor: pointer;
            transition: 0.2s;
            position: relative;
            overflow: hidden;
            box-shadow: 0 6px 18px rgba(124,58,237,0.3);
        }
        .login-btn:hover {
            transform: scale(1.02);
            box-shadow: 0 8px 22px rgba(124,58,237,0.5);
        }
        .register-link {
            text-align: center;
            margin-top: 1.3rem;
            font-size: 0.8rem;
            color: rgba(255,255,255,0.7);
        }
        .register-link a {
            color: #c084fc;
            text-decoration: none;
            font-weight: 600;
        }
        .register-link a:hover {
            text-shadow: 0 0 5px #c084fc;
        }
        
        /* Footer */
        .footer {
            text-align: center;
            padding: 1.2rem;
            font-size: 0.7rem;
            color: rgba(255,255,255,0.4);
            z-index: 10;
            position: relative;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        /* Alert container (if any) */
        .alert-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
        .alert {
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(8px);
            border-radius: 1rem;
            padding: 0.8rem 1.2rem;
            color: white;
            margin-bottom: 0.5rem;
            animation: slideIn 0.3s ease;
        }
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
    </style>
</head>

<body>
    <!-- Animated background shapes (added for glamour, does not affect functionality) -->
    <div class="bg-shape shape-1"></div>
    <div class="bg-shape shape-2"></div>
    <div class="bg-shape shape-3"></div>

    <!-- 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 (original HTML unchanged) -->
    <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 (original HTML unchanged) -->
    <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 (original unchanged) -->
    <footer class="footer">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> <?php echo strtoupper($_SERVER['SERVER_NAME']); ?>. All rights reserved.</p>
        </div>
    </footer>

    <!-- Original JavaScript (unchanged) -->
    <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>