<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'includes/functions.php';

if (isLoggedIn()) {
    $role = $_SESSION['role'];
    if ($role == 'admin') {
        header('Location: admin/dashboard.php');
    } elseif ($role == 'instructor') {
        header('Location: instructor/dashboard.php');
    } elseif ($role == 'student') {
        header('Location: student/dashboard.php');
    } else {
        header('Location: home.php');
    }
    exit;
}

$loginError = '';
$registerError = '';
$registerSuccess = '';
$activeTab = $_GET['tab'] ?? 'login';
$redirect = $_GET['redirect'] ?? '';

// Handle login
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (login($username, $password)) {
        $role = $_SESSION['role'];
        // Transfer session cart items to user account if any exist
        if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
            try {
                $db = getDB();
                $userId = $_SESSION['user_id'];

                // Add session cart items to user's cart_items table
                foreach ($_SESSION['cart'] as $courseId) {
                    // Check if course exists and is published
                    $stmt = $db->prepare("SELECT id FROM courses WHERE id = ? AND status = 'published'");
                    $stmt->execute([$courseId]);
                    if ($stmt->fetch()) {
                        // Check if already in user's cart
                        $stmt = $db->prepare("SELECT id FROM cart_items WHERE user_id = ? AND item_id = ? AND item_type = 'course'");
                        $stmt->execute([$userId, $courseId]);
                        if (!$stmt->fetch()) {
                            // Add to user's cart
                            $stmt = $db->prepare("INSERT INTO cart_items (user_id, item_type, item_id, created_at) VALUES (?, 'course', ?, NOW())");
                            $stmt->execute([$userId, $courseId]);
                        }
                    }
                }

                // Clear session cart after transfer
                unset($_SESSION['cart']);
            } catch (Exception $e) {
                // Log error but don't fail login
                error_log("Error transferring session cart to user account: " . $e->getMessage());
            }
        }

        if (isMobile()) {
            // For mobile, always redirect to dashboard
            if ($role == 'admin') {
                header('Location: admin/dashboard.php');
            } elseif ($role == 'instructor') {
                header('Location: instructor/dashboard.php');
            } elseif ($role == 'student') {
                header('Location: student/dashboard.php');
            } else {
                header('Location: home.php');
            }
            exit;
        } else {
            // For desktop, check redirect param
            if (!empty($redirect)) {
                header('Location: ' . urldecode($redirect));
                exit;
            }
            // Default redirects based on role
            if ($role == 'admin') {
                header('Location: admin/dashboard.php');
            } elseif ($role == 'instructor') {
                header('Location: instructor/dashboard.php');
            } elseif ($role == 'student') {
                header('Location: student/dashboard.php');
            } else {
                header('Location: home.php');
            }
            exit;
        }
    } else {
        $loginError = 'Invalid username or password';
        $activeTab = 'login';
    }
}

// Handle registration
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register'])) {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $role = 'student'; // Default to student role for homepage registrations

    // Validation
    if (empty($username) || empty($email) || empty($password)) {
        $registerError = 'All fields are required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $registerError = 'Please enter a valid email address';
    } elseif (strlen($password) < 8) {
        $registerError = 'Password must be at least 8 characters long';
    } elseif ($password !== $confirmPassword) {
        $registerError = 'Passwords do not match';
    } else {
        $result = registerUser($username, $email, $password, $role);
        if ($result['success']) {
            // Transfer session cart items to new user account if any exist
            if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
                try {
                    $db = getDB();
                    // Get the newly created user ID
                    $stmt = $db->prepare("SELECT id FROM users WHERE username = ? ORDER BY id DESC LIMIT 1");
                    $stmt->execute([$username]);
                    $user = $stmt->fetch();
                    $userId = $user['id'] ?? null;

                    if ($userId) {
                        // Add session cart items to user's cart_items table
                        foreach ($_SESSION['cart'] as $courseId) {
                            // Check if course exists and is published
                            $stmt = $db->prepare("SELECT id FROM courses WHERE id = ? AND status = 'published'");
                            $stmt->execute([$courseId]);
                            if ($stmt->fetch()) {
                                // Check if already in user's cart
                                $stmt = $db->prepare("SELECT id FROM cart_items WHERE user_id = ? AND item_id = ? AND item_type = 'course'");
                                $stmt->execute([$userId, $courseId]);
                                if (!$stmt->fetch()) {
                                    // Add to user's cart
                                    $stmt = $db->prepare("INSERT INTO cart_items (user_id, item_type, item_id, created_at) VALUES (?, 'course', ?, NOW())");
                                    $stmt->execute([$userId, $courseId]);
                                }
                            }
                        }

                        // Clear session cart after transfer
                        unset($_SESSION['cart']);
                    }
                } catch (Exception $e) {
                    // Log error but don't fail registration
                    error_log("Error transferring session cart to new user account: " . $e->getMessage());
                }
            }

            $registerSuccess = $result['message'];
            // After successful registration, redirect to login with preserved redirect parameter
            $redirectParam = $_GET['redirect'] ?? '';
            if (!empty($redirectParam)) {
                header('Location: login.php?tab=login&redirect=' . urlencode($redirectParam));
                exit;
            }
            $activeTab = 'login'; // Switch to login tab after successful registration
        } else {
            $registerError = $result['message'];
            $activeTab = 'register';
        }
    }
}

