<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
//require("../../../../general/getinfo.php");
function UpdateSig($sigjson,$sigdet){
    global $staff;
    $newsig = [$sigdet['Title']=>[]];
    //get the sig json
    $sigarr = explode("/",$staff['Sig']);
    //if(!isset($sigdet["#"]))$sigdet["#"] = "sss";
    //exit(json_encode(["Error"=>json_encode($sigdet)]));
    //check if current sig details exist
    if($sigdet['Parent'] == "" && isset($sigjson[$sigdet['Title']])){
       
      //loop tru all the fields
      if(isset($sigdet['Fields'])){
         foreach ($sigdet['Fields'] as $fkey => $fval) {
           if($fkey == "1")$sigjson[$sigdet['Title']]["1"]="UserImages/".$sigarr[count($sigarr) - 1];
           if($fkey == "2")$sigjson[$sigdet['Title']]["2"]=$staff['StaffName'];
           if($fkey == "3")$sigjson[$sigdet['Title']]["3"]=date("d/m/Y");
           if($fkey == "#")$sigjson[$sigdet['Title']]["#"]=$sigdet['Title'];

         }
      }
     /* if(isset($sigjson[$sigdet['Title']]["1"]))$sigjson[$sigdet['Title']]["1"]="UserImages/".$sigarr[count($sigarr) - 1];
     if(isset($sigjson[$sigdet['Title']]["2"]))$sigjson[$sigdet['Title']]["2"]=$staff['StaffName'];
     if(isset($sigjson[$sigdet['Title']]["3"]))$sigjson[$sigdet['Title']]["3"]=date("d/m/Y"); */
     
    }else if($sigdet['Parent'] != "" && isset($sigjson[$sigdet['Parent']][$sigdet['Title']])){ //if sub
      if(isset($sigdet['Fields'])){
         foreach ($sigdet['Fields'] as $fkey => $fval) {
            if($fkey == "1")$sigjson[$sigdet['Parent']][$sigdet['Title']]["1"]="UserImages/".$sigarr[count($sigarr) - 1];
            if($fkey == "2")$sigjson[$sigdet['Parent']][$sigdet['Title']]["2"]=$staff['StaffName'];
            if($fkey == "3")$sigjson[$sigdet['Parent']][$sigdet['Title']]["3"]=date("d/m/Y");
            if($fkey == "#")$sigjson[$sigdet['Parent']][$sigdet['Title']]["#"]=$sigdet['Title'];
         }
      }
     /* if(isset($sigjson[$sigdet['Parent']][$sigdet['Title']]["1"]))$sigjson[$sigdet['Parent']][$sigdet['Title']]["1"]="UserImages/".$sigarr[count($sigarr) - 1];
     if(isset($sigjson[$sigdet['Parent']][$sigdet['Title']]["2"]))$sigjson[$sigdet['Parent']][$sigdet['Title']]["2"]=$staff['StaffName'];
     if(isset($sigjson[$sigdet['Parent']][$sigdet['Title']]["3"]))$sigjson[$sigdet['Parent']][$sigdet['Title']]["3"]=date("d/m/Y"); */
    }else if($sigdet['Parent'] == ""){
      if(isset($sigdet['Fields'])){
         foreach ($sigdet['Fields'] as $fkey => $fval) {
            if($fkey == "1")$sigjson[$sigdet['Title']]["1"]="UserImages/".$sigarr[count($sigarr) - 1];
            if($fkey == "2")$sigjson[$sigdet['Title']]["2"]=$staff['StaffName'];
            if($fkey == "3")$sigjson[$sigdet['Title']]["3"]=date("d/m/Y");
            if($fkey == "#")$sigjson[$sigdet['Title']]["#"]=$sigdet['Title'];
         }
      }
     //$sigjson[$sigdet['Title']] = ["1"=>"UserImages/".$sigarr[count($sigarr) - 1],"2"=>$staff['StaffName'],"3"=>date("d/m/Y")];
    }else{
      if(isset($sigdet['Fields'])){
         foreach ($sigdet['Fields'] as $fkey => $fval) {
            if($fkey == "1")$sigjson[$sigdet['Parent']][$sigdet['Title']]["1"]="UserImages/".$sigarr[count($sigarr) - 1];
            if($fkey == "2")$sigjson[$sigdet['Parent']][$sigdet['Title']]["2"]=$staff['StaffName'];
            if($fkey == "3")$sigjson[$sigdet['Parent']][$sigdet['Title']]["3"]=date("d/m/Y");
            if($fkey == "#")$sigjson[$sigdet['Parent']][$sigdet['Title']]["#"]=$sigdet['Title'];
         }
      }
    // $sigjson[$sigdet['Parent']][$sigdet['Title']] = ["1"=>"UserImages/".$sigarr[count($sigarr) - 1],"2"=>$staff['StaffName'],"3"=>date("d/m/Y")];
    }
   
    return $sigjson;
        }
