<?php
// =============================================
// AUTH LOGIN PAGE - auth.globalkeystore.site
// =============================================

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Path to includes
$manage_includes = dirname(__DIR__) . '/manage/includes/';

require_once $manage_includes . 'config.php';
require_once $manage_includes . 'database.php';
require_once $manage_includes . 'functions.php';
require_once $manage_includes . 'auth.php';
require_once $manage_includes . 'mail.php';

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$auth = new Auth($pdo);
$error = '';
$success = '';

// Get site settings
$siteLogo = getSetting('site_logo') ?: '';
$siteName = getSetting('site_name') ?: 'Global Key Store';

// Function to get user IP address
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

// Create banned_ips table if not exists
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS `banned_ips` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `ip_address` varchar(45) NOT NULL,
            `reason` text DEFAULT NULL,
            `banned_by` int(11) DEFAULT NULL,
            `created_at` timestamp NULL DEFAULT current_timestamp(),
            PRIMARY KEY (`id`),
            UNIQUE KEY `ip_address` (`ip_address`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
    ");
} catch (PDOException $e) {
    error_log("Error creating banned_ips table: " . $e->getMessage());
}

// Add ip_address column to users table if not exists
try {
    $stmt = $pdo->query("SHOW COLUMNS FROM users LIKE 'ip_address'");
    if ($stmt->rowCount() == 0) {
        $pdo->exec("ALTER TABLE users ADD COLUMN ip_address VARCHAR(45) DEFAULT NULL");
    }
} catch (PDOException $e) {
    error_log("Error adding ip_address column to users: " . $e->getMessage());
}

// Add ip_address column to admins table if not exists
try {
    $stmt = $pdo->query("SHOW COLUMNS FROM admins LIKE 'ip_address'");
    if ($stmt->rowCount() == 0) {
        $pdo->exec("ALTER TABLE admins ADD COLUMN ip_address VARCHAR(45) DEFAULT NULL");
    }
} catch (PDOException $e) {
    error_log("Error adding ip_address column to admins: " . $e->getMessage());
}

// Check if IP is banned
function isIPBanned($pdo, $ip) {
    $stmt = $pdo->prepare("SELECT id, reason FROM banned_ips WHERE ip_address = ?");
    $stmt->execute([$ip]);
    return $stmt->fetch();
}

// Theme handling
$theme = $_COOKIE['theme'] ?? 'light';
if (isset($_GET['toggle_theme'])) {
    $theme = ($theme === 'dark') ? 'light' : 'dark';
    setcookie('theme', $theme, time() + 86400 * 365, '/');
    header('Location: ' . str_replace('&toggle_theme=1', '', $_SERVER['REQUEST_URI']));
    exit;
}

// ===== FORGOT PASSWORD HANDLERS =====

// Handle Forgot Password Request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['forgot_password'])) {
    $email_or_username = trim($_POST['email_or_username'] ?? '');
    
    if (empty($email_or_username)) {
        $error = 'Please enter your username or email!';
    } else {
        $stmt = $pdo->prepare("SELECT id, email, fullname, username FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$email_or_username, $email_or_username]);
        $user = $stmt->fetch();
        
        if ($user) {
            $reset_code = sprintf("%06d", rand(100000, 999999));
            $expires = date('Y-m-d H:i:s', strtotime('+15 minutes'));
            
            $stmt = $pdo->prepare("DELETE FROM password_resets WHERE user_id = ?");
            $stmt->execute([$user['id']]);
            
            $stmt = $pdo->prepare("INSERT INTO password_resets (user_id, code, expires_at) VALUES (?, ?, ?)");
            $stmt->execute([$user['id'], $reset_code, $expires]);
            
            $mailer = new Mailer();
            $emailSent = $mailer->sendPasswordReset($user['email'], $user['fullname'], $reset_code);
            
            if ($emailSent) {
                $_SESSION['reset_user_id'] = $user['id'];
                $_SESSION['reset_email'] = $user['email'];
                $success = 'A 6-digit verification code has been sent to your email.';
            } else {
                $error = 'Failed to send email. Please try again or contact support.';
            }
        } else {
            $error = 'No account found with that username or email!';
        }
    }
}

