<?php
$response = array();
require_once __DIR__ . '/catchexception.php';
// include db connect class
require_once __DIR__ . '/db_config.php';
// $con is provided by db_config.php via DatabaseManager
 
   // check for post data    
	$clientid = $_POST['clientid'];
    $branchcode = $_POST['branchcode'];
    $process = $_POST['process'];
    $branchname = $_POST['branchname'];
    $noofdevices = $_POST['noofdevices'];
    $approvedstatus = $_POST['approvedstatus']; 
    // $clientid ='1';
    // $branchcode ='5';
    // $process ='approve';
    // $branchname = 'My test3';
    // $noofdevices ='5';
    // $approvedstatus = '1';
 try{
    $getbranchcount=1;
      //Get unique count 
      $rowcntqry="SELECT coalesce(count(*),0) as count from tblbranchmaster where   branchcode=$1   ;";
      $resultmax =  pg_prepare($con,'countquery',$rowcntqry); 
      $data = [$branchcode];
      $res = pg_execute($con,'countquery',$data);
      if (!empty($res)) {
          if (pg_num_rows($res) > 0) {   
            while ($row = pg_fetch_assoc($res)) {
                $getbranchcount= $row["count"] ;
            }
          }
      }

    if($process == 'approve'){
        if($getbranchcount > 0){ 
            $originator='Device Approval for branchcode from Trios'.$branchcode;
            $query = "INSERT into tbluserlog(userid,createdtime,originator) values ($1,now(),$2)  ";
            $result1 = pg_prepare($con,"query",$query);
            $data = [$clientid,$originator];
            $res = pg_execute($con,"query",$data);

            $branchapproval = "INSERT into tblbranchapprovaltransaction(branchcode,noofdevices,usercode,createddate) values ($1,$2,$3,now())  ";
            $result1 = pg_prepare($con,"branchapproval",$branchapproval);
            $data = [$branchcode,$noofdevices,$clientid];
            $res = pg_execute($con,"branchapproval",$data);
           

            $varqueryupdate1 = "UPDATE  tblbranchmaster  set updateddate=NOW(),approvestatus=$1
            where branchcode=$2 ";
            $result1 = pg_prepare($con, 'updateval1',$varqueryupdate1);
            $data = [$approvedstatus,$branchcode];
            $resval = pg_execute($con, 'updateval1',$data);  
            if (!empty($resval)) { 
                $response["success"] = 1;
            }else{
                $response["success"] = 0;
            } 
            echo json_encode($response);
        }
      
    } 
    else {
        $response["success"] = 0;
        echo json_encode($response);
    }
			
				  
mch_db_release($con);
}
//catch exception
catch(Exception $e) {
mch_db_release($con);
echo 'Message: ' .$e->getMessage();
}
?>