<?php
    require_once('source/session.php');
    require_once('source/error.php');
    require_once('source/dbconfig.php');
    require_once('source/function.php');
    require_once('source/restrict_user.php');
    
    if(isset($_POST['check'])) {
        try {
            // Sanitize and validate input
            $st_pin = strip_tags($_POST['pin']);
            $st_class = strip_tags($_POST['mclass']);
            $st_reg = strip_tags($_POST['registration_no']);
            $st_year = strip_tags($_POST['year']);
            $st_term = strip_tags($_POST['term']);
            
            // Validate PIN exists
            $STH = $DBH->prepare("SELECT count(*) FROM tbl_pin WHERE pin = ?");
            $result = $STH->execute(array($st_pin));
            $count_pin = $STH->fetchColumn();
            
            if($count_pin > 0) {  
                // Get PIN details
                $rows1 = sql($DBH, "SELECT * FROM tbl_pin WHERE pin = ?", array($st_pin), "rows");                            
                foreach($rows1 as $row1) {    
                    $st_reg_no = $row1['reg_no'];
                    $st_thisclass = $row1['class'];
                    $st_thisterm = $row1['term'];
                    $st_thisyear = $row1['year'];
                }
                
                // PIN is unused - assign to this student
                if($st_reg_no == "") {
                    sql($DBH, "UPDATE tbl_pin SET reg_no = ?, class = ?, term = ?, year = ? WHERE pin = ?", 
                        array($st_reg, $st_class, $st_term, $st_year, $st_pin));
                    
                    redirect("my_results.php?msg=results&mypin=$st_pin&term=$st_term&myreg=$st_reg&examyear=$st_year&myclass=$st_class");
                    exit;
                } 
                // PIN is already assigned to this student for this session
                else if($st_reg_no == $st_reg && $st_thisyear == $st_year) {
                    redirect("my_results.php?msg=results&mypin=$st_pin&term=$st_term&myreg=$st_reg&examyear=$st_year&myclass=$st_class");
                    exit;
                } 
                // PIN is assigned to someone else or different session
                else {
                    redirect("main.php?msg=PINfailed");
                    exit;
                }
            } 
            // Invalid PIN
            else {
                redirect("main.php?msg=failed");
                exit;
            }
        }
        catch(PDOException $e) { 
            file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
            redirect('main.php?msg=failed');
        }
    } 
    // Form not submitted properly
    else {
        redirect('main.php?msg=failed');
    }
?>