<?php
$EpModuleName = "pgateway";
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
//require("../../../../general/getinfo.php");
 //exit('{"Message":"#'.json_encode($_FILES).'}');
 function ProccessParam($param){
  global $dbo;
  if(trim($param) == "")return ["",""];
   //covert the spread sheet to data array
   $ParamArr = $dbo->DataArray($param);
if(!isset($ParamArr['MaxDataRow'])) return ["",""];
$totalrws = (int)$ParamArr['MaxDataRow'];
$demoarr = [];
$livearr = [];
//loop tru all rows and form the DEMO and LIVE parameters Data string
for ($rw=1; $rw <= $totalrws; $rw++) {
  $curdel = $ParamArr[$rw . "_deleted"];
 
    $curparam = $ParamArr[$rw . "_1"];
    if($curdel == "true" || trim($curparam) == "")continue;
    $demoval = $ParamArr[$rw . "_2"];
    $liveval = $ParamArr[$rw . "_3"];
    $demoarr[$curparam] = $demoval;
    $livearr[$curparam] = $liveval;
}
return [$dbo->DataString($demoarr),$dbo->DataString($livearr)];
 }
/* function UploadFile($tbname,$filename){
    if(trim($tbname) == "" || trim($filename) == "")return false;
    $filename = strtolower($filename);
    //$gatewayname trim(str_replace($gatewayname," ","_");
    if(isset($_FILES[$tbname."_file"])){
        $fileTmpLoc = $_FILES[$tbname."_file"]["tmp_name"]; // File in the PHP tmp folder
        if ($fileTmpLoc) { // if file not chosen
            $uname = $_FILES[$tbname."_file"]["name"];
            $ext = pathinfo($uname,PATHINFO_EXTENSION);
            $dir = "epconfig/Gateways/";
           //$fn = "UserImages/Student/{$regfile}.jpg";
           if(!file_exists("../../../../".$dir ))mkdir("../../../../".$dir);
           if(move_uploaded_file($fileTmpLoc, "../../../../".$dir.$filename.".".$ext)){
               return $dir.$filename.".".$ext; //return filename from the root directory
           } else {
              // echo "#Operation Aborted: Cannot Upload Payment Receipt";
               exit('{"Message":"#Operation Aborted: File Upload Failed"}');
           }
        }else{
            return false;
          // echo "#Operation Aborted:Payment Receipt not Found";
               //exit("#Operation Aborted:Payment Receipt not Found"); 
        }

   }
   return false;
} */

function RemoveUpload($data){
    //global $data;
    if(isset($data['Script']) && trim($data['Script']) != ""){
      $fn = explode("/",$data['Script']);
      $data['Script'] = $fn[count($fn) - 1];
      unlink("../../../../general/Payment/Gateways/".$data['Script']);
    }
     if(isset($data['ResponseURL']) && trim($data['ResponseURL']) != ""){
      $fn = explode("/",$data['ResponseURL']);
      $data['ResponseURL'] = $fn[count($fn) - 1];
      unlink("../../../../general/Payment/Gateways/".$data['ResponseURL']);
       
     }
     if(isset($data['RequestURL']) && trim($data['RequestURL']) != ""){
      $fn = explode("/",$data['RequestURL']);
      $data['RequestURL'] = $fn[count($fn) - 1];
      unlink("../../../../general/Payment/Gateways/".$data['RequestURL']);
      //  unlink("../../../../".$data['RequestURL']);//FooterImage
     }
     if(isset($data['FooterImage']) && trim($data['FooterImage']) != ""){
      $fn = explode("/",$data['FooterImage']);
      $data['FooterImage'] = $fn[count($fn) - 1];
      unlink("../../../../general/Payment/Gateways/".$data['FooterImage']);
       //unlink("../../../../".$data['FooterImage']);//
     }
}
 extract($_POST);
 if($tpid != $EPTPID)exit('{"Message":"#INVALID TECHNICAL PERSONEL ID (TPID)"}');
 if(!isset($gid) || !isset($paygatenametb) || trim($paygatenametb) == "" || !isset($paygatescripttb) || trim($paygatescripttb) == "")exit('{"Message":"INVALID DATA SUPPLIED"}');
 $paygatestatus = (int)$paygatestatus == 1?"LIVE":"DEMO";
 $pparam = ProccessParam($param);