if(!isset($_POST['param']) && !isset($_POST['SignDet']))exit(json_encode(["Error"=>"Invalid Parameter"]));
//echo $_POST['param'];

if(isset($_POST['param'])){ //Get the Signatory
    if(trim($_POST['param']) == "")exit(json_encode(["Error"=>"Invalid Report Details Supplied"]));
//get the param
$params = json_decode($_POST['param'],true);
if(!isset($params['ReportID']))exit(json_encode(["Error"=>"Report Identification Failed"]));

$ReportID = $params['ReportID'];

//get the report
$rportdet = $dbo->SelectFirstRow("report_tb","","ID=".$ReportID);

if(!is_array($rportdet))exit(json_encode(["Error"=>"Reading Report Details Failed"]));

$signatories = $rportdet['Signatories'];
if(trim($signatories) == "")exit(json_encode(["Error"=>"No Signatories Set"]));

$signatoriesobj = json_decode($signatories,true);

if(is_null($signatoriesobj))exit(json_encode(["Error"=>"Reading Signatories Failed - Invalid Format"]));

//get all signatorie titles
$Titles = [];
/* {"HEAD OF DEPARTMENT":{"1":"","2":"","3":""},"DEAN":{"1":"","2":"","3":"","SENATE APPROVAL":{"3":""}},"CHAIRMAN, SERVC":{"1":"","2":"","3":""}} */
foreach($signatoriesobj as $tit=>$cont){
   if(is_numeric($tit)){
    $Titles[] = ["Title"=>$cont,"Fields"=>["1"=>"","2"=>"","3"=>""],"Parent"=>""];continue;
   }
   
   $fields = [];
   $subs = [];
   //check if sub title exist
   if(is_array($cont)){
       foreach($cont as $field=>$val){
          if(!is_array($val)){
            $fields[$field] = $val;
          }else{
            $Titles[] = ["Title"=>$field,"Fields"=>$val,"Parent"=>$tit];
          }
       }
   }

   $Titles[] = ["Title"=>$tit,"Fields"=>$fields,"Parent"=>""];
}

//form username and password field
ob_start();
TextBoxGroup();
TextBox("title=Signatory Username (Email),style=width:250px,id=SigUserName,logo=user,info=Signatory Login Username");
TextBox("title=Signatory Password,style=width:250px,id=SigPassw,logo=user-secret,info=Signatory Login Password,type=password");
_TextBoxGroup();
$sigmarkup = ob_get_contents();
ob_end_clean();
exit(json_encode(["Signatories"=>$Titles,"HTML"=>$sigmarkup]));
}


