<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
AllowUser("staff");
//require("../../../../epconfig/GenScript/PHP/getinfo.php");//hold basic 
/*
staffsearchsearchtxt=yom&staffsearch_crtlb=&staffsearch_crimgl=&stuserId=8&staffFullnme=Keje%20Yommy&staffDOB_day=8&staffDOB_month=9&staffDOB_year=1999&staffstateorig=3&staffstateoriglga=68&staffnat=Nigeria&staffemail=ab_keje@yahoo.com&staffphone=08077887656&staffemmg=07089787665&staffaddr=50%2C%20Oro%20road%20Uyo%20AKS&loadimg=&camimg=&clearimg=&staffposition=Vice%20Chancelor&staffIDSch=ST00/MED/09&staffunit=Administration&staffqual=Bsc%20Mathematics%2C%20PHd%20Statiticstic%3B%20Msc%20Business%20in%20University%20of%20New%20York&staffrstup=1&courses=3%7E6%7E10
*/

//display date to mysql date

//function to form insert / update array 
function FormDBArray($post){
  global $dbo;
    $rtn = array(
        "StaffName"=>$dbo->SqlSafe($post['staffFullnme']),
        "DOB"=>MysqlDateEncode($post['staffDOB']),
        "LGAID"=>$post['staffstateoriglga'],
        "StateID"=>$post['staffstateorig'],
        "EduQual"=>$dbo->SqlSafe($post['staffqual']),
        "Phone"=>$dbo->SqlSafe($post['staffphone']),
        "Rank"=>$dbo->SqlSafe($post['staffposition']),
        "Email"=>$dbo->SqlSafe($post['staffemail']),
        "Nat"=>$dbo->SqlSafe($post['staffnat']),
        "Addrs"=>$dbo->SqlSafe($post['staffaddr']),
        "Emergency"=>$dbo->SqlSafe($post['staffemmg']),
        "StaffUnit"=>$dbo->SqlSafe($post['staffunit']),"StaffSchID"=>$dbo->SqlSafe($post['staffIDSch']),"Courses"=>$dbo->SqlSafe($post['courses']),
        "DeptIDs"=>$dbo->SqlSafe($post['depts'])
        );
        return $rtn;
}
//echo $_POST['staffid'];
if(isset($_POST['staffid'])){
   // echo FormDBArray($_POST);
   // extract($_POST);
  // exit(implode(" ; ",FormDBArray($_POST)));
    if((int)$_POST['staffid'] == 0){ //new staff
      $em = $dbo->SqlSafe($_POST['staffemail']);
     // $uid = trim($_POST['stuserId']) == "" ?0:$_POST['stuserId'];
      //exit($em);
       $chckuid = $dbo->SelectFirstRow("staff_tb","","Email = '".$em."'");
       if(is_array($chckuid)){
           exit("#INVALID OPERATION: Staff Already Exist");
       }
       $chckuid = $dbo->SelectFirstRow("user_tb","","UserLogName = '".$em."'");
       if(is_array($chckuid)){
           exit("#INVALID OPERATION: User Already Exist: You can Set a User as a Staff in the Users Module");
       }
       //if(isset($_FILES['staffpasspd_image_file'])){
         //load passport
         $temp = rand().time();
         if(Upload('staffpasspd_image_file',$configdir."Files/UserImages/".$temp.".jpg")){
              //insert in user first
              //form user data / defaults
              $fielArr = array("UserLogName"=>$dbo->SqlSafe($_POST["staffemail"]),"UserName"=>$dbo->SqlSafe($_POST['staffFullnme']));
            $fielArr['Pin'] = "1111";
            $passwarr = $dbo->Hash("default@password");
            $fielArr['UserPassw'] = $passwarr[0];
            $fielArr['enc'] = $passwarr[1];
            $fielArr['MaxEntry'] = 8;
            $fielArr['IdleTime'] = 60;
            $fielArr['PinStatus'] = 1;
            $fielArr['StaffID'] = 0;
            $fielArr['Hint'] = '';
            $fielArr['remail'] = '';
            $fielArr['rphone'] = '';
            $rstup = (int)$_POST['staffrstup'] > 0?":RUpload":"";
            $fielArr['Privs'] = "Password:Pin".$rstup;
            //exit(json_encode($fielArr));
            $inst = $dbo->InsertID2("user_tb",$fielArr); //insert ib db
            //
            if($inst < 0){ 
                 exit("#Staff/User Creation Failed");
                }//user detatils inserted
                //exit('aaa - '.$inst );
                $NID = $inst; //get new user id
                
                //rename user passport

                //updated userid element of the array
               // $_POST['stuserId'] = $NID;
                rename($configdir."Files/UserImages/".$temp.".jpg",$configdir."Files/UserImages/".$NID.".jpg"); //rename user passport to 
                //upload signature if set
                //Upload('staffpasspd_image_file',"../../../Files/UserImages/".$temp.".jpg");
                $sigu = UploadFile("staffsigpd_image",$configdir."Files/UserImages/".$NID."_sig");
                if($sigu !== FALSE){ //signature uploaded
                  $staffinfo['Sig'] = "UserImages/".$NID."_sig";
                }
                //form the staff info array 
                $staffinfo = FormDBArray($_POST);
                $staffinfo['UserID'] = $NID;
                $staffinfo['StaffType'] = '';
                $staffinfo['Passport'] = '';
                //insert staff
                $inststaff = $dbo->Insert("staff_tb",$staffinfo);
                //exit($inststaff);
               if($inststaff == "#"){
                 exit("*Staff/User Added Successfully`_`".$NID);
               }else{ //if staff insert faild (delete user account)
                  $dbo->Delete("user_tb","UserID=$NID");
                  exit("#Staff/User Creation Failed - ".$inststaff);
               }
            
            
         }else{
             exit("Error Uploading Passport Photograph");
         }
       //insert to form new user
       //}
       
    }else{ //update staff / User Info
       $SID = $_POST['staffid'];
       $UID = $_POST['stuserId'];
       $em = $dbo->SqlSafe($_POST["staffemail"]);
       $emrec = $dbo->SelectFirstRow("staff_tb","ID","Email = '".$em."'");
       if(is_array($emrec)){
           if((int)$SID != (int)$emrec['StaffID']){
               exit("#INVALID EMAIL: Already Exist");
           }
       }

       if(isset($_FILES['staffpasspd_image_file'])){
           Upload('staffpasspd_image_file',$configdir."Files/UserImages/".$UID.".jpg");
       }

       //staffsigpd_image_file
       $upsig = NULL;
       if(isset($_FILES['staffsigpd_image_file'])){
        
        $upsig = UploadFile('staffsigpd_image',$configdir."Files/UserImages/".$UID."_sig");
        
        if($upsig === FALSE){
          exit("#SIGNATURE UPDATE FAILED");
        }
        //exit(ltrim($upsig,"../"));
        $upsig = "UserImages/".$UID."_sig";
    }else{
      //exit("#NOT SEEN");
    }
       $dbo->Bigin();
         $staffinfo = FormDBArray($_POST);
if(!is_null($upsig)){
  $staffinfo['Sig'] = $upsig;
}
         $updt = $dbo->Update("staff_tb",$staffinfo,"StaffID=".$SID);
         if(is_array($updt)){
           // if($updt[1] > 0){ //if update found
            $rstup = (int)$_POST['staffrstup'] > 0?"CONCAT(REPLACE(Privs,':RUpload',''),':RUpload')":"REPLACE(Privs,':RUpload','')";
            
              //update user_tb 
              $emm = $dbo->SqlSafe($_POST["staffemail"]);
              $un = $dbo->SqlSafe($_POST['staffFullnme']);
             // $fielArr['Privs'] = $rstup;
              $uspdt = $dbo->RunQuery("UPDATE user_tb SET  UserLogName = '$emm', UserName = '$un', Privs = $rstup WHERE UserID=".$UID);
              if(is_array($uspdt)){
                 $dbo->Commit();
                 exit("*Staff Record Updated Successfully");
              }else{
                  $dbo->Rollback();
                  exit("#Staff Record Update Failed");
              }
           // }else{
               // $dbo->Rollback();
               // exit("No Changes Found");
           // }
         }else{
             $dbo->Rollback();
             exit("#Staff Record Update Failed");
         }

    }
}else{
    exit("#INVALID PARAMETER");
}



?>