<?php
session_start();
if (isset($_POST["paramValues"])) {


    $paramValues = json_decode($_POST["paramValues"]);
    //echo json_encode($paramValues->FTA);


    $claimStatus = $paramValues->inlineRadioOptions;
    $empId = $paramValues->empId;
    $presentDate = $paramValues->presentDate;
    $DepuationAllowance = $paramValues->DepuationAllowance;
    $DaAmount = $paramValues->DaAmount;
    $hotelBill = $paramValues->hotelBill;
    $otherBill = $paramValues->otherBill;
    $TotalAmount = $paramValues->TotalAmount;
    $deductedAmount = $paramValues->loggedInUserDeductAmount;
    $totalDeductedAmount = $paramValues->allTotalDeductedAmount;
    $deductedReason = $paramValues->Reason;
    $rejectReason = $paramValues->Reason;
    $EditedDate = $paramValues->report_date;
    $totalDistance = $paramValues->totalDistance;

    $distanceArray = $paramValues->distance;
    $projectArray = $paramValues->project;
    $stageOfAuditArray = $paramValues->stageOfAudit;
    $ftaArray = $paramValues->FTA;
    $rowIdArray = $paramValues->rowId;
    $finalLoopSubmitData=$paramValues->finalLoopSubmitData;






    $loggedInUserID = $_SESSION['userId'];
    $loggedInUserName = $_SESSION['userName'];
    $loggedInUserDepartment = $_SESSION['teamLeads'];
   
    $claimStatusUpdatedBy = $loggedInUserID . "," . $loggedInUserName;
    $uniqueID = $empId . '_' . $presentDate;
    
    $tlTesfJson = json_encode([
    "rowId" => $rowIdArray,
    "fta" => $ftaArray
    ]);
    
    $tlTesf2ClaimJson = json_encode([
    "CLAIM_STATUS" => $claimStatus,
    "TL_APPROVED_DEPUTATION_ALLOWANCE" => $DepuationAllowance,
    "TL_APPROVED_DA_AMOUNT" => $DaAmount,
    "TL_APPROVED_HOTEL_BILLS" => $hotelBill,
    "TL_APPROVED_OTHER_BILLS" => $otherBill,
    "TL_APPROVED_FINAL_AMOUNT" => $TotalAmount,
    "TL_APPROVED_DATE" => $EditedDate,
    "TL_DEDUCTED_AMOUNT" => $deductedAmount,
    "TOTAL_DEDUCTED_AMOUNT" => $totalDeductedAmount,
    "TL_DEDUCTED_REASON" => $deductedReason,
    "FINANCE_APPROVED_DEPUTATION_ALLOWANCE" => $DepuationAllowance,
    "FINANCE_APPROVED_DA_AMOUNT" => $DaAmount,
    "FINANCE_APPROVED_HOTEL_BILLS" => $hotelBill,
    "FINANCE_APPROVED_OTHER_BILLS" => $otherBill,
    "FINANCE_APPROVED_FINAL_AMOUNT" => $TotalAmount,
    "CLAIM_STATUS_UPDATED_BY" => $claimStatusUpdatedBy,
    "UNIQUE_ID" => $uniqueID
    ]);
    
    $financeTesfJson = json_encode([
    "rowId" => $rowIdArray,
    "distance" => $distanceArray,
    "fta" => $ftaArray
    ]);
    
    
    $financeTesf2ClaimJson = json_encode([
    "CLAIM_STATUS" => $claimStatus,
    "TOTAL_DISTANCE" => $totalDistance,
    "FINANCE_EMP_ID" => $loggedInUserID,
    "FINANCE_EMP_NAME" => $loggedInUserName,
    "FINANCE_APPROVED_DATE" => $EditedDate,
    "FINANCE_APPROVED_DEPUTATION_ALLOWANCE" => $DepuationAllowance,
    "FINANCE_APPROVED_DA_AMOUNT" => $DaAmount,
    "FINANCE_APPROVED_HOTEL_BILLS" => $hotelBill,
    "FINANCE_APPROVED_OTHER_BILLS" => $otherBill,
    "FINANCE_APPROVED_FINAL_AMOUNT" => $TotalAmount,
    "FINANCE_DEDUCTED_AMOUNT" => $deductedAmount,
    "TOTAL_DEDUCTED_AMOUNT" => $totalDeductedAmount,
    "FINANCE_DEDUCTED_REASON" => $deductedReason,
    "CLAIM_STATUS_UPDATED_BY" => $claimStatusUpdatedBy,
    "UNIQUE_ID" => $uniqueID
]);
    
    
    
    
    
    
    
    
    
    
    
    

    $obj = new updateClaimStatus();
    switch($claimStatus){
        case CLAIM_TL_REJECTED:// normal reject
        case CLAIM_FINANCE_REJECTED: //or normal reject
        case CLAIM_PERMANENT_TL_REJECT: //or permanent reject
        case CLAIM_PERMANENT_FINANCE_REJECT: //or permanent reject
            $obj->rejectClaim($empId,$presentDate, $claimStatus, $rejectReason, $EditedDate, $claimStatusUpdatedBy, $loggedInUserDepartment, $loggedInUserID, $loggedInUserName);
            break;
        case CLAIM_PAID:
            $obj->paid_Claim($empId,$presentDate, $claimStatus, $EditedDate, $claimStatusUpdatedBy);
            break;
        case CLAIM_UNDO:
            $obj->undo_Claim($empId,$presentDate, $claimStatus, $loggedInUserDepartment);
            break;
        case CLAIM_TL_APPROVED:
        case CLAIM_FINANCE_APPROVED://or
            $obj->approveClaim(
            $empId,
            $presentDate,
            $tlTesfJson,
            $tlTesf2ClaimJson,
            $financeTesfJson,
            $financeTesf2ClaimJson,
            $finalLoopSubmitData
        );
            break;
    }

}else {
  header('location: ../../login.php');
}

