<?php
/**
 * Login Page - TutorKita System
 * Redesigned: Original Theme + Glassmorphism + Fullscreen Background
 */

require_once __DIR__ . '/db.php';

// ============================================
// DATABASE SETTINGS - Fetch portal settings
// ============================================
$portalLogo = '';
$portalFavicon = 'favicon.ico';
$pageTitle = 'Log Masuk - TutorKita';
$portalName = 'TutorKita';
$portalTagline = 'Platform Pembelajaran Terbaik';
$footerText = '© 2026 Hak Cipta Terpelihara';
$portalBackground = '';

// Default fallback background image URL (education-themed)
$FALLBACK_BACKGROUND_URL = 'https://images.unsplash.com/photo-1503676260728-1c00da094a0b?w=1920';

try {
    // Fetch settings from admin table
    $stmt = $pdo->query("SELECT portal_name, portal_tagline, portal_logo, portal_favicon, theme_color, portal_background, font_type, font_size, footer_text FROM admin LIMIT 1");
    $settings = $stmt->fetch();

    if ($settings) {
        $portalName = $settings['portal_name'] ?: $portalName;
        $portalTagline = $settings['portal_tagline'] ?: $portalTagline;
        $themeColor = $settings['theme_color'] ?: '#667eea';
        $portalBackground = $settings['portal_background'] ?: '';
        $fontType = $settings['font_type'] ?: 'Segoe UI';
        $fontSize = $settings['font_size'] ?: '14px';
        $portalLogo = $settings['portal_logo'] ?: '';
        $portalFavicon = $settings['portal_favicon'] ?: 'favicon.ico';
        $footerText = $settings['footer_text'] ?: $footerText;
    } else {
        $themeColor = '#667eea';
        $fontType = 'Segoe UI';
        $fontSize = '14px';
        $portalBackground = '';
    }
} catch (Exception $e) {
    $themeColor = '#667eea';
    $fontType = 'Segoe UI';
    $fontSize = '14px';
    $portalBackground = '';
}

