<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');

// Initialize message variable
$msg = '';

// Check if teacher is already logged in
if(isset($_SESSION['SESS_ID_TEACHER']) && !empty($_SESSION['SESS_ID_TEACHER'])){
    header("Location: main.php");
    exit();
}

// Process session messages
if(isset($_SESSION['msg'])) {
    switch($_SESSION['msg']) {
        case "activated":
            $msg = "Email Verification is Successful!<br>Sign in to Your Dashboard";
            break;
        case "duplicate":
            $msg = "Email already registered, please try another.";
            break;
        case "signup":
            $msg = "Account Registered successfully.";
            break;
        case "captcha":
            $msg = "Incorrect Captcha.";
            break;
        case "samp":
            $msg = "Samp request found, please try again.";
            break;
        case "failed":
            $msg = "Invalid Email Password Combination.";
            break;
        case "forget":
            $msg = "New password has been sent to your verified email.";
            break;
        case "signin":
            $msg = "Login successful!";
            break;
        case "access_denied":
            $msg = "Access denied. Teachers only.";
            break;
        case "teacher_login_success":
            $msg = "Teacher login successful!";
            break;
    }
    unset($_SESSION['msg']);
}

// Process GET messages
if(isset($_GET['msg'])) {
    switch($_GET['msg']) {
        case "inactive":
            $msg = "Are you a new member? Check your email to activate your account Now! For a blocked participant, write to support.";
            break;
        case "failed":
            $msg = "Invalid Email Password Combination.";
            break;
        case "logout":
            $msg = "You have been successfully logged out.";
            break;
        case "teacher_only":
            $msg = "This portal is for teachers only.";
            break;
    }
}

