<?php
require_once 'includes/init.php';

// Redirect if already logged in
if (isAuthenticated()) {
    redirect(APP_URL . '/chats.php');
}

$pageTitle = 'Login';
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'login') {
        $loginType = $_POST['login_type'] ?? 'password';
        
        if ($loginType === 'password') {
            $uniqueId = sanitizeInput($_POST['unique_id'] ?? '');
            $password = $_POST['password'] ?? '';
            
            if (empty($uniqueId) || empty($password)) {
                $error = 'Please enter both Unique ID and password.';
            } else {
                // Check rate limit
                if (!checkRateLimit($uniqueId)) {
                    $error = 'Too many login attempts. Please try again later.';
                } else {
                    $db = getDB();
                    $stmt = $db->prepare("SELECT id, unique_id, name, email, password_hash, status, is_admin, is_ghost_mode, profile_photo FROM users WHERE unique_id = ?");
                    $stmt->execute([$uniqueId]);
                    $user = $stmt->fetch();
                    
                    if ($user && password_verify($password, $user['password_hash'])) {
                        if ($user['status'] === 'approved') {
                            // Create session
                            $sessionToken = bin2hex(random_bytes(32));
                            $expiresAt = date('Y-m-d H:i:s', time() + SESSION_LIFETIME);
                            
                            $stmt = $db->prepare("INSERT INTO sessions (user_id, session_token, device_info, ip_address, expires_at) VALUES (?, ?, ?, ?, ?)");
                            $stmt->execute([
                                $user['id'],
                                $sessionToken,
                                $_SERVER['HTTP_USER_AGENT'] ?? '',
                                $_SERVER['REMOTE_ADDR'],
                                $expiresAt
                            ]);
                            
                            // Set session variables
                            $_SESSION['user_id'] = $user['id'];
                            $_SESSION['user_unique_id'] = $user['unique_id'];
                            $_SESSION['user_name'] = $user['name'];
                            $_SESSION['user_email'] = $user['email'];
                            $_SESSION['is_admin'] = $user['is_admin'];
                            $_SESSION['session_token'] = $sessionToken;
                            
                            // Update last seen
                            $stmt = $db->prepare("UPDATE users SET last_seen = NOW(), last_activity = NOW() WHERE id = ?");
                            $stmt->execute([$user['id']]);
                            
                            // Log activity
                            $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent) VALUES (?, 'login', 'Password login', ?, ?)");
                            $stmt->execute([$user['id'], $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'] ?? '']);
                            
                            if ($user['is_admin']) {
                                redirect(APP_URL . '/admin/dashboard.php');
                            } else {
                                redirect(APP_URL . '/chats.php');
                            }
                        } else if ($user['status'] === 'pending') {
                            $error = 'Your account is pending approval. Please wait for admin confirmation.';
                        } else {
                            $error = 'Your account has been blocked. Please contact support.';
                        }
                    } else {
                        $error = 'Invalid Unique ID or password.';
                    }
                }
            }
        } else if ($loginType === 'otp') {
            $email = sanitizeInput($_POST['email'] ?? '');
            
            if (empty($email)) {
                $error = 'Please enter your email address.';
            } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = 'Please enter a valid email address.';
            } else {
                $db = getDB();
                $stmt = $db->prepare("SELECT id, unique_id, name, email, status, is_admin, is_ghost_mode FROM users WHERE email = ?");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user) {
                    if ($user['status'] === 'approved') {
                        // Generate OTP
                        $otp = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
                        $expiresAt = date('Y-m-d H:i:s', time() + OTP_EXPIRY);
                        
                        // Store OTP
                        $stmt = $db->prepare("INSERT INTO otp_codes (user_id, otp_code, type, expires_at) VALUES (?, ?, 'login', ?)");
                        $stmt->execute([$user['id'], $otp, $expiresAt]);
                        
                        // In a production environment, send email via PHPMailer
                        // For now, we'll show it in the success message
                        $success = "OTP sent to your email. (Demo OTP: $otp)";
                        $_SESSION['otp_email'] = $email;
                        $_SESSION['otp_user_id'] = $user['id'];
                    } else if ($user['status'] === 'pending') {
                        $error = 'Your account is pending approval.';
                    } else {
                        $error = 'Your account has been blocked.';
                    }
                } else {
                    $error = 'No account found with this email.';
                }
            }
        } else if ($loginType === 'verify_otp') {
            $otp = sanitizeInput($_POST['otp'] ?? '');
            $email = $_SESSION['otp_email'] ?? '';
            $userId = $_SESSION['otp_user_id'] ?? 0;
            
            if (empty($otp) || empty($email)) {
                $error = 'Please enter the OTP.';
            } else {
                $db = getDB();
                $stmt = $db->prepare("SELECT oc.id, u.* FROM otp_codes oc 
                    JOIN users u ON oc.user_id = u.id 
                    WHERE oc.user_id = ? AND oc.otp_code = ? AND oc.type = 'login' 
                    AND oc.used = 0 AND oc.expires_at > NOW()");
                $stmt->execute([$userId, $otp]);
                $result = $stmt->fetch();
                
                if ($result) {
                    // Mark OTP as used
                    $stmt = $db->prepare("UPDATE otp_codes SET used = 1 WHERE id = ?");
                    $stmt->execute([$result['id']]);
                    
                    // Create session
                    $sessionToken = bin2hex(random_bytes(32));
                    $expiresAt = date('Y-m-d H:i:s', time() + SESSION_LIFETIME);
                    
                    $stmt = $db->prepare("INSERT INTO sessions (user_id, session_token, device_info, ip_address, expires_at) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $result['user_id'],
                        $sessionToken,
                        $_SERVER['HTTP_USER_AGENT'] ?? '',
                        $_SERVER['REMOTE_ADDR'],
                        $expiresAt
                    ]);
                    
                    // Set session variables
                    $_SESSION['user_id'] = $result['user_id'];
                    $_SESSION['user_unique_id'] = $result['unique_id'];
                    $_SESSION['user_name'] = $result['name'];
                    $_SESSION['user_email'] = $result['email'];
                    $_SESSION['is_admin'] = $result['is_admin'];
                    $_SESSION['session_token'] = $sessionToken;
                    
                    // Update last seen
                    $stmt = $db->prepare("UPDATE users SET last_seen = NOW(), last_activity = NOW() WHERE id = ?");
                    $stmt->execute([$result['user_id']]);
                    
                    // Log activity
                    $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent) VALUES (?, 'login', 'OTP login', ?, ?)");
                    $stmt->execute([$result['user_id'], $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'] ?? '']);
                    
                    unset($_SESSION['otp_email']);
                    unset($_SESSION['otp_user_id']);
                    
                    if ($result['is_admin']) {
                        redirect(APP_URL . '/admin/dashboard.php');
                    } else {
                        redirect(APP_URL . '/chats.php');
                    }
                } else {
                    $error = 'Invalid or expired OTP.';
                }
            }
        }
    }
}