//     $obj = new updateClaimStatus();
// $obj->updateClaim("200424", "2","2020-08-01","350", "No","0", "sdsd", "TL", "180291", "sai", "2020-09-23","180291sai","0","0", "reas");
class updateClaimStatus
{
    function __construct()
    {
        require_once dirname(__DIR__) . '../../php/DB_Connect.php';
        $DBclassObject = new DB_conncect;
        $this->db = $DBclassObject->connectToDB();
        $this->db_Pdo = $DBclassObject->connectToDBVia_PDO();
    }
    function approveClaim(
        $empId, $siteVisitDate,$tlTesfJson,$tlTesf2ClaimJson,$financeTesfJson,$financeTesf2ClaimJson,$updateFNCStatus
    )
    {
        $actionStatus="Approve";
        $uniqueID = $empId . '_' . $presentDate;
        $updateFNCStatus=0;
        $fortNightName="fortNight";
        $query_tl_finance = $this->db->prepare("CALL update_claim_by_tl_finance (?,?,?,?,?,?,?,?,?)");
        try {
                if ($loggedInUserDepartment == TL_DEPARTMENT) {
                    $department="TL";
                    $query_tl_finance->bind_param("ssssssiis",$empId, $siteVisitDate,$actionStatus,$tlTesfJson,$tlTesf2ClaimJson, $department,$updateFNCStatus,$updateFNCStatus,$fortNightName);
                } elseif ($loggedInUserDepartment == FINANCE_DEPARTMENT) {
                    $department="Finance";
                    $query_tl_finance->bind_param("ssssssiis",$empId, $siteVisitDate,$actionStatus,$financeTesfJson,$financeTesf2ClaimJson, $department,$updateFNCStatus,$updateFNCStatus,$fortNightName);
                }
                
                 if($query_tl_finance->execute()){
                        echo  "UPDATED";
                    }else{
                        echo "FAILURE";
                    }
            } catch (mysqli_sql_exception $e) {
                echo "FAILURE";
            }
    }
    function update_fort_night_clame_status($siteVisitDate,$empId){
        $platform="web";
        $queryFortNight=$this->db->prepare("CALL `update_fort_night_claim_status`(?,?,?)");
        $queryFortNight->bind_param("sss", $siteVisitDate,$empId,$platform);
        return $queryFortNight;
    }
    function update_final_payable_value_procedure($siteVisitDate,$empId){
        $fortNight=$this->getFortNight($siteVisitDate);
        $stmnt=$this->db->prepare("CALL `update_final_payable_value`(?,?)");
        $stmnt->bind_param('ss',$empId,$fortNight);
        return $stmnt;
    }

