<?php
// Tells the header to switch to the "Back Arrow" and "Language Selector" layout
$is_auth_page = true;

// ==============================================================================
// 1. DATABASE CONNECTION & LOGIN LOGIC
// ==============================================================================
session_start();

// --- IF ALREADY LOGGED IN, REDIRECT TO INDEX IMMEDIATELY ---
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'config.php'; // Include your DB connection

$message = '';
$messageType = ''; // 'success' or 'error'

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_action'])) {
    $phone = trim($_POST['login_phone'] ?? '');
    $password = $_POST['login_pwd'] ?? '';

    // Check if user exists and password matches (Using plain text as requested)
    $stmt = $pdo->prepare("SELECT id, number, password, isbanned, is_demo FROM users WHERE number = ?");
    $stmt->execute([$phone]);
    $user = $stmt->fetch();

    if ($user && $user['password'] === $password) {
        if ($user['isbanned'] == 1) {
            $message = "Your account has been suspended."; // Account is banned
            $messageType = "error";
        } else {
            // Login successful
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['phone']   = $user['number'];
            $_SESSION['is_demo'] = (int)$user['is_demo'];
            
            $message = "Login successful!"; // Login Successful
            $messageType = "success";
            // Redirect is handled by JS below so toast can animate
        }
    } else {
        $message = "Invalid phone number or password."; // Invalid phone or password
        $messageType = "error";
    }
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
    <title>Login - PAKclub</title>
    
    <meta name="google" content="notranslate">
    <meta name="robots" content="notranslate">
    <meta http-equiv="Content-Language" content="en">
    <script>
        document.documentElement.setAttribute("translate", "no");
        document.documentElement.classList.add("notranslate");
        document.documentElement.setAttribute("lang", "en");

        const translateObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.tagName === 'SCRIPT' && node.src && node.src.includes('translate.google.com')) {
                        node.remove(); 
                    }
                    if (node.className && typeof node.className === 'string' && node.className.includes('goog-te-')) {
                        node.remove(); 
                    }
                });
            });
        });
        translateObserver.observe(document.documentElement, { childList: true, subtree: true });
    </script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="icon" type="image/png" href="./img/ico.png">
    <link rel="apple-touch-icon" href="./img/ico.png">
    
    <style>
        /* ========================================================
           TRANSLATION CSS CLOAKING DEVICE
           ======================================================== */
        .goog-te-banner-frame.skiptranslate, 
        .goog-te-banner-frame, 
        #goog-gt-tt, 
        .goog-te-balloon-frame { 
            display: none !important; 
            visibility: hidden !important; 
            opacity: 0 !important;
        }
        body { top: 0px !important; }
        .goog-text-highlight { background-color: transparent !important; box-shadow: none !important; }

        * { 
            box-sizing: border-box; 
            font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 
            -webkit-tap-highlight-color: transparent !important;
            -webkit-touch-callout: none !important; 
            -webkit-user-select: none !important;   
            -moz-user-select: none !important;      
            -ms-user-select: none !important;       
            user-select: none !important; 
        }

        input, textarea {
            -webkit-user-select: auto !important;
            -moz-user-select: auto !important;
            -ms-user-select: auto !important;
            user-select: auto !important;
        }

        a, button, img, .lang-selector, .auth-header-left {
            touch-action: manipulation !important;
            outline: none !important; 
        }

        /* 1. ACTUAL DARK BROWN BG */
        html, body {
            background-color: #0e0a07 !important; 
            background-image: none !important; 
            margin: 0 auto !important;
            padding: 0;
            min-height: 100vh;
            width: 100% !important;
            max-width: 414px !important; 
            position: relative !important;
            overflow-x: hidden !important;
            -ms-overflow-style: none; 
            -webkit-overflow-scrolling: touch !important; 
            scroll-behavior: smooth; 
        }
        ::-webkit-scrollbar { display: none; width: 0px; background: transparent; }

        /* ========================================================
           CUSTOM TOP HEADER (OVERLAYS HERO IMAGE)
           ======================================================== */
        .custom-top-header {
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            display: flex !important;
            justify-content: space-between !important;
            align-items: center !important;
            padding: 15px 20px !important;
            z-index: 10 !important; 
            background: transparent !important; 
            border: none !important;
            box-shadow: none !important;
        }

        .custom-top-header .back-btn {
            color: #ffffff !important;
            font-size: 22px !important;
            text-decoration: none !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .custom-top-header .header-right-actions {
            display: flex !important;
            align-items: center !important;
            gap: 15px !important;
        }

        .custom-top-header .support-btn {
            color: #ff9800 !important; 
            font-size: 20px !important;
            text-decoration: none !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .custom-top-header .lang-selector {
            display: flex !important;
            align-items: center !important;
            gap: 6px !important;
            color: #ffffff !important;
            font-weight: bold !important;
            font-size: 15px !important;
            cursor: pointer !important;
        }

        .custom-top-header .lang-selector img {
            width: 20px !important;
            height: 20px !important;
            border-radius: 50% !important;
            object-fit: cover !important;
        }

        /* 2. IMAGE AT FULL TOP WITH CSS SVG MASKING */
        .login-hero {
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 320px !important; 
            /* Only the image is loaded here, no gradient overlays */
            background: url('./img/login-bg.png') center top/cover no-repeat !important;
            
            /* THIS IS THE MAGIC: It natively fades the image opacity to 0% at the bottom, eliminating all hard cuts */
            -webkit-mask-image: linear-gradient(to bottom, rgba(0,0,0,1) 40%, rgba(0,0,0,0) 100%) !important;
            mask-image: linear-gradient(to bottom, rgba(0,0,0,1) 40%, rgba(0,0,0,0) 100%) !important;
            
            z-index: 0 !important;
            display: flex !important;
            justify-content: center !important;
        }
        
        .hero-logo {
            position: absolute;
            top: 90px; 
            width: 130px;
        }

        /* 3. FORM CONTAINER */
        .login-container {
            position: relative;
            z-index: 1;
            margin-top: 220px; 
            padding: 0 20px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* --- iPHONE STYLE TOAST NOTIFICATION --- */
        .ios-toast {
            position: fixed;
            bottom: -80px; 
            left: 50%;
            transform: translateX(-50%);
            background: rgba(28, 28, 30, 0.95); 
            backdrop-filter: blur(15px);
            -webkit-backdrop-filter: blur(15px);
            color: #fff;
            padding: 12px 24px;
            border-radius: 30px; 
            font-size: 14px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 99999;
            box-shadow: 0 8px 30px rgba(0,0,0,0.8); 
            transition: bottom 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); 
            white-space: nowrap;
            pointer-events: none;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .ios-toast.show { bottom: 60px; }
        .toast-error i { color: #ff453a; font-size: 16px; } 
        .toast-success i { color: #32d74b; font-size: 16px; } 

        /* 4. FLAT INPUT GROUPS (Boxy, Sharp, No Glow) */
        .input-group {
            background-color: #111111; 
            border: 1px solid #2a2a2a; 
            border-radius: 6px; 
            display: flex;
            align-items: center;
            padding: 12px 15px;
            gap: 12px;
            transition: border-color 0.2s ease;
        }
        
        .input-group:focus-within {
            border-color: #cf7029; 
        }

        .input-icon {
            color: #b09e91;
            font-size: 16px;
        }

        .prefix {
            color: #ffffff;
            font-weight: bold;
            font-size: 14px;
            border-right: 1px solid #2a2a2a;
            padding-right: 12px;
        }

        .input-field {
            flex: 1;
            background: transparent;
            border: none;
            color: #ffffff;
            font-size: 14px;
            outline: none;
            text-align: left; 
            width: 100%;
        }
        
        .input-field::placeholder { color: #6b5c52; }

        /* --- BROWSER AUTOFILL KILLER --- */
        .input-field:-webkit-autofill,
        .input-field:-webkit-autofill:hover, 
        .input-field:-webkit-autofill:focus, 
        .input-field:-webkit-autofill:active {
            -webkit-box-shadow: 0 0 0 30px #111111 inset !important;
            -webkit-text-fill-color: #ffffff !important;
            transition: background-color 5000s ease-in-out 0s;
            caret-color: #ffffff;
        }

        /* 5. CLOUDFLARE WIDGET */
        .cf-widget {
            background-color: #222222; 
            border: 1px solid #3a3a3a;
            border-radius: 3px; 
            padding: 0 12px;
            height: 65px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 5px;
        }

        .cf-left {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .cf-spinner {
            width: 24px;
            height: 24px;
            border: 3px solid transparent;
            border-top-color: #ff9800; 
            border-left-color: #ff9800;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        .cf-success-icon {
            display: none; 
            color: #00c853; 
            font-size: 24px;
        }

        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

        .cf-text {
            color: #ffffff;
            font-size: 14px;
            font-family: -apple-system, sans-serif;
        }

        .cf-right {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 2px;
        }

        .cf-logo {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #ffffff;
            font-size: 12px;
            font-weight: bold;
            font-family: -apple-system, sans-serif;
        }
        
        .cf-logo-cloud {
            color: #f38020; 
            font-size: 18px;
        }

        .cf-links {
            color: #888888;
            font-size: 9px;
            font-family: sans-serif;
        }
        .cf-links a { color: #888888; text-decoration: none; }
        .cf-links a:hover { text-decoration: underline; }

        /* 6. FLAT LINKS & BUTTONS */
        .forgot-link-container {
            text-align: right; 
            width: 100%;
        }

        .forgot-link {
            color: #cfc529; 
            font-size: 13px;
            text-decoration: underline;
            margin-bottom: 20px;
            cursor: pointer;
            display: inline-block;
        }

        .btn-main {
            background: #d17028; 
            color: #fff;
            border: none;
            border-radius: 25px;
            padding: 14px;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            margin-bottom: 12px;
            transition: opacity 0.2s ease;
            font-weight: bold;
        }
        .btn-main:active { opacity: 0.8; }

        .btn-outline {
            background: transparent;
            color: #d17028; 
            border: 1px solid #d17028;
            border-radius: 25px;
            padding: 14px;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            transition: opacity 0.2s ease;
            font-weight: bold;
        }
        .btn-outline:active { opacity: 0.8; }
        
        .eye-icon {
            color: #6b5c52;
            cursor: pointer;
            font-size: 16px;
        }

        /* ========================================================
           FORGOT PASSWORD MODAL 
           ======================================================== */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85); 
            z-index: 1000;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }

        .modal-overlay.active {
            opacity: 1;
            pointer-events: all;
        }

        .modal-content {
            width: 90%;
            max-width: 360px;
            background-color: #1d110b; 
            border-radius: 10px;
            border: 1px solid #362215;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .modal-header {
            padding: 16px;
            text-align: center;
            border-bottom: 1px solid #362215;
        }

        .modal-title {
            color: #ffffff;
            margin: 0;
            font-size: 16px;
            font-weight: bold;
        }

        .modal-body {
            padding: 20px 15px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .btn-send-otp {
            background: #d17028;
            color: #fff;
            border: none;
            border-radius: 20px;
            padding: 6px 14px;
            font-size: 12px;
            cursor: pointer;
            font-family: inherit;
            white-space: nowrap;
        }
        .btn-send-otp:active { opacity: 0.8; }

        .fake-select {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            color: #ffffff;
            cursor: pointer;
        }
        .fake-select-left { 
            display: flex; 
            align-items: center; 
            gap: 10px; 
        }
        .fake-select-icon { 
            color: #b09e91; 
            font-size: 14px; 
        }

        .modal-close-btn {
            margin-top: 25px;
            width: 40px;
            height: 40px;
            border: 1.5px solid #ffffff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #ffffff;
            font-size: 18px;
            cursor: pointer;
            transition: background 0.2s;
        }
        .modal-close-btn:active { background: rgba(255,255,255,0.2); }

    </style>
</head>
<body>

    <?php if (!empty($message)): ?>
        <div id="iosToast" class="ios-toast toast-<?php echo $messageType; ?>">
            <i class="fa-solid <?php echo $messageType === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation'; ?>"></i>
            <span><?php echo $message; ?></span>
        </div>
        <script>
            document.addEventListener("DOMContentLoaded", () => {
                const toast = document.getElementById('iosToast');
                setTimeout(() => { toast.classList.add('show'); }, 10);
                
                <?php if ($messageType === 'success'): ?>
                    setTimeout(() => { window.location.href = 'index.php'; }, 600);
                <?php else: ?>
                    setTimeout(() => { toast.classList.remove('show'); }, 3000);
                <?php endif; ?>
            });
        </script>
    <?php endif; ?>

    <div style="display: none !important; visibility: hidden !important;">
        <?php include 'external/header.php'; ?>
    </div>

    <div class="custom-top-header">
        <a href="javascript:history.back()" class="back-btn">
            <i class="fa-solid fa-chevron-left"></i>
        </a>
        <div class="header-right-actions">
            <a href="support.php" class="support-btn">
                <i class="fa-solid fa-headset"></i>
            </a>
            <div class="lang-selector">
                <img src="https://flagcdn.com/w40/gb.png" alt="English Flag">
                <span>EN</span>
            </div>
        </div>
    </div>

    <div class="login-hero">
        <img src="./img/logo.png" alt="PAKclub" class="hero-logo">
    </div>

    <div class="login-container">
        
        <form id="loginForm" method="POST" action="">
            <input type="hidden" name="login_action" value="1">
            
            <div class="input-group" style="margin-bottom: 15px;">
                <i class="fa-solid fa-mobile-screen input-icon"></i>
                <span class="prefix">+92</span>
                <input type="tel" id="loginPhone" name="login_phone" class="input-field pk-phone" placeholder="Enter your phone number" required>
            </div>

            <div class="input-group" style="margin-bottom: 15px;">
                <i class="fa-solid fa-lock input-icon"></i>
                <input type="password" id="loginPwd" name="login_pwd" class="input-field" placeholder="Please enter password" required>
                <i class="fa-solid fa-eye-slash eye-icon pwd-toggle" data-target="loginPwd"></i>
            </div>

            <div class="cf-widget" id="cfWidget" style="margin-bottom: 15px;">
                <div class="cf-left">
                    <div class="cf-spinner" id="cfSpinner"></div>
                    <i class="fa-solid fa-circle-check cf-success-icon" id="cfSuccess"></i>
                    <span class="cf-text" id="cfText">Verifying...</span>
                </div>
                <div class="cf-right">
                    <div class="cf-logo">
                        <i class="fa-brands fa-cloudflare cf-logo-cloud"></i>
                        CLOUDFLARE
                    </div>
                    <div class="cf-links">
                        <a href="#">Privacy</a> • <a href="#">Help</a>
                    </div>
                </div>
            </div>

            <div class="forgot-link-container">
                <span class="forgot-link" id="openForgotModal">Forgot password?</span>
            </div>

            <button type="submit" class="btn-main">Log in</button>
            <button type="button" class="btn-outline" onclick="window.location.href='signup.php'">Register Now</button>

        </form>

    </div>

    <div class="modal-overlay" id="forgotModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Set Login Password</h3>
            </div>
            
            <form id="forgotPasswordForm" class="modal-body" onsubmit="submitForgotPassword(event)">
                
                <div class="input-group">
                    <div class="fake-select">
                        <div class="fake-select-left">
                            <i class="fa-solid fa-id-card fake-select-icon"></i>
                            <span>Phone</span>
                        </div>
                        <i class="fa-solid fa-chevron-down fake-select-icon"></i>
                    </div>
                </div>

                <div class="input-group">
                    <i class="fa-solid fa-mobile-screen input-icon"></i>
                    <span class="prefix">+92</span>
                    <input type="tel" name="phone" class="input-field pk-phone" placeholder="Enter your phone number" required>
                </div>

                <div class="input-group">
                    <i class="fa-solid fa-shield-halved input-icon"></i>
                    <input type="text" name="otp" class="input-field" placeholder="Enter verification code" required>
                    <button type="button" class="btn-send-otp" onclick="requestOTP()">Send</button>
                </div>

                <div class="input-group">
                    <i class="fa-solid fa-lock input-icon"></i>
                    <input type="password" id="forgotNewPwd" name="new_password" class="input-field" placeholder="Enter 8 to 32 characters" minlength="8" maxlength="32" required>
                    <i class="fa-solid fa-eye-slash eye-icon pwd-toggle" data-target="forgotNewPwd"></i>
                </div>

                <div class="input-group">
                    <i class="fa-solid fa-lock input-icon"></i>
                    <input type="password" id="forgotConfirmPwd" name="confirm_password" class="input-field" placeholder="Re-enter password" required>
                    <i class="fa-solid fa-eye-slash eye-icon pwd-toggle" data-target="forgotConfirmPwd"></i>
                </div>

                <button type="submit" class="btn-main" style="margin-bottom: 0;">Confirm</button>
            </form>
        </div>

        <div class="modal-close-btn" id="closeForgotModal">
            <i class="fa-solid fa-xmark"></i>
        </div>
    </div>

    <script>
        // 0. PK Phone Number Validation (No leading zeros, max 10 digits)
        document.querySelectorAll('.pk-phone').forEach(input => {
            input.addEventListener('input', function(e) {
                // Strip all non-numeric characters immediately
                let value = this.value.replace(/\D/g, '');
                
                // If the user types '0' as the very first digit, remove it
                if (value.startsWith('0')) {
                    value = value.substring(1);
                }
                
                // Standard Pakistani number length is 10 digits after +92 (e.g. 300 1234567)
                if (value.length > 10) {
                    value = value.substring(0, 10);
                }
                
                // Update the input field with the cleaned value
                this.value = value;
            });
        });

        // 1. Dynamic Multi-Password Visibility Toggle
        document.querySelectorAll('.pwd-toggle').forEach(icon => {
            icon.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const targetInput = document.getElementById(targetId);
                
                if(targetInput.type === 'password') {
                    targetInput.type = 'text';
                    this.classList.remove('fa-eye-slash');
                    this.classList.add('fa-eye');
                } else {
                    targetInput.type = 'password';
                    this.classList.remove('fa-eye');
                    this.classList.add('fa-eye-slash');
                }
            });
        });

        // 2. Fake Cloudflare Widget Animation
        window.addEventListener('load', () => {
            const spinner = document.getElementById('cfSpinner');
            const successIcon = document.getElementById('cfSuccess');
            const cfText = document.getElementById('cfText');

            setTimeout(() => {
                spinner.style.display = 'none';
                successIcon.style.display = 'block';
                cfText.innerText = 'Success!';
            }, 2500); 
        });

        // 3. Modal Open/Close Logic
        const forgotModal = document.getElementById('forgotModal');
        const openForgotBtn = document.getElementById('openForgotModal');
        const closeForgotBtn = document.getElementById('closeForgotModal');

        openForgotBtn.addEventListener('click', (e) => {
            e.preventDefault();
            forgotModal.classList.add('active');
        });

        closeForgotBtn.addEventListener('click', () => {
            forgotModal.classList.remove('active');
        });

        // 4. Backend-Ready Functions for Forgot Password
        function requestOTP() {
            const phone = document.querySelector('input[name="phone"]').value;
            if(!phone) {
                alert("Please enter a phone number first.");
                return;
            }
            alert("OTP Request Sent to +92 " + phone);
        }

        function submitForgotPassword(e) {
            e.preventDefault();
            // BACKEND TODO: Serialize form and Fetch/AJAX post to your backend endpoint
            const formData = new FormData(e.target);
            console.log("Submitting Forgot Password Form...", Object.fromEntries(formData));
            
            // Temporary frontend success toast for the modal
            const toast = document.createElement('div');
            toast.className = 'ios-toast toast-success';
            toast.innerHTML = '<i class="fa-solid fa-circle-check"></i><span>Password changed successfully!</span>';
            document.body.appendChild(toast);
            
            setTimeout(() => toast.classList.add('show'), 10);
            setTimeout(() => { 
                toast.classList.remove('show'); 
                setTimeout(() => toast.remove(), 500);
            }, 3000);
            
            forgotModal.classList.remove('active');
        }
    </script>

</body>
</html>