<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session first
//session_start();

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

// Create log directory if it doesn't exist
if (!is_dir('logs')) {
    mkdir('logs', 0755, true);
}

// Enhanced logging function
function logMessage($message, $level = 'INFO') {
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[$timestamp] [$level] $message\n";
    file_put_contents('logs/teacher_login_debug.log', $logEntry, FILE_APPEND);
    
    // Also log to browser console if possible
    if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
        error_log($logEntry);
    }
}

logMessage("=== TEACHER LOGIN ATTEMPT STARTED ===");
logMessage("Server: " . $_SERVER['SERVER_NAME']);
logMessage("PHP Version: " . PHP_VERSION);
logMessage("Session ID: " . session_id());

// Check if form was submitted
if(isset($_POST['signin'])) {
    logMessage("Signin POST detected");
    
    try {
        // Validate and sanitize inputs
        $email = filter_var(trim($_POST['username']), FILTER_SANITIZE_EMAIL);
        $pass = trim($_POST['password']);
        
        logMessage("Input received - Email: $email, Password Length: " . strlen($pass));
        
        // Validate email format
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            logMessage("Invalid email format: $email", 'ERROR');
            $_SESSION['msg'] = "failed";
            header("Location: index.php");
            exit();
        }
        
        // Check if credentials are not empty
        if (empty($email) || empty($pass)) {
            logMessage("Empty email or password", 'ERROR');
            $_SESSION['msg'] = "failed";
            header("Location: index.php");
            exit();
        }
        
        // Calculate password hash
        $password = md5(md5($salt . md5($pass)) . $salt);
        logMessage("Password hash calculated");
        
        // Prepare and execute query - Only check teacher accounts
        $STH = $DBH->prepare("SELECT * FROM tbl_user WHERE email = :email AND teacher = 'true'");
        $STH->bindParam(':email', $email);
        $STH->execute();
        
        $rowCount = $STH->rowCount();
        logMessage("Database query executed - Teacher rows found: $rowCount");
        
        if($rowCount == 1) {
            $row = $STH->fetch(PDO::FETCH_ASSOC);
            logMessage("Teacher found: " . $row['email'] . ", Name: " . $row['fullname'] . ", Status: " . $row['status']);
            
            // Verify password
            if($password === $row['password']) {
                logMessage("Password verification successful");
                
                // Check user status
                if($row['status'] == "Inactive") {
                    logMessage("Teacher account is inactive", 'WARNING');
                    header("Location: index.php?msg=inactive");
                    exit();
                }
                
                // Verify this is actually a teacher
                $isTeacher = ($row['teacher'] == true || $row['teacher'] == 1 || $row['teacher'] == 'true');
                logMessage("Teacher status confirmed: " . ($isTeacher ? 'YES' : 'NO'));
                
                if(!$isTeacher) {
                    logMessage("Access denied - User is not a teacher", 'WARNING');
                    $_SESSION['msg'] = "access_denied";
                    header("Location: index.php");
                    exit();
                }
                
                // Check access level - Allow both "User" and "Teacher" access levels
                $accessLevel = $row['access_level'];
                logMessage("Access level: $accessLevel");
                
                if($accessLevel == "User" || $accessLevel == "Teacher" || $accessLevel == "Admin") {
                    // Regenerate session ID for security
                    session_regenerate_id(true);
                    logMessage("Session regenerated");
                    
                    // Clear any existing session data
                    $_SESSION = array();
                    
                    // Set teacher-specific session variables (as expected by main.php)
                    $_SESSION['SESS_ID_TEACHER'] = $row['id'];  // This is the key session variable main.php checks
                    $_SESSION['SESS_ID'] = $row['id'];
                    $_SESSION['SESS_PROFILE_PIC'] = $row['profile_pic'];
                    $_SESSION['SESS_FULLNAME'] = $row['fullname'];
                    $_SESSION['SESS_EMAIL'] = $row['email'];
                    $_SESSION['SESS_PASSWORD'] = $row['password'];
                    $_SESSION['SESS_PHONE'] = $row['phone'];
                    $_SESSION['SESS_COUNTRY'] = $row['country'];
                    $_SESSION['SESS_REGISTRATION_DATE'] = $row['registration_date'];
                    $_SESSION['SESS_ACCESS_LEVEL'] = "Teacher"; // Force to Teacher for dashboard
                    $_SESSION['SESS_HASH'] = $row['hash'];
                    $_SESSION['SESS_EMAIL_VERIFIED'] = $row['email_verified'];
                    $_SESSION['SESS_STATUS'] = $row['status'];
                    $_SESSION['SESS_S_TYPE'] = $row['s_type'];
                    $_SESSION['SESS_TEACHER'] = 'true'; // Must be string 'true' for compatibility
                    $_SESSION['SESS_TOKEN'] = $token;
                    $_SESSION['SESS_LOGIN_TIME'] = time();
                    $_SESSION['SESS_USER_TYPE'] = 'teacher';
                    
                    // Set MD5 versions for compatibility
                    $_SESSION['SESS_ID_MD'] = md5($salt . $row['id']);
                    $_SESSION['SESS_FULLNAME_MD'] = md5($salt . $row['fullname']);
                    $_SESSION['SESS_EMAIL_MD'] = md5($salt . $row['email']);
                    $_SESSION['SESS_PASSWORD_MD'] = md5($salt . $row['password']);
                    
                    // Set a flag to indicate successful teacher login
                    $_SESSION['TEACHER_AUTHENTICATED'] = true;
                    
                    session_write_close();
                    
                    logMessage("Teacher session variables set successfully");
                    logMessage("Teacher authenticated: " . $row['fullname'] . " (" . $row['email'] . ")");
                    logMessage("Redirecting to main.php");
                    
                    // Set success message
                    $_SESSION['msg'] = "teacher_login_success";
                    
                    // Redirect to main.php
                    header("Location: main.php");
                    exit();
                    
                } else {
                    logMessage("Invalid access level for teacher: $accessLevel", 'ERROR');
                    $_SESSION['msg'] = "access_denied";
                    header("Location: index.php");
                    exit();
                }
                
            } else {
                logMessage("Password verification failed", 'ERROR');
                $_SESSION['msg'] = "failed";
                header("Location: index.php");
                exit();
            }
            
        } else {
            logMessage("No teacher found with email: $email", 'ERROR');
            
            // Check if email exists but user is not a teacher
            $checkUser = $DBH->prepare("SELECT * FROM tbl_user WHERE email = :email");
            $checkUser->bindParam(':email', $email);
            $checkUser->execute();
            
            if($checkUser->rowCount() == 1) {
                logMessage("Email exists but user is not a teacher", 'WARNING');
                $_SESSION['msg'] = "access_denied";
            } else {
                $_SESSION['msg'] = "failed";
            }
            
            header("Location: index.php");
            exit();
        }
        
    } catch(PDOException $e) {
        $errorMsg = "Database error: " . $e->getMessage();
        logMessage($errorMsg, 'ERROR');
        file_put_contents('logs/PDOErrors.log', date('Y-m-d H:i:s') . " - " . $e->getMessage() . "\n", FILE_APPEND);
        
        $_SESSION['msg'] = "failed";
        header("Location: index.php");
        exit();
        
    } catch(Exception $e) {
        $errorMsg = "General error: " . $e->getMessage();
        logMessage($errorMsg, 'ERROR');
        
        $_SESSION['msg'] = "failed";
        header("Location: index.php");
        exit();
    }
    
} else {
    logMessage("Invalid access - No signin POST data", 'ERROR');
    header("Location: index.php");
    exit();
}

logMessage("=== TEACHER LOGIN ATTEMPT COMPLETED ===\n");
?>