include 'includes/header.php';
?>

<div class="relative flex min-h-screen w-full flex-col overflow-x-hidden bg-background-light dark:bg-background-dark">
    <!-- Top App Bar -->
    <div class="flex items-center bg-background-light dark:bg-background-dark p-4 pb-2 justify-between sticky top-0 z-10">
        <div class="text-slate-900 dark:text-slate-100 flex size-12 shrink-0 items-center cursor-pointer" onclick="history.back()">
            <span class="material-symbols-outlined" style="font-size: 24px;">arrow_back</span>
        </div>
        <h2 class="text-slate-900 dark:text-slate-100 text-lg font-bold leading-tight tracking-[-0.015em] flex-1 text-center pr-12"><?php echo APP_NAME; ?></h2>
    </div>

    <!-- Tab Navigation -->
    <div class="pb-3">
        <div class="flex border-b border-slate-200 dark:border-slate-800 px-4 justify-between">
            <a class="flex flex-col items-center justify-center border-b-[3px] border-transparent text-slate-500 dark:text-slate-400 pb-[13px] pt-4 flex-1" href="signup.php">
                <p class="text-sm font-bold leading-normal tracking-[0.015em]">Sign Up</p>
            </a>
            <a class="flex flex-col items-center justify-center border-b-[3px] border-primary text-primary pb-[13px] pt-4 flex-1" href="login.php">
                <p class="text-sm font-bold leading-normal tracking-[0.015em]">Log In</p>
            </a>
        </div>
    </div>

    <!-- Scrollable Content Area -->
    <div class="flex flex-col px-4 pt-5 pb-10 max-w-[480px] mx-auto w-full flex-1">
        <h2 class="text-slate-900 dark:text-slate-100 tracking-light text-[28px] font-bold leading-tight text-center pb-6">Welcome Back</h2>

        <?php if ($error): ?>
        <div class="bg-red-500/10 border border-red-500/20 text-red-500 px-4 py-3 rounded-xl mb-4 text-sm">
            <?php echo $error; ?>
        </div>
        <?php endif; ?>

        <?php if ($success): ?>
        <div class="bg-green-500/10 border border-green-500/20 text-green-500 px-4 py-3 rounded-xl mb-4 text-sm">
            <?php echo $success; ?>
        </div>
        <?php endif; ?>

        <!-- Login Options -->
        <div class="space-y-3 mb-6">
            <button onclick="showPasswordLogin()" class="flex h-14 w-full items-center justify-center gap-3 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 px-4 text-slate-900 dark:text-slate-100 transition-colors hover:bg-slate-50 dark:hover:bg-slate-800" id="password-login-btn">
                <span class="material-symbols-outlined text-primary" style="font-size: 22px;">pin</span>
                <span class="text-sm font-semibold">Login with Unique ID</span>
            </button>
            <button onclick="showOTPLogin()" class="flex h-14 w-full items-center justify-center gap-3 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 px-4 text-slate-900 dark:text-slate-100 transition-colors hover:bg-slate-50 dark:hover:bg-slate-800" id="otp-login-btn">
                <span class="material-symbols-outlined text-primary" style="font-size: 22px;">key</span>
                <span class="text-sm font-semibold">Email OTP Login</span>
            </button>
        </div>

        <!-- Password Login Form -->
        <form method="POST" action="" class="space-y-4" id="password-form" style="display: block;">
            <input type="hidden" name="action" value="login">
            <input type="hidden" name="login_type" value="password">
            
            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Unique ID</p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">fingerprint</span>
                    <input name="unique_id" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="Enter your unique ID" type="text" required/>
                </div>
            </label>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Password</p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">lock</span>
                    <input name="password" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-12 text-base font-normal" placeholder="••••••••" type="password" required/>
                    <span class="material-symbols-outlined absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 cursor-pointer" style="font-size: 20px;" onclick="togglePassword(this)">visibility_off</span>
                </div>
            </label>

            <div class="flex justify-between items-center">
                <label class="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" name="remember" class="w-4 h-4 rounded border-slate-300 text-primary focus:ring-primary"/>
                    <span class="text-sm text-slate-600 dark:text-slate-400">Remember me</span>
                </label>
                <a href="forgot-password.php" class="text-sm text-primary hover:underline">Forgot password?</a>
            </div>

            <button type="submit" class="mt-4 flex h-14 w-full items-center justify-center rounded-xl bg-primary px-4 text-base font-bold tracking-wide text-white transition-opacity active:opacity-90">
                Sign In
            </button>
        </form>

        <!-- OTP Login Form -->
        <form method="POST" action="" class="space-y-4" id="otp-form" style="display: none;">
            <input type="hidden" name="action" value="login">
            <input type="hidden" name="login_type" value="otp" id="otp-login-type">
            
            <div id="otp-step-1">
                <label class="flex flex-col w-full">
                    <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Email Address</p>
                    <div class="relative">
                        <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">mail</span>
                        <input name="email" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="name@example.com" type="email" required/>
                    </div>
                </label>

                <button type="submit" class="mt-4 flex h-14 w-full items-center justify-center rounded-xl bg-primary px-4 text-base font-bold tracking-wide text-white transition-opacity active:opacity-90">
                    Send OTP
                </button>
            </div>
        </form>

        <!-- OTP Verification Form (shown after OTP sent) -->
        <?php if (isset($_SESSION['otp_email'])): ?>
        <form method="POST" action="" class="space-y-4" id="verify-otp-form">
            <input type="hidden" name="action" value="login">
            <input type="hidden" name="login_type" value="verify_otp">
            
            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Enter OTP</p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">pin</span>
                    <input name="otp" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="6-digit code" type="text" maxlength="6" required/>
                </div>
                <p class="text-xs text-slate-500 dark:text-slate-400 mt-2">Enter the OTP sent to <?php echo htmlspecialchars($_SESSION['otp_email']); ?></p>
            </label>

            <button type="submit" class="mt-4 flex h-14 w-full items-center justify-center rounded-xl bg-primary px-4 text-base font-bold tracking-wide text-white transition-opacity active:opacity-90">
                Verify & Login
            </button>
        </form>
        <?php endif; ?>

        <!-- Security Footer -->
        <div class="mt-auto pt-10 flex flex-col items-center justify-center gap-2">
            <div class="flex items-center gap-2 text-slate-500 dark:text-slate-400">
                <span class="material-symbols-outlined" style="font-size: 16px;">verified_user</span>
                <p class="text-xs">End-to-end encrypted security</p>
            </div>
            <p class="text-xs text-slate-500 dark:text-slate-500 text-center px-6">
                Don't have an account? <a class="text-primary hover:underline font-medium" href="signup.php">Sign up</a>
            </p>
        </div>
    </div>
