<?php
// Ensure no output before session_start
if (ob_get_level()) { ob_end_clean(); }
ob_start();
session_start();
require_once 'config.php';
require_once 'app/classes/UserLoginTracker.php';
require_once 'app/classes/AccountStatusManager.php';
require_once 'app/classes/NotificationManager.php';

use App\classes\UserLoginTracker;

$error_message = '';
$success_message = '';

// Check if user is already logged in - redirect to appropriate dashboard
if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
    if (isset($conn)) {
        $stmt = $conn->prepare("SELECT id, role, is_store_owner FROM agents WHERE id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param("i", $_SESSION['user_id']);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $user = $result->fetch_assoc();
                $stmt->close();
                
                // Redirect based on role
                require_once 'app/classes/StoreManager.php';
                $storeManager = new StoreManager($conn);
                
                // Check if user owns a store
                $store = $storeManager->getStoreByOwnerId($user['id']);
                
                if ($store || ($user['role'] === 'store_owner' || $user['is_store_owner'] == 1)) {
                    // Store owner - redirect to store dashboard
                    header('Location: pages/store_dashboard.php');
                    exit();
                } else {
                    // Agent - redirect to agent dashboard
                    header('Location: user_index.php');
                    exit();
                }
            }
            $stmt->close();
        }
    }
}

// Check if redirected from registration
if (isset($_GET['registered']) && $_GET['registered'] == '1') {
    $success_message = "Account created successfully! Please sign in with your credentials.";
}

function columnExists(mysqli $conn, string $table, string $column): bool {
    $stmt = $conn->prepare("SHOW COLUMNS FROM $table LIKE ?");
    $stmt->bind_param("s", $column);
    $stmt->execute();
    $result = $stmt->get_result();
    $exists = $result && $result->num_rows > 0;
    $stmt->close();
    return $exists;
}