// Determine alert type based on message content
$alertType = 'info';
if(strpos($msg, 'successful') !== false || strpos($msg, 'Successful') !== false) {
    $alertType = 'success';
} else if(strpos($msg, 'Invalid') !== false || strpos($msg, 'incorrect') !== false || strpos($msg, 'failed') !== false) {
    $alertType = 'danger';
} else if(strpos($msg, 'registered') !== false) {
    $alertType = 'warning';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teacher Login | VERBUM DEI INT'L COLLEGE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-blue: #1976d2;
            --dark-blue: #0d47a1;
            --light-blue: #64b5f6;
            --accent-blue: #bbdefb;
            --bg-light: #e3f2fd;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            color: #333;
        }
        
        .login-container {
            max-width: 500px;
            margin: 0 auto;
            animation: fadeIn 0.5s ease-in-out;
        }
        
        .login-card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .login-card:hover {
            transform: translateY(-5px);
        }
        
        .card-header {
            background-color: var(--dark-blue);
            color: white;
            padding: 1.5rem;
            text-align: center;
            font-weight: 600;
            font-size: 1.25rem;
        }
        
        .card-body {
            padding: 2rem;
            background-color: white;
        }
        
        .form-control {
            height: 50px;
            border-radius: 8px;
            border: 1px solid #ddd;
            padding-left: 45px;
            transition: all 0.3s;
        }
        
        .form-control:focus {
            border-color: var(--light-blue);
            box-shadow: 0 0 0 0.2rem rgba(25, 118, 210, 0.25);
        }
        
        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-blue);
        }
        
        .btn-login {
            background-color: var(--primary-blue);
            border: none;
            color: white;
            padding: 12px 0;
            font-weight: 600;
            border-radius: 8px;
            transition: all 0.3s;
            width: 100%;
        }
        
        .btn-login:hover {
            background-color: var(--dark-blue);
        }
        
        .btn-login:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        
        .school-logo {
            width: 120px;
            height: auto;
            margin-bottom: 1.5rem;
            filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
        }
        
        .powered-by {
            color: white;
            text-align: center;
            margin-top: 2rem;
            font-size: 0.9rem;
        }
        
        .powered-by a {
            color: white;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .powered-by a:hover {
            color: var(--accent-blue);
        }
        
        .powered-by img {
            height: 30px;
            margin-left: 10px;
            vertical-align: middle;
        }
        
        .message-alert {
            margin-bottom: 1.5rem;
            border-radius: 8px;
            text-align: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .form-group {
            position: relative;
            margin-bottom: 1.5rem;
        }
        
        .debug-info {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            font-size: 14px;
            display: none;
        }
        
        .debug-toggle {
            color: var(--primary-blue);
            cursor: pointer;
            font-size: 0.9rem;
            text-align: center;
            margin-top: 15px;
        }
        
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        
        .status-active {
            background-color: #28a745;
        }
        
        .status-inactive {
            background-color: #dc3545;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid transparent;
            border-top: 2px solid currentColor;
            border-radius: 50%;
            animation: spin 0.75s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .session-info {
            background: #e9ecef;
            border-radius: 5px;
            padding: 10px;
            margin-top: 10px;
            font-size: 12px;
        }
        
        .teacher-badge {
            background: linear-gradient(45deg, #ff6b35, #f7931e);
            color: white;
            padding: 3px 8px;
            border-radius: 15px;
            font-size: 0.8rem;
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <div class="container login-container">
        <div class="text-center mb-4">
            <img src="https://portal.vda.com.ng/coll_admin/coll_logo.jpg" alt="VERBUM DEI INT'L COLLEGE" class="school-logo" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0iIzE5NzZkMiIvPjx0ZXh0IHg9IjYwIiB5PSI2NSIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjE0IiBmaWxsPSJ3aGl0ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSI+VkRJQzwvdGV4dD48L3N2Zz4='">
        </div>
        
        <div class="login-card">
            <div class="card-header">
                <i class="fas fa-chalkboard-teacher me-2"></i>TEACHER RESULT PORTAL 
                <div class="teacher-badge d-inline-block">Teachers Only</div>
            </div>
            
            <div class="card-body">
                <?php if(!empty($msg)): ?>
                    <div class="alert alert-<?php echo $alertType; ?> message-alert">
                        <i class="fas <?php echo $alertType == 'success' ? 'fa-check-circle' : ($alertType == 'danger' ? 'fa-exclamation-triangle' : 'fa-info-circle'); ?> me-2"></i> 
                        <?php echo $msg; ?>
                    </div>
                <?php else: ?>
                    <div class="alert alert-info message-alert">
                        <i class="fas fa-chalkboard-teacher me-2"></i> Teacher Login - Enter your credentials
                    </div>
                <?php endif; ?>
                
                <form id="loginForm" action="exe_signin.php" method="POST" autocomplete="off">
                    <div class="form-group">
                        <i class="fas fa-envelope input-icon"></i>
                        <input type="email" class="form-control" id="username" name="username" placeholder="Enter Teacher Email" required autofocus value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" required>
                    </div>
                    
                    <div class="form-group form-check mb-3">
                        <input type="checkbox" class="form-check-input" id="rememberMe" name="rememberMe" value="1">
                        <label class="form-check-label" for="rememberMe">Remember me</label>
                    </div>
                    
                    <!-- Hidden signin field that PHP expects -->
                    <input type="hidden" name="signin" value="1">
                    <input type="hidden" name="user_type" value="teacher">
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-login" id="loginButton">
                            <i class="fas fa-sign-in-alt me-2"></i> TEACHER SIGN IN
                        </button>
                    </div>
                </form>
                
                <div class="text-center mt-3">
                    <a href="forgot_password.php" class="text-decoration-none">
                        <i class="fas fa-key me-1"></i>Forgot Password?
                    </a>
                </div>
                
                <div class="debug-toggle" id="debugToggle">
                    <i class="fas fa-bug me-1"></i> Show Debug Info
                </div>
                
                <div class="debug-info" id="debugInfo">
                    <h5>Teacher Login Debug Information</h5>
                    <p>Session variables expected by main.php:</p>
                    <ul>
                        <li><code>SESS_ID_TEACHER</code> - Teacher ID from tbl_user</li>
                        <li><code>SESS_FULLNAME</code> - Teacher's full name</li>
                        <li><code>SESS_EMAIL</code> - Teacher's email</li>
                        <li><code>SESS_TEACHER</code> - Must be 'true'</li>
                    </ul>
                    
                    <div class="mt-3">
                        <h6>Session Status:</h6>
                        <p>
                            <span class="status-indicator <?php echo isset($_SESSION['SESS_ID_TEACHER']) ? 'status-active' : 'status-inactive'; ?>"></span> 
                            <?php echo isset($_SESSION['SESS_ID_TEACHER']) ? 'Teacher Authenticated (ID: ' . $_SESSION['SESS_ID_TEACHER'] . ')' : 'Not authenticated'; ?>
                        </p>
                    </div>
                    
                    <div class="session-info">
                        <strong>Current Session Data:</strong><br>
                        <?php 
                        echo "SESS_ID_TEACHER: " . (isset($_SESSION['SESS_ID_TEACHER']) ? $_SESSION['SESS_ID_TEACHER'] : 'Not set') . "<br>";
                        echo "SESS_EMAIL: " . (isset($_SESSION['SESS_EMAIL']) ? $_SESSION['SESS_EMAIL'] : 'Not set') . "<br>";
                        echo "SESS_TEACHER: " . (isset($_SESSION['SESS_TEACHER']) ? $_SESSION['SESS_TEACHER'] : 'Not set') . "<br>";
                        echo "SESS_FULLNAME: " . (isset($_SESSION['SESS_FULLNAME']) ? $_SESSION['SESS_FULLNAME'] : 'Not set');
                        ?>
                    </div>
                    
                    <div class="mt-3">
                        <button class="btn btn-sm btn-outline-primary me-2" id="testRedirect">Test Redirect to main.php</button>
                        <button class="btn btn-sm btn-outline-secondary" id="clearSession">Clear Session</button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="powered-by">
            <div class="mt-3">
                <a href="https://dataswift.com.ng" target="_blank">
                    <span>Proudly powered by</span>
                    <img src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjE1IiB5PSIzMCIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjE0IiBmaWxsPSIjZmZmIj5EYXRhU3dpZnQ8L3RleHQ+PC9zdmc+" alt="DataSwift">
                </a>
            </div>
            <div class="mt-2">
                <i class="fas fa-phone-alt me-2"></i> Teacher Support: +234 803 292 9756
            </div>
            <div class="mt-3 small">
                &copy; <?php echo date('Y'); ?> VERBUM DEI INT'L COLLEGE. All Rights Reserved.
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            const email = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const loginBtn = document.getElementById('loginButton');
            
            // Simple validation
            if (!email || !password) {
                showAlert('Please enter both email and password', 'danger');
                e.preventDefault();
                return;
            }
            
            // Email validation
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                showAlert('Please enter a valid email address', 'danger');
                e.preventDefault();
                return;
            }
            
            // Show loading state
            loginBtn.innerHTML = '<span class="loading-spinner me-2"></span> SIGNING IN...';
            loginBtn.disabled = true;
            
            // Allow form to submit naturally
        });
        
        function showAlert(message, type) {
            // Remove existing alerts
            const existingAlerts = document.querySelectorAll('.alert');
            existingAlerts.forEach(alert => alert.remove());
            
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show message-alert`;
            alertDiv.innerHTML = `
                <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'danger' ? 'fa-exclamation-triangle' : 'fa-info-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.querySelector('.card-body').insertBefore(alertDiv, document.querySelector('form'));
            
            // Auto-dismiss after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
        
        // Toggle debug info
        document.getElementById('debugToggle').addEventListener('click', function() {
            const debugInfo = document.getElementById('debugInfo');
            if (debugInfo.style.display === 'block') {
                debugInfo.style.display = 'none';
                this.innerHTML = '<i class="fas fa-bug me-1"></i> Show Debug Info';
            } else {
                debugInfo.style.display = 'block';
                this.innerHTML = '<i class="fas fa-bug me-1"></i> Hide Debug Info';
            }
        });
        
        // Test redirect
        document.getElementById('testRedirect').addEventListener('click', function() {
            showAlert('Testing redirect to main.php...', 'info');
            setTimeout(() => {
                window.location.href = 'main.php';
            }, 1000);
        });
        
        // Clear session
        document.getElementById('clearSession').addEventListener('click', function() {
            fetch('clearsession.php')
                .then(response => response.text())
                .then(data => {
                    showAlert('Session cleared. Refreshing page...', 'info');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                })
                .catch(error => {
                    showAlert('Error clearing session', 'danger');
                });
        });
        
        // Auto-focus on email field
        document.getElementById('username').focus();
        
        // Check if there's a message in URL parameters
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('msg')) {
            const msg = urlParams.get('msg');
            if (msg === 'teacher_login_success') {
                showAlert('Teacher login successful! Redirecting...', 'success');
            }
        }
    </script>
</body>
</html>