</div>

<script>
    function showPasswordLogin() {
        document.getElementById('password-form').style.display = 'block';
        document.getElementById('otp-form').style.display = 'none';
        var verifyForm = document.getElementById('verify-otp-form');
        if (verifyForm) verifyForm.style.display = 'none';
        document.getElementById('password-login-btn').classList.add('border-primary', 'bg-primary/5');
        document.getElementById('otp-login-btn').classList.remove('border-primary', 'bg-primary/5');
    }

    function showOTPLogin() {
        document.getElementById('password-form').style.display = 'none';
        document.getElementById('otp-form').style.display = 'block';
        var verifyForm = document.getElementById('verify-otp-form');
        if (verifyForm) verifyForm.style.display = 'none';
        document.getElementById('otp-login-btn').classList.add('border-primary', 'bg-primary/5');
        document.getElementById('password-login-btn').classList.remove('border-primary', 'bg-primary/5');
    }

    function togglePassword(icon) {
        const input = icon.previousElementSibling;
        if (input.type === 'password') {
            input.type = 'text';
            icon.textContent = 'visibility';
        } else {
            input.type = 'password';
            icon.textContent = 'visibility_off';
        }
    }

    // Show password login by default if no OTP session
    <?php if (!isset($_SESSION['otp_email'])): ?>
    // Form is already visible by default
    <?php endif; ?>
</script>

<?php
$hideFooter = true;
include 'includes/footer.php';
?>
