<?php
$GLOBALS ['errors'] = array();


// LOGIN FUNCTION
function login($username1, $password1){
    // connecting to db
    $db = getConnection();


    // getting ip
    $ip = getip();
    
    
        $username = mysqli_real_escape_string($db, $username1);
        $password = mysqli_real_escape_string($db, $password1);
    
        if (empty($username)) {
            array_push($GLOBALS['errors'], "Username is required");
        }
        if (empty($password)) {
            array_push($GLOBALS['errors'], "Password is required");
        }
    
        if (count($GLOBALS['errors']) == 0) {
            //$password = md5($username.$password);
            $query = "SELECT * FROM customer WHERE email='$username' AND password='$password'";
            $results = mysqli_query($db, $query);
            if (mysqli_num_rows($results) == 1) {
                $result=mysqli_fetch_assoc($results);


                //************ CAPTURING THE ACCTIVITY ON THE AUDIT TRAIL TABLE */
                $t = time();
                $d = date("Y-m-d G:i:s",$t);
                //$_SESSION['username'] = $username;
                //$_SESSION['success'] = "You are now logged in";
                //$_SESSION['usertype']=$result['role'];
                //$_SESSION['ip']= $ip;
                $query1 = "INSERT INTO `audit_trail`(`username`, `time_stamp`, `action`, `results`, `data`, `impact`, `ip_address`) 
                VALUES ('$username','$d','login','success','n/a','$username','$ip')";
                mysqli_query($db, $query1);
                /*   END OF AUDIT TRACKING*/

                // CREATING USER PROFILE
                $fullname = $result['fullName'];
                $customerID = $result['customerID'];
                $school = $result['school'];
                $email = $result['email'];
                $usertype = $result['customerType'];
                $tell = $result['tell'];
                $dateCreated = $result['dateCreated'];
                $subscriptions = array("PQU1234FGT", "PQU1234FGT", "PQU1234FGT");




                // FUNCTIONS RESPONSE
                $response = array(
                    "status" => 1,
                    "auth" => "success",
                    "username" => "$email",
                    "fullname" =>"$fullname",
                    "customerID" =>"$customerID",
                    "school" => "$school",
                    "tell" => "$tell",
                    "user_type" => "$usertype",
                    "subscriptions" => json_encode($subscriptions),
                    "response_type" => "json",
                    );
                //pt end
                print (json_encode($response));
            }else { // IF AUTHENTION FAILS RETURN ERROR MASSAGE
                $t = time();
                $d = date("Y-m-d G:i:s",$t);
                
                array_push($GLOBALS['errors'], "Wrong username/password combination");

                $query2 = "INSERT INTO `audit_trail`(`username`, `time_stamp`, `action`, `results`, `data`, `impact`, `ip_address`) 
                VALUES ('$username','$d','login','failed','n/a','$username','$ip')";

                mysqli_query($db, $query2);

                
                //ch
                $response = array(
                    "status" => 0,
                    "auth" => "fail",
                    "massage" => $GLOBALS['errors'],
                    "username" => "$username",
                    "role" => "n/a",
                    "access" => 0,
                    "response_type" => "json",
                    );
                //ch

                print (json_encode($response));
            }
        }
}

// IP COLLECTION  FUNCTION
function getip(){
        // 

        $ip_address = "";
        //whether ip is from share internet
        if (!empty($_SERVER['HTTP_CLIENT_IP']))   
        {
            $ip_address = $_SERVER['HTTP_CLIENT_IP'];
        }
        //whether ip is from proxy
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
        {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        //whether ip is from remote address
        else
        {
            $ip_address = $_SERVER['REMOTE_ADDR'];
        }
        $ip = $ip_address;
        return $ip;
}

// REGISTER
function addCustomer($name, $email, $tell, $password, $type, $school){
    
    
    //
    $db = getConnection();
     //receive all input values from the form
     
     //form validation: ensure that the form is correctly filled ...
     //by adding (array_push()) corresponding error unto $GLOBALS['errors'] array
     if (empty($name)) { array_push($GLOBALS['errors'], "Username is required"); }
     if (empty($email)) { array_push($GLOBALS['errors'], "Email is required"); }
     if (empty($tell)) { array_push($GLOBALS['errors'], "telepnone is required"); }
     if (empty($type)) { array_push($GLOBALS['errors'], "type is required is required"); }
     if (empty($password)) { array_push($GLOBALS['errors'], "Password is required"); }
     if (empty($school)) { array_push($GLOBALS['errors'], "school is required"); }
     
     // first check the database to make sure 
     // a user does not already exist with the same username and/or email
     $user_check_query = "SELECT * FROM customer WHERE  email='$email' LIMIT 1";
     $result = mysqli_query($db, $user_check_query);
     $user = mysqli_fetch_assoc($result);
 
     if ($user) { // if user exists
 
         if ($user['email'] === $email) {
             array_push($GLOBALS['errors'], "email already exists");
         }
     }
      
     // Finally, register user if there are no errors in the form
     if (count($GLOBALS['errors']) == 0) {
         //echo("prog1");
         //$password = md5($username.$password_1);//encrypt the password before saving in the database
         $t = time();
         $d = date("Y-m-d G:i:s",$t);

         // Create user profile
         $query = "INSERT INTO `customer`(`fullName`, `email`, `tell`, `school`, `password`, `customerType`) 
            VALUES ('$name','$email','$tell','$school','$password','$type')";
         mysqli_query($db, $query);
         //print(mysqli_error($db));

      //****AUDIT TRAIL */
      $query1 = "INSERT INTO `audit_trail`(`username`, `time_stamp`, `action`, `results`, `data`, `impact`, `ip_address`) 
      VALUES ('$username','$d','registration','success','n/a','$username','$ip')";

      mysqli_query($db, $query1);
      /*****END OF AUDIT TRAIL */
         
         $response = array(
             "status" => 1,
             "message" => "registration successful",
             "response_type" => "json",
         );
         print(json_encode($response));
     }else {

        //****AUDIT TRAIL */
      $query2 = "INSERT INTO `audit_trail`(`username`, `time_stamp`, `action`, `results`, `data`, `impact`, `ip_address`) 
      VALUES ('$username','$d','registration','failed','n/a','$username','$ip')";

      mysqli_query($db, $query2);
      /*****END OF AUDIT TRAIL */

        $response = array(
            "status" => 0,
            "message" => $GLOBALS['errors'],
            "response_type" => "json",
        );
        print(json_encode($response));
         
     }
 
}

// ACCESS
function access(){
        session_start();

    if (!isset($_SESSION['username'])) {
        $_SESSION['msg'] = "You must log in first";
        header('location: login.php');
    }

    if (isset($_GET['logout'])) {
        session_destroy();
        unset($_SESSION['username']);
        unset($_SESSION['usertype']);
        header("location: login.php");
    }
}

// ADMIN
function admin(){
    if ($_SESSION['roles']!= "admin"){
        header("location: index.php");
    }
}
?>