// Handle Verify Reset Code
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['verify_code'])) {
    $code = trim($_POST['code'] ?? '');
    
    if (empty($code) || strlen($code) != 6) {
        $error = 'Please enter a valid 6-digit code!';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM password_resets WHERE user_id = ? AND code = ? AND expires_at > NOW() ORDER BY id DESC LIMIT 1");
        $stmt->execute([$_SESSION['reset_user_id'], $code]);
        $reset = $stmt->fetch();
        
        if ($reset) {
            $_SESSION['code_verified'] = true;
            $success = 'Code verified! Please enter your new password.';
        } else {
            $error = 'Invalid or expired verification code!';
        }
    }
}

// Handle Reset Password
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['reset_password'])) {
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (strlen($new_password) < 6) {
        $error = 'Password must be at least 6 characters long!';
    } elseif ($new_password !== $confirm_password) {
        $error = 'Passwords do not match!';
    } else {
        $hashed = password_hash($new_password, PASSWORD_DEFAULT);
        
        $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
        $stmt->execute([$hashed, $_SESSION['reset_user_id']]);
        
        $stmt = $pdo->prepare("DELETE FROM password_resets WHERE user_id = ?");
        $stmt->execute([$_SESSION['reset_user_id']]);
        
        unset($_SESSION['reset_user_id']);
        unset($_SESSION['reset_email']);
        unset($_SESSION['code_verified']);
        
        $success = 'Password reset successfully! You can now login with your new password.';
    }
}

// ===== LOGIN HANDLER WITH IP CHECK =====
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
    try {
        if (!isset($_POST['verified']) || $_POST['verified'] != 'true') {
            $error = 'Please complete the human verification!';
        } else {
            $username = $_POST['username'];
            $password = $_POST['password'];
            $userIP = getUserIP();
            
            $bannedIP = isIPBanned($pdo, $userIP);
            if ($bannedIP) {
                $error = 'Your IP address has been banned. Reason: ' . ($bannedIP['reason'] ?: 'No reason provided');
            } else {
                // Try user login first
                $result = $auth->login($username, $password, 'user');
                
                if ($result === 'banned') {
                    $error = 'Your account has been banned. Please contact support for assistance.';
                } elseif ($result === true) {
                    // USER LOGIN SUCCESSFUL
                    $userId = $_SESSION['user_id'];
                    
                    // Update user's IP address
                    $stmt = $pdo->prepare("UPDATE users SET ip_address = ? WHERE id = ? AND (ip_address IS NULL OR ip_address = '')");
                    $stmt->execute([$userIP, $userId]);
                    
                    $stmt = $pdo->prepare("SELECT verified, email, fullname FROM users WHERE id = ?");
                    $stmt->execute([$userId]);
                    $user = $stmt->fetch();
                    
                    if ($user && $user['verified'] == 0) {
                        $code = generateVerificationCode();
                        $expires = date('Y-m-d H:i:s', strtotime('+15 minutes'));
                        
                        $stmt = $pdo->prepare("DELETE FROM verification_codes WHERE user_id = ?");
                        $stmt->execute([$userId]);
                        
                        $stmt = $pdo->prepare("INSERT INTO verification_codes (user_id, code, expires_at) VALUES (?, ?, ?)");
                        $stmt->execute([$userId, $code, $expires]);
                        
                        $mailer = new Mailer();
                        $mailer->sendVerification($user['email'], $user['fullname'], $code);
                        
                        header('Location: verify.php');
                        exit();
                    }
                    
                    $_SESSION['verified'] = true;
                    $_SESSION['login_ip'] = $userIP;
                    
                    // Check if there's a redirect URL stored
                    $redirect = $_SESSION['redirect_after_login'] ?? USER_URL . '/dashboard.php';
                    unset($_SESSION['redirect_after_login']);
                    
                    // Clear any output buffers
                    while (ob_get_level()) {
                        ob_end_clean();
                    }
                    
                    // Redirect to user dashboard
                    header('Location: ' . $redirect);
                    exit();
                    
                } elseif ($auth->login($username, $password, 'admin') === true) {
                    // ADMIN LOGIN SUCCESSFUL
                    $adminId = $_SESSION['admin_id'];
                    
                    $stmt = $pdo->prepare("UPDATE admins SET ip_address = ? WHERE id = ? AND (ip_address IS NULL OR ip_address = '')");
                    $stmt->execute([$userIP, $adminId]);
                    
                    $_SESSION['verified'] = true;
                    $_SESSION['login_ip'] = $userIP;
                    
                    $redirect = $_SESSION['redirect_after_login'] ?? ADMIN_URL . '/dashboard.php';
                    unset($_SESSION['redirect_after_login']);
                    
                    // Clear any output buffers
                    while (ob_get_level()) {
                        ob_end_clean();
                    }
                    
                    // Redirect to admin dashboard
                    header('Location: ' . $redirect);
                    exit();
                } else {
                    $error = 'Invalid username or password!';
                }
            }
        }
    } catch (Exception $e) {
        $error = 'Login error: ' . $e->getMessage();
        error_log('Login error: ' . $e->getMessage());
    }
}