    function construct_tesf_table_Query(
        $distanceArray,
        $projectArray,
        $stageOfAuditArray,
        $ftaArray,
        $rowIdArray
    ) {
        $queryBeginning = "INSERT INTO `tesf` (`ID`,`DISTANCE_(KMS)`,`FTA`,`SITE_ID_PROJECT`,`STAGE_OF_VISIT_OR_AUDIT`) VALUES ";
        $queryMid = '';
        for ($i = 0; $i < count($rowIdArray); $i++) {
            if ($i == (count($rowIdArray) - 1)) {
                $queryMid .= "(" . $rowIdArray[$i] . "," . $distanceArray[$i] . "," . $ftaArray[$i] . ",'" . $projectArray[$i] . "','" . $stageOfAuditArray[$i] . "')";
            } else {
                $queryMid .= "(" . $rowIdArray[$i] . "," . $distanceArray[$i] . "," . $ftaArray[$i] . ",'" . $projectArray[$i] . "','" . $stageOfAuditArray[$i] . "'),";
            }
        }
        $queryEnd = " ON DUPLICATE KEY UPDATE `DISTANCE_(KMS)`=VALUES(`DISTANCE_(KMS)`),`FTA`=VALUES(`FTA`), `SITE_ID_PROJECT`=VALUES(`SITE_ID_PROJECT`),`STAGE_OF_VISIT_OR_AUDIT`=VALUES(`STAGE_OF_VISIT_OR_AUDIT`)";
        return $queryBeginning . $queryMid . $queryEnd;
    }

    function construct_tesf_table_Query_for_TL(
        $projectArray,
        $stageOfAuditArray,
        $ftaArray,
        $rowIdArray
    ) {
        $queryBeginning = "INSERT INTO `tesf` (`ID`,`FTA`,`SITE_ID_PROJECT`,`STAGE_OF_VISIT_OR_AUDIT`) VALUES ";
        $queryMid = '';
        for ($i = 0; $i < count($rowIdArray); $i++) {
            if ($i == (count($rowIdArray) - 1)) {
                $queryMid .= "(" . $rowIdArray[$i] . "," . $ftaArray[$i] . ",'" . $projectArray[$i] . "','" . $stageOfAuditArray[$i] . "')";
            } else {
                $queryMid .= "(" . $rowIdArray[$i] . "," . $ftaArray[$i] . ",'" . $projectArray[$i] . "','" . $stageOfAuditArray[$i] . "'),";
            }
        }
        $queryEnd = " ON DUPLICATE KEY UPDATE `FTA`=VALUES(`FTA`), `SITE_ID_PROJECT`=VALUES(`SITE_ID_PROJECT`),`STAGE_OF_VISIT_OR_AUDIT`=VALUES(`STAGE_OF_VISIT_OR_AUDIT`)";
        return $queryBeginning.$queryMid.$queryEnd;
        // echo $queryBeginning . $queryMid . $queryEnd;
    }



    function rejectClaim($empId,$presentDate, $claimStatus, $rejectReason, $EditedDate, $claimStatusUpdatedBy, $loggedInUserDepartment, $loggedInUserID, $loggedInUserName)
    {
        
        try{
            $fortNightQuery=$this->update_fort_night_clame_status($presentDate,$empId);
            
            $uniqueID = $empId . '_' . $presentDate;
            if ($loggedInUserDepartment == FINANCE_DEPARTMENT) {
                $query = $this->db->prepare("UPDATE `tesf-2` SET `CLAIM_STATUS`=?, `REJECT_REASON`=?, `TL_OR_FINANCE_REJECTED_DATE`=?, `CLAIM_STATUS_UPDATED_BY`=?, `FINANCE_EMP_NAME`=?, `FINANCE_EMP_ID`=?  WHERE `UNIQUE_ID`=?");
                $query->bind_param("issssss", $claimStatus, $rejectReason, $EditedDate, $claimStatusUpdatedBy, $loggedInUserName, $loggedInUserID, $uniqueID);
                $finalPayableValStmt=$this->update_final_payable_value_procedure($presentDate, $empId);
                $this->db_Pdo->beginTransaction();
                        $stmt1Excn=$query->execute();
                        $stmt2Excn=$fortNightQuery->execute();
                        $stmt3Excn=$finalPayableValStmt->execute();
                $this->db_Pdo->commit();
                if($stmt1Excn && $stmt2Excn && $stmt3Excn){
                    echo "UPDATED";
                }else{
                    echo "FAILURE";
                }
                
            } elseif($loggedInUserDepartment == TL_DEPARTMENT) {
                $query = $this->db->prepare("UPDATE `tesf-2` SET `CLAIM_STATUS`=?, `REJECT_REASON`=?, `TL_OR_FINANCE_REJECTED_DATE`=?, `CLAIM_STATUS_UPDATED_BY`=?  WHERE `UNIQUE_ID`=?");
                $query->bind_param("issss", $claimStatus, $rejectReason, $EditedDate, $claimStatusUpdatedBy, $uniqueID);
                $this->db_Pdo->beginTransaction();
                        $stmt1Excn=$query->execute();
                        $stmt2Excn=$fortNightQuery->execute();
                $this->db_Pdo->commit();
                if($stmt1Excn && $stmt2Excn){
                    echo "UPDATED";
                }else{
                    echo "FAILURE";
                }
            }
        }catch(PDOException $e){
            // roll back the transaction if something failed
                    $this->db_Pdo->rollback();
                    echo "FAILURE";
                    //      return  "Error: " . $e->getMessage();
        }
    }