// Use database background URL or fallback to default
$backgroundImageUrl = !empty($portalBackground) ? $portalBackground : $FALLBACK_BACKGROUND_URL;
?>
<!DOCTYPE html>
<html lang="ms">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Log Masuk ke TutorKita - Platform Pembelajaran Terbaik">
    <link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($portalFavicon); ?>">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <style>
        /* ============================================
           CSS VARIABLES
           ============================================ */
        :root {
            --primary-color:
                <?php echo $themeColor; ?>
            ;
            --secondary-color: #764ba2;
            --font-family:
                <?php echo $fontType; ?>
                , sans-serif;
            --font-size:
                <?php echo $fontSize; ?>
            ;

            /* Glassmorphism Colors */
            --glass-bg: rgba(255, 255, 255, 0.95);
            --glass-border: rgba(255, 255, 255, 0.3);
            --glass-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);

            /* Spacing */
            --spacing-xs: 0.25rem;
            --spacing-sm: 0.5rem;
            --spacing-md: 1rem;
            --spacing-lg: 1.5rem;
            --spacing-xl: 2rem;

            /* Border Radius */
            --radius-sm: 8px;
            --radius-md: 12px;
            --radius-lg: 16px;
            --radius-xl: 20px;

            /* Transitions */
            --transition-fast: 0.15s ease;
            --transition-normal: 0.3s ease;
            --transition-slow: 0.5s ease;
        }

        /* Reset */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* ============================================
           FULLSCREEN BACKGROUND WITH FALLBACK
           ============================================ */
        body {
            font-family: var(--font-family);
            font-size: var(--font-size);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            /* Multi-layer background for fallback:
               1. URL image (tries first)
               2. Gradient overlay (if image fails to load)
               3. Solid gradient (final fallback) */
            background:
                linear-gradient(135deg,
                    rgba(102, 126, 234, 0.85) 0%,
                    rgba(118, 75, 162, 0.85) 50%,
                    rgba(102, 126, 234, 0.85) 100%),
                url('<?php echo $backgroundImageUrl; ?>') no-repeat center center,
                linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);

            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            background-color: var(--primary-color);

            padding: 20px;
        }

        /* Overlay for better text readability */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.2);
            pointer-events: none;
            z-index: 0;
        }

        /* ============================================
           GLASSMORPHISM LOGIN CARD
           ============================================ */
        .login-container {
            position: relative;
            z-index: 1;
            width: auto;
            max-width: auto;

            /* Glassmorphism Effect */
            background: var(--glass-bg);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border: 1px solid var(--glass-border);
            border-radius: var(--radius-xl);
            box-shadow: var(--glass-shadow);

            /* Animation - Slide up effect */
            animation: slideUp var(--transition-slow) ease-out;
            overflow: hidden;
            margin-bottom: 20px;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* ============================================
           ORIGINAL THEME HEADER (KEPT)
           ============================================ */
        .login-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 40px 30px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        /* Decorative circle */
        .login-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -20%;
            width: 150px;
            height: 150px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .logo {
            font-size: 2rem;
            margin-bottom: 7px;
            display: inline-block;
            animation: bounce 2s infinite;
        }

        .logo img {
            max-width: 120px;
            height: auto;
            display: block;
            margin: 0 auto;
        }

        @keyframes bounce {

            0%,
            20%,
            50%,
            80%,
            100% {
                transform: translateY(0);
            }

            40% {
                transform: translateY(-10px);
            }

            60% {
                transform: translateY(-5px);
            }
        }

        .login-header h1 {
            font-size: 1.8rem;
            margin-bottom: 5px;
            position: relative;
            z-index: 1;
        }

        .login-header p {
            opacity: 0.9;
            font-size: 0.9rem;
            position: relative;
            z-index: 1;
        }

        .login-body {
            padding: 30px;
        }

        /* ============================================
           USER TYPE TABS (ORIGINAL STYLE)
           ============================================ */
        .user-type-tabs {
            display: flex;
            margin-bottom: 25px;
            background: rgba(0, 0, 0, 0.05);
            border-radius: var(--radius-md);
            padding: 5px;
        }

        .user-type-tab {
            flex: 1;
            padding: 12px;
            border: none;
            background: transparent;
            cursor: pointer;
            border-radius: var(--radius-sm);
            font-family: inherit;
            font-size: inherit;
            transition: all var(--transition-normal);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            color: #666;
        }

        .user-type-tab span {
            font-size: 1.3rem;
            transition: transform var(--transition-normal);
        }

        .user-type-tab.active {
            background: var(--primary-color);
            color: white;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .user-type-tab.active span {
            transform: scale(1.1);
        }

        .user-type-tab:not(.active):hover {
            background: rgba(0, 0, 0, 0.05);
        }

        /* ============================================
           FORM ELEMENTS (ORIGINAL + MICRO-INTERACTIONS)
           ============================================ */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
            transition: color var(--transition-fast);
        }

        .form-group input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: var(--radius-md);
            font-size: inherit;
            font-family: inherit;
            transition: all var(--transition-normal);
            background: rgba(255, 255, 255, 0.95);
        }

        .form-group input::placeholder {
            color: #9ca3af;
        }

        .form-group input:hover {
            border-color: #d1d5db;
        }

        .form-group input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.2);
            background: #ffffff;
        }

        .form-group input:focus+label,
        .form-group input:not(:placeholder-shown)+label {
            color: var(--primary-color);
        }

        /* ============================================
           PASSWORD FIELD WITH TOGGLE
           ============================================ */
        .password-wrapper {
            position: relative;
        }

        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #666;
            font-size: 1.2rem;
            padding: 5px;
            border-radius: var(--radius-sm);
            transition: all var(--transition-fast);
            background: transparent;
            border: none;
        }

        .password-toggle:hover {
            color: var(--primary-color);
            background: rgba(102, 126, 234, 0.1);
        }

        .password-toggle:focus {
            outline: 2px solid var(--primary-color);
            outline-offset: 2px;
        }

        /* ============================================
           LOGIN BUTTON (ORIGINAL + ANIMATIONS)
           ============================================ */
        .btn-login {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            border: none;
            border-radius: var(--radius-md);
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all var(--transition-normal);
            font-family: inherit;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }

        .btn-login:active {
            transform: translateY(0);
        }

        .btn-login:focus {
            outline: none;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.3);
        }

        .btn-login:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none;
        }

        /* Ripple Effect */
        .btn-login::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width 0.4s ease, height 0.4s ease, opacity 0.4s ease;
            opacity: 0;
        }

        .btn-login:active::after {
            width: 300px;
            height: 300px;
            opacity: 1;
            transition: width 0s, height 0s, opacity 0s;
        }

        /* ============================================
           ALERT MESSAGES
           ============================================ */
        .alert {
            padding: 15px;
            border-radius: var(--radius-md);
            margin-bottom: 20px;
            display: none;
            animation: shake 0.5s ease;
            font-size: 0.9rem;
        }

        @keyframes shake {

            0%,
            100% {
                transform: translateX(0);
            }

            20%,
            60% {
                transform: translateX(-5px);
            }

            40%,
            80% {
                transform: translateX(5px);
            }
        }

        .alert.error {
            background: rgba(220, 38, 38, 0.1);
            color: #dc2626;
            border: 1px solid rgba(220, 38, 38, 0.2);
        }

        .alert.success {
            background: rgba(22, 163, 74, 0.1);
            color: #16a34a;
            border: 1px solid rgba(22, 163, 74, 0.2);
        }

        /* ============================================
           REGISTER LINK
           ============================================ */
        .register-link {
            text-align: center;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 1px solid rgba(0, 0, 0, 0.08);
        }

        .register-link p {
            color: #666;
            font-size: 0.9rem;
        }

        .register-link a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 600;
            transition: all var(--transition-fast);
            position: relative;
        }

        .register-link a::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 0;
            height: 2px;
            background: var(--primary-color);
            transition: width var(--transition-normal);
        }

        .register-link a:hover::after {
            width: 100%;
        }

        .register-link a:hover {
            color: var(--secondary-color);
        }

        .register-link a:focus {
            outline: 2px solid var(--primary-color);
            outline-offset: 2px;
            border-radius: 2px;
        }

        /* ============================================
           LOADING SPINNER
           ============================================ */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
            vertical-align: middle;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* ============================================
           FOOTER
           ============================================ */
        .login-footer {
            text-align: center;
            color: rgba(255, 255, 255, 0.95);
            font-size: 0.85rem;
            text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
            font-weight: 500;
            margin-top: 10px;
            position: relative;
            z-index: 1;
            animation: fadeIn 1s ease 0.5s both;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        /* ============================================
           RESPONSIVE DESIGN
           ============================================ */
        @media (max-width: 480px) {
            .login-container {
                border-radius: 15px;
            }

            .login-header {
                padding: 30px 20px;
            }

            .logo {
                font-size: 3rem;
            }

            .login-header h1 {
                font-size: 1.5rem;
            }

            .login-body {
                padding: 20px;
            }

            .user-type-tab {
                padding: 10px;
                font-size: 0.85rem;
            }

            .user-type-tab span {
                font-size: 1.2rem;
            }

            .form-group input {
                padding: 12px;
            }

            .btn-login {
                padding: 12px;
            }
        }

        /* Tablet */
        @media (max-width: 768px) {
            .login-container {
                max-width: 100%;
                margin: 10px;
            }

            .login-header {
                padding: 30px;
            }

            .login-body {
                padding: 25px;
            }
        }
    </style>
</head>

<body>
    <!-- Login Card Container -->
    <div class="login-container">
        <!-- Header with Logo and Portal Info -->
        <div class="login-header">
            <div class="logo">
                <?php if (!empty($portalLogo)): ?>
                    <img src="<?php echo htmlspecialchars($portalLogo); ?>"
                        alt="Logo <?php echo htmlspecialchars($portalName); ?>"
                        onerror="this.style.display='none'; this.parentElement.innerHTML='📚';">
                <?php else: ?>
                    📚
                <?php endif; ?>
            </div>

            <h1><?php echo htmlspecialchars($portalName); ?></h1>
            <p><?php echo htmlspecialchars($portalTagline); ?></p>
        </div>

        <!-- Login Form Body -->
        <div class="login-body">
            <!-- Maintenance Mode Check -->
            <?php
            try {
                // Optimized maintenance check - single fast query
                // If column doesn't exist, query will fail silently
                $stmt = $pdo->query("SELECT 1 FROM admin WHERE id = 1 AND maintenance_mode = '1' LIMIT 1");
                $isMaintenance = $stmt->fetch();
                $showNotice = $isMaintenance || isset($_GET['maintenance']);

                if ($showNotice) {
                    echo '<div class="maintenance-notice" id="maintenanceNotice" style="background: linear-gradient(135deg, #ff6b6b, #ee5a52); color: white; padding: 20px; border-radius: 12px; margin-bottom: 20px; text-align: center; box-shadow: 0 4px 15px rgba(238, 90, 82, 0.3); animation: slideInDown 0.5s ease-out;">
                        <div style="font-size: 3rem; margin-bottom: 10px;">🔧</div>
                        <h3 style="margin: 0 0 10px 0; font-size: 1.2rem; font-weight: bold;">Sistem Sedang Diperbaharui</h3>
                        <p style="margin: 0; font-size: 0.9rem; opacity: 0.9;">Portal sedang dalam penyelenggaraan berat. Sila cuba lagi kemudian.</p>
                        <div style="margin-top: 15px; font-size: 0.8rem; opacity: 0.8;">Untuk pertanyaan, sila hubungi pentadbir sistem.</div>
                    </div>';
                }
            } catch (Exception $e) {
                // Skip if column doesn't exist yet
            }
            ?>

            <!-- Alert Message Display -->
            <div class="alert" id="alertMessage" style="display: none;"></div>

            <!-- User Type Selection Tabs -->
            <div class="user-type-tabs" role="tablist">
                <button class="user-type-tab active" data-type="student" onclick="selectUserType('student')" role="tab"
                    aria-selected="true">
                    <span>👨‍🎓</span> Pelajar
                </button>
                <button class="user-type-tab" data-type="teacher" onclick="selectUserType('teacher')" role="tab"
                    aria-selected="false">
                    <span>👨‍🏫</span> Guru
                </button>
                <button class="user-type-tab" data-type="admin" onclick="selectUserType('admin')" role="tab"
                    aria-selected="false">
                    <span>👨‍💻</span> Admin
                </button>
            </div>

            <!-- Login Form -->
            <form id="loginForm" onsubmit="handleLogin(event)">
                <!-- Hidden field for user type selection -->
                <input type="hidden" id="userType" name="user_type" value="student">

                <!-- Username Field -->
                <div class="form-group">
                    <input type="text" id="username" name="username" placeholder=" " autocomplete="username" required>
                    <label for="username">Nama Pengguna</label>
                </div>

                <!-- Password Field with Toggle -->
                <div class="form-group">
                    <div class="password-wrapper">
                        <input type="password" id="password" name="password" placeholder=" "
                            autocomplete="current-password" required>
                        <label for="password">Kata Laluan</label>
                        <button type="button" class="password-toggle" onclick="togglePassword()"
                            aria-label="Tunjukkan atau sembunyikan kata laluan">
                            👁️
                        </button>
                    </div>
                </div>

                <!-- Submit Button -->
                <button type="submit" class="btn-login" id="submitBtn">
                    Log Masuk
                </button>
            </form>

            <!-- Registration Link -->
            <div class="register-link">
                <p>Belum mempunyai akaun pelajar? <a href="register-student.php">Daftar Sekarang</a></p>
            </div>
        </div>
    </div>

    <!-- Footer Section -->
    <footer class="login-footer">
        <?php echo htmlspecialchars($footerText); ?>
    </footer>

    <!-- ============================================
         JAVASCRIPT FUNCTIONALITY
         ============================================ -->
    <script>
        // Current selected user type
        let currentUserType = 'student';

        /**
         * Select User Type Tab
         * Updates active state and hidden input value
         */
        function selectUserType(type) {
            currentUserType = type;
            document.getElementById('userType').value = type;

            // Update tab active states
            document.querySelectorAll('.user-type-tab').forEach(tab => {
                tab.classList.remove('active');
                tab.setAttribute('aria-selected', 'false');
            });

            // Activate selected tab
            const selectedTab = document.querySelector('[data-type="' + type + '"]');
            selectedTab.classList.add('active');
            selectedTab.setAttribute('aria-selected', 'true');
        }

        /**
         * Toggle Password Visibility
         * Switches between password and text input type
         */
        function togglePassword() {
            const passwordInput = document.getElementById('password');
            const toggleBtn = document.querySelector('.password-toggle');

            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleBtn.textContent = '🙈';
                toggleBtn.setAttribute('aria-label', 'Sembunyikan kata laluan');
            } else {
                passwordInput.type = 'password';
                toggleBtn.textContent = '👁️';
                toggleBtn.setAttribute('aria-label', 'Tunjukkan kata laluan');
            }
        }

        /**
         * Show Alert Message
         * Displays error or success messages with animation
         */
        function showAlert(message, type) {
            const alertEl = document.getElementById('alertMessage');
            alertEl.className = 'alert ' + type;
            alertEl.textContent = message;
            alertEl.style.display = 'block';

            // Auto-hide after 5 seconds
            setTimeout(() => {
                alertEl.style.display = 'none';
            }, 5000);
        }

        /**
         * Handle Login Form Submission
         * Sends credentials to API and redirects on success
         */
        async function handleLogin(event) {
            event.preventDefault();

            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.innerHTML;
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            // Quick validation
            if (!username || !password) {
                showAlert('Sila isi nama pengguna dan kata laluan.', 'error');
                return;
            }

            // Disable button and show loading state
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading-spinner"></span> Sedang Memproses...';

            // Prepare form data
            const formData = new FormData();
            formData.append('action', 'login');
            formData.append('username', username);
            formData.append('password', password);
            formData.append('user_type', currentUserType);

            try {
                // Send login request to API with timeout
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout

                const response = await fetch('api.php', {
                    method: 'POST',
                    body: formData,
                    signal: controller.signal
                });

                clearTimeout(timeoutId);

                if (!response.ok) {
                    throw new Error('Ralat respons pelayan');
                }

                const result = await response.json();
                console.log('API Result:', result);

                if (result.success) {
                    console.log('Login berjaya!', result.message);

                    // Paparkan mesej berjaya dan tukar butang
                    showAlert(result.message, 'success');
                    submitBtn.innerHTML = '✅ Log Masuk Berjaya!';
                    submitBtn.style.background = 'linear-gradient(135deg, #16a34a 0%, #15803d 100%)';

                    // Redirect selepas 1.5 saat - bagi masa untuk pengguna lihat mesej
                    setTimeout(() => {
                        console.log('Redirecting to dashboard...');
                        switch (currentUserType) {
                            case 'admin':
                                window.location.href = 'admin/index.php';
                                break;
                            case 'teacher':
                                window.location.href = 'teacher/index-v2.php';
                                break;
                            case 'student':
                                window.location.href = 'student/index.php';
                                break;
                        }
                    }, 1500); // 1.5 saat untuk pengguna lihat mesej berjaya
                } else {
                    console.log('Login gagal:', result.message);
                    // Show error message
                    showAlert(result.message, 'error');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            } catch (error) {
                console.error('Ralat:', error);
                // Handle network errors with specific messages
                if (error.name === 'AbortError') {
                    showAlert('Sambungan melambat. Cuba lagi.', 'error');
                } else {
                    showAlert('Ralat sambungan. Sila cuba lagi.', 'error');
                }
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        }

        /**
         * Check Existing Session
         * Redirects logged-in users to their dashboard
         */
        async function checkSession() {
            try {
                const response = await fetch('api.php?action=check_session');
                const result = await response.json();

                if (result.success && result.logged_in) {
                    // Redirect based on user type
                    switch (result.user.user_type) {
                        case 'admin':
                            window.location.href = 'admin/index.php';
                            break;
                        case 'teacher':
                            window.location.href = 'teacher/index-v2.php';
                            break;
                        case 'student':
                            window.location.href = 'student/index.php';
                            break;
                    }
                }
            } catch (error) {
                console.log('Session check failed');
            }
        }

        // Check session on page load
        checkSession();

        // Handle Enter key for form submission
        document.getElementById('password').addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('loginForm').dispatchEvent(new Event('submit'));
            }
        });
    </script>
</body>

</html>