<?php
 header("Access-Control-Allow-Origin: *");
date_default_timezone_set("Africa/Lagos");
//include connection file 
include_once("db_cls_connect.php");

include('../partials/header.php');

$params = $_REQUEST;
$action = $params['action'] != '' ? $params['action'] : '';
$staff = new Staff();

switch ($action) {
    case 'login':
        $staff->login();
        break;
    case 'logout':
        $staff->logout();
        break;
    default:
        return;
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Staff
 *
 * @author Username
 */
class Staff {

    //put your code here
    public function __construct() {
        $db = new dbObj();
        $connString = $db->getConnstring();
        $this->conn = $connString;
    }

     function login() {
        if (isset($_POST['login-submit'])) {
            $user_name = mysqli_real_escape_string($this->conn, trim($_POST['username']));
            $user_name = strtoupper($user_name);
            $user_password = mysqli_real_escape_string($this->conn, trim($_POST['password']));
            $sql = "SELECT * FROM nonacadstaffs WHERE password='$user_password' and staffsId= '$user_name'";
            $resultset = mysqli_query($this->conn, $sql) or die("database error:" . mysqli_error($this->conn));
            if (mysqli_num_rows($resultset)>0) {
                $row = mysqli_fetch_assoc($resultset);
				$hma = $row['hashedbui'];
				$_SESSION['username'] = $hma;
                $_SESSION['staff_session'] = $user_name;
                //get the details
				calogin($_SESSION['staff_session']);
                echo "1";
            }else{
				 $sql = "SELECT * FROM nonacadstaffs WHERE phonenumber='$user_password' and staffsId= '$user_name'";
            $resultset = mysqli_query($this->conn, $sql) or die("database error:" . mysqli_error($this->conn));
			 if (mysqli_num_rows($resultset)>0) {
				 $_SESSION['staff_reg'] = $user_name;
				echo "Reg";
			 }else {
                echo "Ohhh ! Wrong Credential."; // wrong details
            }
			
			
			
			}



			
        }
    }
    
    	function logout() {
			calogout($_SESSION['staff_session']);
		unset($_SESSION['staff_session']);
		if(session_destroy()) {
			header("Location: ../../index.php");
		}
    
        }

        public function insertStaff($depcode, $coscode, $description, $cosunit) {

        if (!$this->conn) {
            die('Failed to connect to MySQL: ' . mysqli_connect_error());
        }

        $sql = "INSERT INTO course(CourseID, Description, UNIT, Departments_DepartmentCode) VALUES  (trim('$coscode'),trim('$description'), trim('$cosunit'), trim('$depcode'))";

        $query = mysqli_query($this->conn, $sql);

        if (!$query) {
            die('SQL Error: ' . mysqli_error($this->conn));
        }
        return $query;
    }

    public function getAllStaffs() {

        if (!$this->conn) {
            die('Failed to connect to MySQL: ' . mysqli_connect_error());
        }

        $sql = 'SELECT * FROM nonacadstaffs';

        $query = mysqli_query($this->conn, $sql);

        if (!$query) {
            die('SQL Error: ' . mysqli_error($this->conn));
        }
        return $query;
    }
    
    public function getAllStaffsByCourseCode($course_code) {

        if (!$this->conn) {
            die('Failed to connect to MySQL: ' . mysqli_connect_error());
        }

        $sql = "SELECT * FROM `staff_course_mapping` JOIN nonacadstaffs ON (staff_course_mapping.staff_id=nonacadstaffs.nonacadstaffsId)
WHERE staff_course_mapping.course_id='$course_code'";
        
        $query = mysqli_query($this->conn, $sql);

        if (!$query) {
            die('SQL Error: ' . mysqli_error($this->conn));
        }
        return $query;
    }
    
    public function getCoursesAssignedToStaff($id) {

        if (!$this->conn) {
            die('Failed to connect to MySQL: ' . mysqli_connect_error());
        }

        $sql = "SELECT * FROM `staff_course_mapping` JOIN course ON (staff_course_mapping.course_id=course.CourseID)
WHERE staff_course_mapping.staff_id='$id'";
        
        $query = mysqli_query($this->conn, $sql);

        if (!$query) {
            die('SQL Error: ' . mysqli_error($this->conn));
        }
        return $query;
    }

    public function assignStaff($id, $course_id) {

        if (!$this->conn) {
            die('Failed to connect to MySQL: ' . mysqli_connect_error());
        }
        $today=date("Y-m-d");
        
        $sql="SELECT id from staff_course_mapping WHERE staff_id ='$id' and course_id='$course_id' ";
        $query = mysqli_query($this->conn, $sql);
        
        if(mysqli_num_rows($query)>0){
            return 0;
        }else{
        $sql = "INSERT INTO staff_course_mapping(staff_id, course_id,date_) VALUES  ('$id','$course_id','$today')";

        $query = mysqli_query($this->conn, $sql);

        if (!$query) {
            die('SQL Error: ' . mysqli_error($this->conn));
        }
        
        }
        return 1;
    }
    
    public function unassignStaff($id, $course_id) {

        if (!$this->conn) {
            die('Failed to connect to MySQL: ' . mysqli_connect_error());
        }
       
        $sql = "DELETE FROM staff_course_mapping WHERE staff_id='$id' AND  course_id='$course_id' ";

        $query = mysqli_query($this->conn, $sql);

        if (!$query) {
            die('SQL Error: ' . mysqli_error($this->conn));
        }
        
        
        return 1;
    }
public function getStaffByID($id) {

        if (!$this->conn) {
            die('Failed to connect to MySQL: ' . mysqli_connect_error());
        }

        $sql = "SELECT * FROM nonacadstaffs WHERE nonacadstaffsId='$id'";
        
        $query = mysqli_query($this->conn, $sql);

        if (!$query) {
            die('SQL Error: ' . mysqli_error($this->conn));
        }
       
        if(mysqli_num_rows($query)>0){
            //valid
            $rs= mysqli_fetch_assoc($query);
            return $rs;
        }else{
            //wrong
            return 0;
        }
        
        
        
    }
}
function connect(){
$dbc = mysqli_connect("localhost", "bowensta_bowen", "80622BOWen") or die('No server');
	mysqli_select_db($dbc, "bowensta_sshub") or die('No db');
	return $dbc;

}



function calogout($username){
	$dbc = connect();
	$timestamp = strtotime("now");
	$deviceid = getdeviceip();	
	mysqli_query($dbc, "INSERT into logs(action,actor,message,lastseen, deviceid) VALUES('Logout','$username', 'User logged out', '$timestamp', '$deviceid' )");
	
}
function calogin($username){
	$dbc = connect();
	$timestamp = strtotime("now");
	$deviceid = getdeviceip();
	mysqli_query($dbc, "INSERT into logs(action,actor,message,lastseen, deviceid) VALUES('Login','$username', 'User logged in', '$timestamp', '$deviceid' )");
	
}

function getdeviceip(){
	// Get real visitor IP behind CloudFlare network
    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
              $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
              $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}