if(isset($_POST['SignDet'])){ //Sign the Report

   if(trim($_POST['SignDet']) == "")exit(json_encode(["Error"=>"Invalid Signatory Details"]));
   if(trim($_POST['ReportDet']) == "")exit(json_encode(["Error"=>"Invalid Report Details"]));
   if(trim($_POST['UserName']) == "")exit(json_encode(["Error"=>"Invalid Username"]));
   if(trim($_POST['UserPassw']) == "")exit(json_encode(["Error"=>"Invalid Password"]));

   //get user enc
   $enc = $dbo->SelectFirstRow("user_tb","enc","UserLogName = '{$_POST['UserName']}'");
   if(!is_array($enc)){
    exit(json_encode(["Error"=>"Wrong Username Supplied"]));
   }
$enc = $enc['enc'];
   $hash = $dbo->Hash($_POST['UserPassw'],$enc);
	  $hashpw = $hash[0];
	 $emailrec = $dbo->SelectFirstRow("user_tb","","UserLogName = '{$_POST['UserName']}' and UserPassw = '$hashpw'");

     if(!is_array($emailrec))exit(json_encode(["Error"=>"Wrong Username and Password Supplied"]));

     //get the user staff details
     $staff = $dbo->SelectFirstRow("staff_tb","","UserID = {$emailrec['UserID']}");
     if(!is_array($staff))exit(json_encode(["Error"=>"Invalid Staff. Only Approved Staff can sign on a Report"]));

     $signature = $staff['Sig'];
     $sigdet = json_decode($_POST['SignDet'],true);
     $reptdet = json_decode($_POST['ReportDet'],true);
     $rpdatastr = $dbo->DataString($reptdet);
     $ReportID = (int)$reptdet['ReportID'];

     //check if signature json already exist for the report
     $repsig = $dbo->SelectFirstRow("reportsig_tb","","Param = '".$rpdatastr."'");
     if(is_array($repsig)){ //if exist
        //get the user det
       
       //get the sig json
       $sigjson = json_decode($repsig['Signatories'],true);
       
       $sigjson = UpdateSig($sigjson,$sigdet);
       
       
       /* //check if current sig details exist
       if($sigdet['Parent'] == "" && isset($sigjson[$sigdet['Title']])){
        if(isset($sigjson[$sigdet['Title']]["1"]))$sigjson[$sigdet['Title']]["1"]=$staff['Sig'];
        if(isset($sigjson[$sigdet['Title']]["2"]))$sigjson[$sigdet['Title']]["2"]=$staff['StaffName'];
        if(isset($sigjson[$sigdet['Title']]["3"]))$sigjson[$sigdet['Title']]["3"]=date("d/m/Y");
       }else if($sigdet['Parent'] != "" && isset($sigjson[$sigdet['Parent']['Title']])){ //if sub
        if(isset($sigjson[$sigdet['Parent']['Title']]["1"]))$sigjson[$sigdet['Parent']['Title']]["1"]=$staff['Sig'];
        if(isset($sigjson[$sigdet['Parent']['Title']]["2"]))$sigjson[$sigdet['Parent']['Title']]["2"]=$staff['StaffName'];
        if(isset($sigjson[$sigdet['Parent']['Title']]["3"]))$sigjson[$sigdet['Parent']['Title']]["3"]=date("d/m/Y");
       }else if($sigdet['Parent'] == ""){
        $sigjson[$sigdet['Title']] = ["1"=>$staff['Sig'],"2"=>$staff['StaffName'],"3"=>date("d/m/Y")];
       }else{
        $sigjson[$sigdet['Parent']][$sigdet['Title']] = ["1"=>$staff['Sig'],"2"=>$staff['StaffName'],"3"=>date("d/m/Y")];
       } */

       //update id

$update = $dbo->Update("reportsig_tb",['Signatories'=>json_encode($sigjson)],"ID=".$repsig['ID']);
if(!is_array($update))exit(json_encode(["Error"=>"Update Failed"]));
//exit(json_encode(["Error"=>$repsig['ID']]));

exit(json_encode(["Finish"=>"Finish"]));
     }else{
         //get template from report_tb
         //get the report
$rportdet = $dbo->SelectFirstRow("report_tb","","ID=".$ReportID);

if(!is_array($rportdet))exit(json_encode(["Error"=>"Reading Report Details Failed"]));

$signatories = $rportdet['Signatories'];
if(trim($signatories) == "")exit(json_encode(["Error"=>"No Signatories Set"]));

$signatoriesobj = json_decode($signatories,true);

if(is_null($signatoriesobj))exit(json_encode(["Error"=>"Reading Signatories Failed - Invalid Format"]));
$sigjson = UpdateSig($signatoriesobj,$sigdet);
//insert
$ins = $dbo->InsertID("reportsig_tb",["Param"=>$rpdatastr,"Signatories"=>json_encode($sigjson)]);
if(!is_numeric($ins))exit(json_encode(["Error"=>"Adding Sidnatory Details Failed"]));

exit(json_encode(["Finish"=>"Finish"]));
     }

     

     




//echo $_POST['ReportDet'];
   
  




}







?>