// Determine which form to show
$show_forgot = isset($_GET['forgot']) ? true : false;
$show_reset = isset($_SESSION['reset_user_id']) && !isset($_SESSION['code_verified']) ? true : false;
$show_new_password = isset($_SESSION['code_verified']) ? true : false;
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?php echo $theme; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Login — <?php echo $siteName; ?></title>
    <link rel="stylesheet" href="<?php echo ASSETS_URL; ?>/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        [data-theme="dark"] {
            --primary: #ff6b2b;
            --bg: #0d0e14;
            --surface: #1a1b25;
            --surface2: #20222e;
            --border: rgba(255,255,255,0.08);
            --text: #f0f1f8;
            --text-muted: #8b8fa8;
        }

        [data-theme="light"] {
            --primary: #ff6b2b;
            --bg: #f8fafc;
            --surface: #ffffff;
            --surface2: #f8fafc;
            --border: #e2e8f0;
            --text: #0f172a;
            --text-muted: #475569;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg);
            color: var(--text);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            max-width: 450px;
            width: 100%;
            margin: 20px;
        }

        .login-card {
            background: var(--surface);
            border-radius: 24px;
            padding: 40px;
            border: 1px solid var(--border);
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        }

        .logo {
            text-align: center;
            margin-bottom: 30px;
        }

        .logo img {
            max-height: 50px;
        }

        .logo h1 {
            font-size: 24px;
            margin-top: 10px;
            color: var(--primary);
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-muted);
        }

        input {
            width: 100%;
            padding: 12px 16px;
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 12px;
            color: var(--text);
            font-size: 14px;
        }

        input:focus {
            outline: none;
            border-color: var(--primary);
        }

        .btn-login {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, var(--primary), #e85a1a);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-login:hover {
            transform: translateY(-2px);
        }

        .error-message {
            background: rgba(239,68,68,0.1);
            border: 1px solid #ef4444;
            color: #ef4444;
            padding: 12px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .success-message {
            background: rgba(16,185,129,0.1);
            border: 1px solid #10b981;
            color: #10b981;
            padding: 12px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .verify-card {
            background: var(--surface2);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }

        .verify-card.verified {
            background: rgba(16,185,129,0.1);
            border: 1px solid #10b981;
        }

        .verify-circle {
            width: 50px;
            height: 50px;
            background: var(--surface);
            border: 2px solid var(--border);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            cursor: pointer;
        }

        .verify-circle.verifying {
            border-color: var(--primary);
            animation: pulse 1s infinite;
        }

        .verify-circle.verified {
            background: #10b981;
            border-color: #10b981;
            color: white;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.1); opacity: 0.7; }
        }

        .forgot-link {
            text-align: right;
            margin-bottom: 20px;
        }

        .forgot-link a {
            color: var(--primary);
            text-decoration: none;
            font-size: 13px;
        }

        .register-link {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid var(--border);
        }

        .register-link a {
            color: var(--primary);
            text-decoration: none;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="logo">
                <?php if ($siteLogo): ?>
                    <img src="<?php echo $siteLogo; ?>" alt="<?php echo $siteName; ?>">
                <?php else: ?>
                    <h1><?php echo $siteName; ?></h1>
                <?php endif; ?>
            </div>

            <?php if ($error): ?>
                <div class="error-message"><?php echo $error; ?></div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="success-message"><?php echo $success; ?></div>
            <?php endif; ?>

            <?php if ($show_new_password): ?>
                <!-- New Password Form -->
                <form method="POST">
                    <div class="form-group">
                        <label>New Password</label>
                        <input type="password" name="new_password" placeholder="Enter new password" minlength="6" required>
                    </div>
                    <div class="form-group">
                        <label>Confirm Password</label>
                        <input type="password" name="confirm_password" placeholder="Confirm new password" required>
                    </div>
                    <button type="submit" name="reset_password" class="btn-login">Reset Password</button>
                </form>

            <?php elseif ($show_reset): ?>
                <!-- Verify Code Form -->
                <form method="POST">
                    <div class="form-group">
                        <label>Verification Code</label>
                        <input type="text" name="code" placeholder="Enter 6-digit code" maxlength="6" required>
                    </div>
                    <button type="submit" name="verify_code" class="btn-login">Verify Code</button>
                </form>
                <div class="register-link">
                    <a href="login.php?forgot=1">Resend Code</a>
                </div>

            <?php elseif ($show_forgot): ?>
                <!-- Forgot Password Form -->
                <form method="POST">
                    <div class="form-group">
                        <label>Username or Email</label>
                        <input type="text" name="email_or_username" placeholder="Enter username or email" required>
                    </div>
                    <button type="submit" name="forgot_password" class="btn-login">Send Reset Code</button>
                </form>
                <div class="register-link">
                    <a href="login.php">Back to Login</a>
                </div>

            <?php else: ?>
                <!-- Login Form -->
                <form method="POST" id="loginForm">
                    <div class="form-group">
                        <label>Username or Email</label>
                        <input type="text" name="username" placeholder="Enter username or email" required>
                    </div>

                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" name="password" placeholder="Enter password" required>
                    </div>

                    <div class="forgot-link">
                        <a href="login.php?forgot=1">Forgot Password?</a>
                    </div>

                    <!-- Human Verification -->
                    <div class="verify-card" id="verifyCard">
                        <div class="verify-circle" id="verifyCircle" onclick="startVerification()">
                            <i class="fas fa-play"></i>
                        </div>
                        <div class="verify-text">Click to verify you're human</div>
                    </div>

                    <input type="hidden" name="verified" id="verifiedInput" value="false">
                    <input type="hidden" name="login" value="1">

                    <button type="submit" class="btn-login" id="loginBtn" disabled>
                        <i class="fas fa-sign-in-alt"></i> Login
                    </button>
                </form>

                <div class="register-link">
                    Don't have an account? <a href="signup.php">Create Account</a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        let verificationComplete = false;

        function startVerification() {
            if (verificationComplete) return;

            const circle = document.getElementById('verifyCircle');
            const card = document.getElementById('verifyCard');
            const loginBtn = document.getElementById('loginBtn');
            const verifiedInput = document.getElementById('verifiedInput');

            circle.classList.add('verifying');
            circle.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

            setTimeout(() => {
                circle.classList.remove('verifying');
                circle.classList.add('verified');
                circle.innerHTML = '<i class="fas fa-check"></i>';
                card.classList.add('verified');
                card.querySelector('.verify-text').innerHTML = '✓ Verified successfully!';
                
                verificationComplete = true;
                loginBtn.disabled = false;
                verifiedInput.value = 'true';
            }, 2000);
        }

        const loginForm = document.getElementById('loginForm');
        if (loginForm) {
            loginForm.addEventListener('submit', function(e) {
                if (!verificationComplete) {
                    e.preventDefault();
                    alert('Please complete the human verification first!');
                }
            });
        }
    </script>
</body>
</html>