<?php
//session
session_start();
if(isset($_POST['paramValues'])){
    $paramValuesObj=json_decode($_POST['paramValues']);
    // $paramValuesObj->createdBy=$_SESSION['userId'].", ".$_SESSION["userName"];
    $classObj=new insertAdvanceAmntDetails();
    $classObj->createFnForEmployeesWhoDntHave($paramValuesObj);
}else{
    echo "NO RESULT-FOUND";
}

class insertAdvanceAmntDetails{
    
    function __construct(){
        require_once dirname(__DIR__).'../../php/DB_Connect.php';
        $dbClassObj=new DB_conncect();
        $this->db=$dbClassObj->connectToDB();
        $this->db_Pdo=$dbClassObj->connectToDBVia_PDO();
    }
    
    function createFnForEmployeesWhoDntHave($paramValuesObj){
       
        $fnInsertObjts=$paramValuesObj->InsertFn;
        $advAmntInsertObjts=$paramValuesObj->advanceAmntDetails;
        $totalFnInsertQueries=count($fnInsertObjts);
        $totalAdvAmntInsertQueries=count($advAmntInsertObjts);
        if(count($fnInsertObjts)>0){
            $this->multiQueries_fn_and_advAmnt_queriesExecution($fnInsertObjts,$advAmntInsertObjts,$totalFnInsertQueries,$totalAdvAmntInsertQueries);
        }else{                                                                      //NO FORTNIGHT INSERTIONS
            $this->advAmnt_queryExecution($advAmntInsertObjts,$totalAdvAmntInsertQueries);
        }
    }
    
    
   function multiQueries_fn_and_advAmnt_queriesExecution($fnInsertObjts,$advAmntInsertObjts,$totalFnInsertQueries, $totalAdvAmntInsertQueries){
        $responseArray=array();
        $fnInsertQuery=$this->fnInsertQueryCreation($fnInsertObjts);
        $advAmntInsertQuery=$this->advanceAmountDetailsQueryCreation($advAmntInsertObjts);
        $stmnt1=$this->db_Pdo->prepare($fnInsertQuery);
        $stmnt2=$this->db_Pdo->prepare($advAmntInsertQuery);
        
        try{
            $this->db_Pdo->beginTransaction();
                $stmnt1Execution=$stmnt1->execute();
                if($stmnt1Execution){
                    $noOfRowsInserted_stmnt1=$stmnt1->rowCount();
                    if($noOfRowsInserted_stmnt1==$totalFnInsertQueries){
                        $stmnt2Execution=$stmnt2->execute();
                        $resultArray=$this->getResultOfAdvAmtQueryExecution($stmnt2Execution,$stmnt2,$totalAdvAmntInsertQueries);
                        $responseArray["message"]=$resultArray["message"];
                        $responseArray['Reason']=$resultArray["Reason"];
                    }else{
                        $responseArray["message"]="FAILURE";
                        $responseArray["Reason"]="NoOf Fn Inserted queries: $noOfRowsInserted_stmnt1 ,Total FnQueries: $totalFnInsertQueries";
                    }
                }else{
                    $responseArray["message"]="FAILURE";
                    $responseArray["Reason"]="FN Insert Query Execution Failed";
                }
            $this->db_Pdo->commit();
        }
        catch(PDOException $e){
            $responseArray['message']="FAILURE";
            $responseArray['Reason']="500 InternalErrro: $e";
        }
        echo json_encode($responseArray);
    }
    
 
    function advAmnt_queryExecution($advAmntInsertObjts,$totalAdvAmntInsertQueries){
        $responseArray=array();
        $advAmntInsertQueries=$this->advanceAmountDetailsQueryCreation($advAmntInsertObjts);
        $stmnt=$this->db_Pdo->prepare($advAmntInsertQueries);
        try{
            $this->db_Pdo->beginTransaction();
                $executionStatus=$stmnt->execute();
            $this->db_Pdo->commit();
            $resultArray=$this->getResultOfAdvAmtQueryExecution($executionStatus,$stmnt,$totalAdvAmntInsertQueries);
            $responseArray["message"]=$resultArray["message"];
            $responseArray['Reason']=$resultArray["Reason"];
        }
        catch(PDOException $e){
            $responseArray['message']="FAILURE";
            $responseArray['Reason']="500 InternalErrro: $e";
        }
        echo json_encode($responseArray);
    }
    