try {
    if (!columnExists($conn, 'agents', 'email')) {
        mysqli_query($conn, "ALTER TABLE agents ADD COLUMN email VARCHAR(191) NULL UNIQUE AFTER username");
    }
    if (!columnExists($conn, 'agents', 'password_hash')) {
        mysqli_query($conn, "ALTER TABLE agents ADD COLUMN password_hash VARCHAR(255) NULL AFTER email");
    }
} catch (Throwable $e) {}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? (string)$_POST['password'] : '';

    if ($email !== '' && $password !== '') {
        $stmt = $conn->prepare("SELECT id, username, role, password_hash, email FROM agents WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();

        if ($user && !empty($user['password_hash']) && password_verify($password, $user['password_hash'])) {
            // SECURITY: If another user is already logged in, log them out first
            // This prevents session confusion and ensures only one user per browser
            if (isset($_SESSION['user_id']) && $_SESSION['user_id'] != $user['id']) {
                $previousUserId = $_SESSION['user_id'];
                $previousUsername = $_SESSION['username'] ?? 'Unknown';
                
                // Log the previous user's logout
                try {
                    $loginTracker = new UserLoginTracker($conn);
                    $ipAddress = UserLoginTracker::getClientIP();
                    $userAgent = UserLoginTracker::getUserAgent();
                    
                    $loginTracker->logLogout(
                        $previousUserId, 
                        date('Y-m-d H:i:s', $_SESSION['login_time'] ?? time())
                    );
                } catch (Exception $e) {
                    error_log("Failed to log previous user logout: " . $e->getMessage());
                }
                
                // Destroy previous session completely
                session_destroy();
                session_start();
                
                // Log the account switch
                error_log("Account switch detected - Previous: $previousUsername (ID: $previousUserId), New: {$user['username']} (ID: {$user['id']})");
            }
            
            // SECURITY: Regenerate session ID to prevent session fixation attacks
            session_regenerate_id(true);
            
            // Check account status
            $accountManager = new AccountStatusManager($conn);
            if (!$accountManager->canUserLogin($user['id'])) {
                // Log failed login due to account status
                try {
                    $loginTracker = new UserLoginTracker($conn);
                    $ipAddress = UserLoginTracker::getClientIP();
                    $userAgent = UserLoginTracker::getUserAgent();
                    
                    $loginTracker->logLogin(
                        $user['id'], 
                        $user['username'], 
                        $user['role'], 
                        $ipAddress, 
                        $userAgent, 
                        'failed',
                        'Account is not active'
                    );
                } catch (Exception $e) {
                    // Log the error but don't break the login process
                    error_log("Failed to log inactive account login attempt: " . $e->getMessage());
                }
                
                $error_message = "Your account is currently inactive. Please contact support.";
            } else {
                // Log successful login
                try {
                    $loginTracker = new UserLoginTracker($conn);
                    $ipAddress = UserLoginTracker::getClientIP();
                    $userAgent = UserLoginTracker::getUserAgent();
                    
                    $loginTracker->logLogin(
                        $user['id'], 
                        $user['username'], 
                        $user['role'], 
                        $ipAddress, 
                        $userAgent, 
                        'success'
                    );
                } catch (Exception $e) {
                    // Log the error but don't break the login process
                    error_log("Failed to log successful login: " . $e->getMessage());
                }
                
                // Send email notification for successful login (non-blocking)
                try {
                    $notificationManager = new NotificationManager($conn);
                    $ipAddress = UserLoginTracker::getClientIP();
                    $userAgent = UserLoginTracker::getUserAgent();
                    $loginTime = date('Y-m-d H:i:s');
                    
                    // Detect browser and device from user agent
                    $browser = 'Unknown';
                    $device = 'Unknown';
                    
                    if (stripos($userAgent, 'Mobile') !== false || stripos($userAgent, 'Android') !== false || stripos($userAgent, 'iPhone') !== false) {
                        $device = 'Mobile';
                    } elseif (stripos($userAgent, 'Tablet') !== false || stripos($userAgent, 'iPad') !== false) {
                        $device = 'Tablet';
                    } else {
                        $device = 'Desktop';
                    }
                    
                    if (stripos($userAgent, 'Chrome') !== false) {
                        $browser = 'Chrome';
                    } elseif (stripos($userAgent, 'Firefox') !== false) {
                        $browser = 'Firefox';
                    } elseif (stripos($userAgent, 'Safari') !== false && stripos($userAgent, 'Chrome') === false) {
                        $browser = 'Safari';
                    } elseif (stripos($userAgent, 'Edge') !== false) {
                        $browser = 'Edge';
                    } elseif (stripos($userAgent, 'Opera') !== false) {
                        $browser = 'Opera';
                    }
                    
                    $notificationData = [
                        'username' => $user['username'],
                        'login_time' => $loginTime,
                        'ip_address' => $ipAddress,
                        'user_agent' => $userAgent,
                        'device' => $device,
                        'browser' => $browser,
                        'date' => $loginTime
                    ];
                    
                    // Try to send notification via template system first
                    $result = $notificationManager->sendNotification($user['id'], 'account_login', $notificationData);
                    
                    // If template doesn't exist or email failed, send directly
                    if (!$result['email'] && !empty($user['email'])) {
                        // Send email directly with login details
                        $emailSubject = "🔐 New Login Detected - D-Bundles Stores";
                        $emailBody = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; padding: 20px; border-radius: 8px 8px 0 0; }
        .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
        .info-box { background: white; border-left: 4px solid #3b82f6; padding: 15px; margin: 15px 0; border-radius: 4px; }
        .info-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #e5e7eb; }
        .info-label { font-weight: 600; color: #6b7280; }
        .info-value { color: #111827; }
        .warning { background: #fef3c7; border-left-color: #f59e0b; padding: 15px; margin: 15px 0; border-radius: 4px; }
        .footer { text-align: center; margin-top: 20px; color: #6b7280; font-size: 12px; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h2 style='margin: 0;'>🔐 New Login Detected</h2>
        </div>
        <div class='content'>
            <p>Hello <strong>{$user['username']}</strong>,</p>
            <p>We detected a new login to your D-Bundles Stores account.</p>
            
            <div class='info-box'>
                <div class='info-row'>
                    <span class='info-label'>Login Time:</span>
                    <span class='info-value'>{$loginTime}</span>
                </div>
                <div class='info-row'>
                    <span class='info-label'>IP Address:</span>
                    <span class='info-value'>{$ipAddress}</span>
                </div>
                <div class='info-row'>
                    <span class='info-label'>Device:</span>
                    <span class='info-value'>{$device}</span>
                </div>
                <div class='info-row'>
                    <span class='info-label'>Browser:</span>
                    <span class='info-value'>{$browser}</span>
                </div>
            </div>
            
            <div class='warning'>
                <strong>⚠ Security Notice:</strong><br>
                If you did not make this login, please change your password immediately and contact support.
            </div>
            
            <p>If this was you, you can safely ignore this email.</p>
            
            <div class='footer'>
                <p>This is an automated security notification from D-Bundles Stores.</p>
                <p>© " . date('Y') . " D-Bundles Stores. All rights reserved.</p>
            </div>
        </div>
    </div>
</body>
</html>";
                        
                        // Send email directly using public method
                        $notificationManager->sendEmail($user['email'], $emailSubject, $emailBody);
                    }
                } catch (Exception $e) {
                    // Log the error but don't break the login process
                    error_log("Failed to send login notification email: " . $e->getMessage());
                }
                
                // MULTI-LAYER SECURITY: Check if user owns a store (even if role is still 'agent')
                require_once 'app/classes/StoreManager.php';
                $storeManager = new StoreManager($conn);
                $store = $storeManager->getStoreByOwnerId($user['id']);
                
                // AUTO-FIX: If user owns a store but has wrong role, fix it
                if ($store && $user['role'] !== 'store_owner') {
                    error_log("Auto-fixing store owner role - User ID: {$user['id']}, Username: {$user['username']}");
                    $fixStmt = $conn->prepare("UPDATE agents SET role = 'store_owner', is_store_owner = 1, store_id = ? WHERE id = ?");
                    $fixStmt->bind_param("ii", $store['id'], $user['id']);
                    $fixStmt->execute();
                    $fixStmt->close();
                    
                    // Update user data
                    $user['role'] = 'store_owner';
                    $user['is_store_owner'] = 1;
                }
                
                // Create new session with user data
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['login_time'] = time();
                $_SESSION['session_token'] = bin2hex(random_bytes(32)); // Unique session token
                $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
                
                // MULTI-LAYER SECURITY: Redirect based on role with validation
                // Check if user owns a store (primary check - most reliable)
                if ($store) {
                    // User owns a store - they should be a store owner
                    // If role was just fixed above, verification should pass
                    // But if it still fails, we know they own a store so redirect anyway
                    $verification = $storeManager->verifyStoreOwner($user['id']);
                    
                    if ($verification['valid']) {
                        // Perfect - all checks pass
                        header('Location: pages/store_dashboard.php');
                        exit();
                    } else {
                        // Verification failed but user owns a store - this means role wasn't updated properly
                        // Force fix one more time
                        error_log("Store owner verification failed - User ID: {$user['id']}, Reason: " . $verification['reason'] . " - Force fixing");
                        $forceFixStmt = $conn->prepare("UPDATE agents SET role = 'store_owner', is_store_owner = 1, store_id = ? WHERE id = ?");
                        $forceFixStmt->bind_param("ii", $store['id'], $user['id']);
                        $forceFixStmt->execute();
                        $forceFixStmt->close();
                        
                        // Update session
                        $_SESSION['role'] = 'store_owner';
                        
                        // Since user owns a store, redirect to store dashboard (trust the store ownership)
                        header('Location: pages/store_dashboard.php');
                        exit();
                    }
                } elseif ($user['role'] === 'store_owner') {
                    // User has store_owner role but doesn't own a store - this is an error
                    error_log("User has store_owner role but doesn't own a store - User ID: {$user['id']}");
                    // Fix the role
                    $fixStmt = $conn->prepare("UPDATE agents SET role = 'agent', is_store_owner = 0 WHERE id = ?");
                    $fixStmt->bind_param("i", $user['id']);
                    $fixStmt->execute();
                    $fixStmt->close();
                    $_SESSION['role'] = 'agent';
                    header('Location: user_index.php');
                    exit();
                } else {
                    // Agent role - verify agent is legitimate
                    $agentVerification = $storeManager->verifyAgent($user['id']);
                    if (!$agentVerification['valid']) {
                        error_log("Invalid agent login - User ID: {$user['id']}, Reason: " . $agentVerification['reason']);
                    }
                    header('Location: user_index.php');
                    exit();
                }
            }
        } else {
            // Log failed login attempt
            try {
                $loginTracker = new UserLoginTracker($conn);
                $ipAddress = UserLoginTracker::getClientIP();
                $userAgent = UserLoginTracker::getUserAgent();
                
                $loginTracker->logLogin(
                    $user ? $user['id'] : null, 
                    $email, 
                    'unknown', 
                    $ipAddress, 
                    $userAgent, 
                    'failed',
                    'Invalid credentials'
                );
            } catch (Exception $e) {
                // Log the error but don't break the login process
                error_log("Failed to log login attempt: " . $e->getMessage());
            }
            
            $error_message = "Invalid email or password.";
        }
    } else {
        $error_message = "Please enter your email and password.";
    }
}

// Get contact configuration
require_once 'app/classes/ContactConfig.php';
$contactConfig = new ContactConfig($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Agent Login | D-Bundles Stores</title>
    <meta name="description" content="Sign in to your D-Bundles Stores agent account - secure, fast, and reliable data bundle management.">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #1e293b 0%, #334155 50%, #475569 100%);
        }
        
        .logo-gradient {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
        }
        
        .footer-link {
            transition: all 0.3s ease;
            position: relative;
        }
        
        .footer-link:hover {
            color: #93c5fd;
            transform: translateX(5px);
        }
        
        .social-icon {
            transition: all 0.3s ease;
        }
        
        .social-icon:hover {
            transform: translateY(-5px);
        }
        
        .contact-icon {
            transition: all 0.3s ease;
        }
        
        .contact-icon:hover {
            transform: scale(1.1);
        }
        
        .hours-item {
            transition: all 0.3s ease;
        }
        
        .hours-item:hover {
            background-color: rgba(255, 255, 255, 0.05);
            transform: translateX(5px);
        }
        
        .footer-divider {
            height: 1px;
            background: linear-gradient(90deg, transparent 0%, rgba(59, 130, 246, 0.5) 50%, transparent 100%);
        }
        
        .pulse-animation {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4); }
            70% { box-shadow: 0 0 0 10px rgba(59, 130, 246, 0); }
            100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); }
        }
    </style>
