<?php
    require_once('source/session.php');
    require_once('source/error.php');
    require_once('source/dbconfig.php');
    require_once('source/function.php');
    
    if(isset($_POST['signin'])) {
        try {
            $reg_no = strip_tags($_POST['username']);
            $password = "3333"; // Default password
            $hashedPassword = md5(md5($salt . md5($password)) . $salt);
            
            $STH = $DBH->prepare("SELECT * FROM tbl_user WHERE email = :reg_no AND password = :password AND teacher = 'false'");
            $STH->bindParam(':reg_no', $reg_no);
            $STH->bindParam(':password', $hashedPassword);
            $STH->execute();
            $row = $STH->fetch(PDO::FETCH_ASSOC);
            
            if($STH->rowCount() == 1) {
                if($row['status'] == "Inactive") {
                    $_SESSION['msg'] = "inactive";
                    redirect('index.php?msg=inactive');
                }
                
                // Set ALL required session variables
                session_regenerate_id();
                $_SESSION['SESS_ID'] = $row['id'];
                $_SESSION['SESS_FULLNAME'] = $row['fullname'];
                $_SESSION['SESS_EMAIL'] = $row['email']; 
                $_SESSION['SESS_REGISTRATION_NO'] = $row['email']; // Explicitly set registration number
                $_SESSION['SESS_HASH_USER'] = $row['hash']; // Critical for main.php
                $_SESSION['SESS_ACCESS_LEVEL'] = $row['access_level'];
                $_SESSION['SESS_TOKEN'] = $token;
                
                redirect('main.php');
            } else {
                $_SESSION['msg'] = "failed";
                redirect('index.php');
            }
        } catch(PDOException $e) {
            file_put_contents('PDOErrors.txt', date('Y-m-d H:i:s')." - ".$e->getMessage()."\n", FILE_APPEND);
            $_SESSION['msg'] = "failed";
            redirect('index.php?msg=failed');
        }
    } else {
        redirect('index.php');
    }
?>