<?php
session_start();
if(isset($_POST["paramValues"])){
    $paramObj=json_decode($_POST["paramValues"]);
    $clsObj= new insertAdditionalAdjustments();
    $clsObj->insertBulkAdditionalAdjustments($paramObj->adjustmentDetails);
}else{
    echo "Result Not Found";
}
class insertAdditionalAdjustments{
 function __construct(){
        require_once dirname(__DIR__).'../../../php/DB_Connect.php';
        $dbClsObj= new DB_conncect();
        $this->db=$dbClsObj->connectToDB();
        $this->db_Pdo=$dbClsObj->connectToDBVia_PDO();
    }
    function insertBulkAdditionalAdjustments($adjustmentDetails){
        $returnArray=array();
        $noOfAdjustmentsNeedToInsert=count($adjustmentDetails);
        $query=$this->getInsertQuery($adjustmentDetails);
        $stmt=$this->db_Pdo->prepare($query);
        try{
            $this->db_Pdo->beginTransaction();
                if($stmt->execute()){
                    $noOfRowsInserted=$stmt->rowCount();
                    if($noOfRowsInserted==$noOfAdjustmentsNeedToInsert){
                        $returnArray["error"]=false;
                        $returnArray["message"]="Successfully Inserted";
                    }else{
                        $returnArray["error"]=true;
                        $returnArray["message"]="Total Adjustments $noOfAdjustmentsNeedToInsert,  No.Of Rows inserted $noOfRowsInserted";
                    }
                }else{
                    $returnArray["error"]=true;
                    $returnArray["message"]="Unable To Execute Insert Query";
                }
            $this->db_Pdo->commit();
        }
        catch(PDOException $e){
            $returnArray["error"]=true;
            $returnArray["message"]="Internal Error 500!";
        }
        echo json_encode($returnArray);
    }
    function getInsertQuery($adjustmentDetails){
        $createdDate=date('Y-m-d H:i:s'); // year, month, date, hour, minutes, sec
        $createdBy=$_SESSION['userId'].", ".$_SESSION["userName"];
        $query="INSERT INTO `fn_adjustments`(`EMP_ID`, `FORTNIGHT`, `TRANSACTION_ID`, `ADJUSTMENT_AMOUNT`,`ADJUSTMENT_RELEASED_DATE`,`REMARKS`, `CREATED_DATE`, `CREATED_BY`) VALUES";
        $lastLoopIndex=count($adjustmentDetails)-1;
        foreach($adjustmentDetails as $currentLoopIndex => $currentLoopObject){
            $query.="('".$currentLoopObject->EmpId."', 
                    '".$currentLoopObject->FortNight."',
                    '".$currentLoopObject->{'T-Id'}."',
                    '".$currentLoopObject->{'Transaction Amount'}."',
                    '".$currentLoopObject->{'Transaction Date'}."',
                    '".$currentLoopObject->Remarks."',
                    '$createdDate',
                    '$createdBy'";
            if($currentLoopIndex != $lastLoopIndex){
                $query.="),";
            }else{
                 $query.=")";// end
            }
        }
        return $query;
    }
}
?>