$page_title = 'Login & Register';
include 'includes/header.php';
?>

<section class="login-section">
    <div class="container">
        <div class="login-card" style="max-width: 500px;">
            <div class="login-header">
                <h1>Welcome to Mutalex Academy</h1>
                <p>Sign in to your account or create a new one</p>
            </div>

            <!-- Tab Navigation -->
            <div class="auth-tabs">
                <button type="button" class="tab-btn <?php echo $activeTab === 'login' ? 'active' : ''; ?>" onclick="switchTab('login')">
                    <i class="fas fa-sign-in-alt me-2"></i>Login
                </button>
                <button type="button" class="tab-btn <?php echo $activeTab === 'register' ? 'active' : ''; ?>" onclick="switchTab('register')">
                    <i class="fas fa-user-plus me-2"></i>Register
                </button>
            </div>

            <!-- Login Tab -->
            <div id="login-tab" class="auth-tab-content <?php echo $activeTab === 'login' ? 'active' : ''; ?>">
                <?php if ($loginError): ?>
                    <div class="alert alert-error">
                        <?php echo htmlspecialchars($loginError); ?>
                    </div>
                <?php endif; ?>

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

                <?php if (isset($_GET['expired'])): ?>
                    <div class="alert alert-error">
                        Your session has expired due to inactivity. Please log in again.
                    </div>
                <?php endif; ?>

                <form method="POST" class="login-form">
                    <input type="hidden" name="login" value="1">
                    <div class="form-group">
                        <label for="login-username">Username</label>
                        <input type="text" id="login-username" name="username" required>
                    </div>

                    <div class="form-group">
                        <label for="login-password">Password</label>
                        <input type="password" id="login-password" name="password" required>
                    </div>

                    <button type="submit" class="btn btn-primary btn-full">Login</button>
                </form>
            </div>

            <!-- Register Tab -->
            <div id="register-tab" class="auth-tab-content <?php echo $activeTab === 'register' ? 'active' : ''; ?>">
                <?php if ($registerError): ?>
                    <div class="alert alert-error">
                        <?php echo htmlspecialchars($registerError); ?>
                    </div>
                <?php endif; ?>

                <form method="POST" class="login-form">
                    <input type="hidden" name="register" value="1">
                    <div class="form-group">
                        <label for="reg-username">Username</label>
                        <input type="text" id="reg-username" name="username" required
                               value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
                    </div>

                    <div class="form-group">
                        <label for="reg-email">Email Address</label>
                        <input type="email" id="reg-email" name="email" required
                               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                    </div>

                    <input type="hidden" name="role" value="student">

                    <div class="form-group">
                        <label for="reg-password">Password</label>
                        <input type="password" id="reg-password" name="password" required minlength="8">
                    </div>

                    <div class="form-group">
                        <label for="reg-confirm-password">Confirm Password</label>
                        <input type="password" id="reg-confirm-password" name="confirm_password" required minlength="8">
                    </div>

                    <button type="submit" class="btn btn-primary btn-full">Create Account</button>
                </form>

                <div class="login-help">
                    <p>Already have an account? <a href="#" onclick="switchTab('login')">Login here</a></p>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
function switchTab(tabName) {
    // Update URL without page reload
    const url = new URL(window.location);
    url.searchParams.set('tab', tabName);
    window.history.pushState({}, '', url);

    // Hide all tabs
    document.querySelectorAll('.auth-tab-content').forEach(tab => {
        tab.classList.remove('active');
    });

    // Remove active class from all tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });

    // Show selected tab
    document.getElementById(tabName + '-tab').classList.add('active');

    // Add active class to clicked button
    event.target.classList.add('active');
}

// Set initial active tab based on URL parameter
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const activeTab = urlParams.get('tab') || 'login';
    switchTab(activeTab);
});
</script>

<style>
.auth-tabs {
    display: flex;
    margin-bottom: 2rem;
    border-bottom: 1px solid #e5e7eb;
}

.tab-btn {
    flex: 1;
    padding: 0.75rem 1rem;
    background: none;
    border: none;
    border-bottom: 2px solid transparent;
    font-weight: 600;
    color: #64748b;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.tab-btn:hover {
    color: #2563eb;
    background-color: #f8fafc;
}

.tab-btn.active {
    color: #2563eb;
    border-bottom-color: #2563eb;
    background-color: #f0f9ff;
}

.auth-tab-content {
    display: none;
}

.auth-tab-content.active {
    display: block;
}

.login-card {
    animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>

<?php include 'includes/footer.php'; ?>