//exit($pparam[0]."  ;  ".$pparam[1]);
  $data = ["Name"=>$paygatenametb,"USE"=>$paygatestatus,"Descr"=>$paydateedecrtb,"Email"=>$paygateemailtb,"Phone"=>$paygatephonetb,"Addr"=>$paygateaddrtb,"PrePayMethod"=>$paygatepremtdtb,"PostPayMethod"=>$paygatepostmtdtb,"QueryStatusMethod"=>$paygatequerytb,"DEMO_PARAM"=>$pparam[0],"PARAM"=>$pparam[1],"FinishPayMethod"=>"","RefIndicator"=>trim($paygatetransindtb) == ""?"Payment Ref.":$paygatetransindtb,"NotificationRefID"=>$paygateresponseidtb,"FinishPayMethod"=>$paygatefinishtb];
  

  $mainscript = UploadFile('paygatescripttb',"../../../../general/Payment/Gateways/".strtolower(str_replace(" ","_",$paygatenametb))."_script");
  if($mainscript === false && $paygatenametb == 'LOADED'){
exit('{"Message":"#Operation Aborted: Payment Gateway Script Upload Failed"}');
  }
  if(is_string($mainscript)){
    // $data['Script'] = strtolower(str_replace(" ","_",$paygatenametb))."_script";
    $valss = explode("/",$mainscript);
    $data['Script'] = $valss[count($valss) - 1];
  }
 //upload the response url script if set - paygateresponsetb
  $resscript = UploadFile('paygateresponsetb',"../../../../general/Payment/Gateways/".strtolower(str_replace(" ","_",$paygatenametb))."_response");
  if(is_string($resscript)){
    $valrr = explode("/",$resscript);
    // $data['ResponseURL'] = strtolower(str_replace(" ","_",$paygatenametb))."_response"; 
    $data['ResponseURL'] = $valrr[count($valrr) - 1];
  }

  //upload the request url script if set - paygateresponsetb
  $reqscript = UploadFile('paygaterequesturltb',"../../../../general/Payment/Gateways/".strtolower(str_replace(" ","_",$paygatenametb))."_request");
  if(is_string($reqscript)){
    $valrq = explode("/",$reqscript);
    // $data['RequestURL'] = strtolower(str_replace(" ","_",$paygatenametb))."_request"; 
    $data['RequestURL'] =  $valrq[count($valrq) - 1];
  }

   //upload the footer image if set - paygateresponsetb
   $footerimg = UploadFile('payGatefoot_image',"../../../../general/Payment/Gateways/".strtolower(str_replace(" ","_",$paygatenametb))."_footer");
   if(is_string($footerimg)){
    $valfm = explode("/",$footerimg);
     //$data['FooterImage'] = strtolower(str_replace(" ","_",$paygatenametb))."_footer"; 
     $data['FooterImage'] =  $valfm[count($valfm) - 1];
    //  $data['FooterImage'] = strtolower(str_replace(" ","_",$paygatenametb))."_footer"; 
   }

 if((int)$gid == 0){ //add new pay gateway
  //check if the name already exist
  $ex = $dbo->SelectFirstRow("thirdparty_tb","","LCASE(TRIM(Name)) = '".trim(strtolower($paygatenametb))."'");
  if(is_array($ex))exit('{"Message":"#ADDING NEW PAYMENT GATEWAY FAILED, GATEWAY NAME ALREADY EXIST"}');
  $ins = $dbo->InsertID2("thirdparty_tb",$data);
  if(!is_numeric($ins)){
     //delete aready added files
     RemoveUpload($data);
     echo '{"Message":"#Error Adding New Gateway"}';
  }else{
//code to insert new payment gateway
 echo '{"GID":'.$ins.',"Message":"*'.$paygatenametb.' Payment Gateway Added Successfully"}';
  }
 
 }else{
     //get the old details
     $olddet = $dbo->SelectFirstRow("thirdparty_tb","","ID=".$gid);
     if(!is_array($olddet)){
        RemoveUpload($data);
        echo '{"Message":"#Payment Gateway Update Failed, Gateway not Found"}';
     }
     
    $upd = $dbo->Update("thirdparty_tb",$data,"ID=".$gid);
    //exit ($upd);
    if(!is_array($upd)){
        //if the old is not same as new, remove the newly added
        if($olddet["Name"] != $data["Name"])RemoveUpload($data);
        echo '{"Message":"#Error Updating Payment Gateway - '.$upd.'"}';
    }else{
        if($olddet["Name"] != $data["Name"])RemoveUpload($olddet);
            //code to update existing gateway
     echo '{"GID":'.$gid.',"Message":"*'.$paygatenametb.' Payment Gateway Updated Successfully"}';
    }
     
 }

 ?>