</head>

<body class="min-h-screen flex flex-col py-4">
    <!-- Main Content -->
    <div class="flex-1 flex items-center justify-center mt-20 px-4 py-4">
        <div class="w-full max-w-sm">
            <!-- Login Card -->
            <div class="bg-gray-800 rounded-lg p-6 shadow-2xl border border-gray-700">
                <!-- Header -->
                <div class="text-center mb-6">
                    <div class="w-12 h-12 bg-blue-600 rounded-full flex items-center justify-center mx-auto mb-3">
                        <i class="fas fa-user text-white text-lg"></i>
                    </div>
                    <h2 class="text-xl font-bold text-white">Login</h2>
                </div>

                <!-- Success Message -->
                <?php if ($success_message): ?>
                <div class="bg-green-900 border border-green-700 text-green-300 px-3 py-2 rounded mb-4 text-sm">
                    <i class="fas fa-check-circle mr-2"></i>
                    <?= htmlspecialchars($success_message) ?>
                </div>
                <?php endif; ?>

                <!-- Error Message -->
                <?php if ($error_message): ?>
                <div class="bg-red-900 border border-red-700 text-red-300 px-3 py-2 rounded mb-4 text-sm">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    <?= htmlspecialchars($error_message) ?>
                </div>
                <?php endif; ?>

                <!-- Login Form -->
                <form method="POST" class="space-y-4" id="loginForm">
                    <div>
                        <input
                            type="email"
                            id="email"
                            name="email"
                            required
                            class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-400"
                            placeholder="Email"
                            value="<?= htmlspecialchars($email ?? '') ?>"
                            autocomplete="username"
                        >
                    </div>

                    <div class="relative">
                        <input
                            type="password"
                            id="password"
                            name="password"
                            required
                            class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 pr-10 placeholder-gray-400"
                            placeholder="Password"
                            autocomplete="current-password"
                        >
                        <button type="button" onclick="togglePassword()" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white">
                            <i class="fas fa-eye text-sm" id="toggleIcon"></i>
                        </button>
                    </div>

                    <button
                        type="submit"
                        name="login"
                        class="w-full bg-blue-600 text-white py-3 rounded-lg font-medium hover:bg-blue-700 transition-colors text-sm"
                    >
                        Sign In
                    </button>
                </form>
            </div>
        </div>
    </div>


  
    <script>
        function togglePassword() {
            const passwordField = document.getElementById('password');
            const toggleIcon = document.getElementById('toggleIcon');
            
            if (passwordField.type === 'password') {
                passwordField.type = 'text';
                toggleIcon.classList.remove('fa-eye');
                toggleIcon.classList.add('fa-eye-slash');
            } else {
                passwordField.type = 'password';
                toggleIcon.classList.remove('fa-eye-slash');
                toggleIcon.classList.add('fa-eye');
            }
        }
    </script>
</body>
</html>