<?php
session_start();
if (isset($_SESSION['logged']) && $_SESSION['logged'] == "1" && $_SESSION['role'] == "admin") {

$file = $_FILES['file']['tmp_name'];
require_once('../../assets/constants/config.php');
require_once('../constants/SimpleXLSX.php');
require_once('../../assets/constants/uniques.php');

$st_rec = 0;


if ( $xlsx = SimpleXLSX::parse($file) ) {
	foreach( $xlsx->rows() as $r ) {

        if ($st_rec == 0) {

        }else{

            $id = 'ST-'.get_rand_numbers(6).'';
            $fname = ucfirst($r[0]);
            $lname = ucfirst($r[1]);
            $gender = $r[3];
            $email = $r[2];
            $dep = $_POST['department'];
            $class = $_POST['class'];
            $login_pass = password_hash($r[4], PASSWORD_DEFAULT);

        
            try {
                $conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4;collation=utf8_general_ci;prefix=''", $username, $password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                    
                $stmt = $conn->prepare("SELECT email FROM tbl_admin WHERE email = :email UNION SELECT email FROM tbl_students WHERE email = :email");
                $stmt->bindParam(':email', $email_address);
                $stmt->execute();
                $result = $stmt->fetchAll();
                $rec = count($result);
                
                if ($rec > 0) {
            
                
                }else{
                
                $stmt = $conn->prepare("INSERT INTO tbl_students (id, first_name, last_name, gender, department, class, email, login) 
                                        VALUES (:id, :fname, :lname, :gender, :dep, :class, :email, :login)");
                $stmt->bindParam(':id', $id);
                $stmt->bindParam(':fname', $fname);
                $stmt->bindParam(':lname', $lname);
                $stmt->bindParam(':gender', $gender);
                $stmt->bindParam(':dep', $dep);
                $stmt->bindParam(':class', $class);
                $stmt->bindParam(':email', $email);
                $stmt->bindParam(':login', $login_pass);
                $stmt->execute();
                

                
                }
                
                                      
                }catch(PDOException $e)
                {
                echo "Connection failed: " . $e->getMessage();
                }


          
        }
        $st_rec++;

    }
    

    $_SESSION['reply'] = "039";
    header("location:../students");

} else {
	echo SimpleXLSX::parseError();
}


}else{
    header("location:../");
}




?>