    function fnInsertQueryCreation($fnInsertDataArray){
        $TLApprovedStatus=2;
        $queryStarting="INSERT INTO `fort_night_claims`(`EMP_ID`, `NAME`, `FORTNIGHT`, `FROM_DATE`, `TO_DATE`,`SUBMITION_STATUS`) VALUES";
        $queryEnd='';
        $lastLoopIndex=count($fnInsertDataArray)-1;   
        for($loopIndex=0;$loopIndex<count($fnInsertDataArray);$loopIndex++){
            $queryEnd.="( '".$fnInsertDataArray[$loopIndex]->empId."', 
                                '".$fnInsertDataArray[$loopIndex]->empName."',
                                '".$fnInsertDataArray[$loopIndex]->fortnight."',
                                '".$fnInsertDataArray[$loopIndex]->fromDate."',
                                '".$fnInsertDataArray[$loopIndex]->toDate."',
                                '".$TLApprovedStatus."'";
            if($loopIndex!=$lastLoopIndex){
                $queryEnd.="),";
            }else{
                $queryEnd.=")";
            }
        }
        return $queryStarting.$queryEnd;
    }
    
    function advanceAmountDetailsQueryCreation($advAmntInsertObjts){
        date_default_timezone_set("Asia/Calcutta");
        $createdDate=date('Y-m-d H:i:s'); // year, month, date, hour, minutes, sec
        $createBy=$_SESSION['userId'].", ".$_SESSION["userName"];
        $queryStarting="INSERT INTO `fn_advances`(`EMP_ID`, `FORTNIGHT`, `TRANSACTION_ID`, `ADVANCE`, `ADVANCE_RELEASE_DATE`, `REMARKS`, `CREATED_DATE`, `CREATED_BY`) VALUES ";
        $queryEnd='';
        $lastLoopIndex=count($advAmntInsertObjts)-1;
        for($loopIndex=0;$loopIndex<count($advAmntInsertObjts);$loopIndex++){
            $queryEnd.=" ('".$advAmntInsertObjts[$loopIndex]->{'EMP ID'}."', 
                            '".$advAmntInsertObjts[$loopIndex]->{'FORTNIGHT'}."',
                            '".$advAmntInsertObjts[$loopIndex]->{'TRANSACTION-ID'}."',
                            '".$advAmntInsertObjts[$loopIndex]->{'ADVANCE AMOUNT'}."',
                            '".$advAmntInsertObjts[$loopIndex]->{'ADVANCE RELEASED DATE (YYYY-MM-DD)'}."',
                            '".$advAmntInsertObjts[$loopIndex]->{'REMARKS'}."',
                            '".$createdDate."',
                            '".$createBy."'"; 
            if($loopIndex==$lastLoopIndex){
                $queryEnd.=")";
            }else{
                $queryEnd.="),";
            }
        }
        return $queryStarting.$queryEnd;
    }
    
    function getResultOfAdvAmtQueryExecution($executionStatus,$stmnt,$totalAdvAmntInsertQueries){
        $resultArray=array();
            if($executionStatus){
                $noOfRowsInserted=$stmnt->rowCount();
                if($noOfRowsInserted==$totalAdvAmntInsertQueries){
                    $resultArray["message"]="SUCCESS";
                    $resultArray["Reason"]="";
                }else{
                    $resultArray['message']="FAILURE";
                    $resultArray['Reason']="NoOf AdvanceAmount Inserted queries: $noOfRowsInserted ,Total AdvAmntQueries: $totalAdvAmntInsertQueries";
                }
            }else{
                $resultArray["message"]="FAILURE";
                $resultArray["Reason"]="AdvanceAmountDetails Insert Query Execution Failed";
            }
        return $resultArray;
    }
    
}

?>