    function paid_Claim($empId,$presentDate, $claimStatus, $EditedDate, $claimStatusUpdatedBy)
    {
        $uniqueID = $empId . '_' . $presentDate;
        $query = $this->db->prepare("UPDATE `tesf-2` SET `CLAIM_STATUS`=?, `PAID_DATE`=?, `PAID_BY`=?  WHERE `UNIQUE_ID`=?");
        $query->bind_param("isss", $claimStatus, $EditedDate, $claimStatusUpdatedBy, $uniqueID);
        $fortNightQuery=$this->update_fort_night_clame_status($presentDate,$empId);
        $finalPayableValStmt=$this->update_final_payable_value_procedure($presentDate, $empId);
        try{
            $this->db_Pdo->beginTransaction();
            	$stmt1Excn=$query->execute();
            	$stmt2Excn=$fortNightQuery->execute();
            	$stmt3Excn=$finalPayableValStmt->execute();
            $this->db_Pdo->commit();
            if($stmt1Excn && $stmt2Excn && $stmt3Excn){
                echo  "UPDATED";
            }else{
                echo "FAILURE";
            }
        }catch(PDOException $e){
            // roll back the transaction if something failed
            $this->db_Pdo->rollback();
            echo "FAILURE";
            //      return  "Error: " . $e->getMessage();
        }
    }
     function undo_Claim($empId,$presentDate, $claimStatus, $loggedInUserDepartment)
    {
        try{
            $fortNightQuery=$this->update_fort_night_clame_status($presentDate,$empId);
            $uniqueID = $empId . '_' . $presentDate;
            if ($loggedInUserDepartment == FINANCE_DEPARTMENT) {
                $claimStatus=CLAIM_TL_APPROVED;
                $query = $this->db->prepare("UPDATE `tesf-2` SET `CLAIM_STATUS`=? WHERE `UNIQUE_ID`=?");
                $query->bind_param("is", $claimStatus, $uniqueID);
                $finalPayableValStmt=$this->update_final_payable_value_procedure($presentDate,$empId);
                $this->db_Pdo->beginTransaction();
                    $stmt1Excn=$query->execute();
                    $stmt2Excn=$fortNightQuery->execute();
                    $stmt3Excn=$finalPayableValStmt->execute();
                $this->db_Pdo->commit();
                if($stmt1Excn && $stmt2Excn && $stmt3Excn){
                    echo "UPDATED";
                }else{
                    echo "FAILURE";
                }
            }elseif($loggedInUserDepartment == TL_DEPARTMENT){
                $claimStatus=CLAIM_PENDING;
                $query = $this->db->prepare("UPDATE `tesf-2` SET `CLAIM_STATUS`=? WHERE `UNIQUE_ID`=?");
                $query->bind_param("is", $claimStatus, $uniqueID);
                $this->db_Pdo->beginTransaction();
                    $stmt1Excn=$query->execute();
                    $stmt2Excn=$fortNightQuery->execute();
                $this->db_Pdo->commit();
                if($stmt1Excn && $stmt2Excn){
                    echo "UPDATED";
                }else{
                    echo "FAILURE";
                }
                
            }
        }catch(PDOException $e){
            // roll back the transaction if something failed
                    $this->db_Pdo->rollback();
                    echo "FAILURE";
                    //      return  "Error: " . $e->getMessage();
        }
    }
    private function  getFortNight($siteVisitDate){
    	$dateArray=explode("-",$siteVisitDate);
        $year=$dateArray[0];
        $monthNumber= $dateArray[1];
        $day=$dateArray[2];
        $monthName=$this->getMonthName($monthNumber); 
        $fnType=$this->getFnType($day);
        
        return $year."-".$monthName."-".$fnType;
    }
    
    private function getMonthName($monthNuber){
      $monthName=date('F',mktime(0,0,0,$monthNuber,12));// parameters (sec, minuts, hours, month, day)
      return $monthName;
    }
    private function getFnType($day){
        return $day > 15 ? "2nd FN":"1st FN";
    }
}
