<?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;






    $loggedInUserID = $_SESSION['userId'];
    $loggedInUserName = $_SESSION['userName'];
    $loggedInUserDepartment = $_SESSION['teamLeads'];
   
    $claimStatusUpdatedBy = $loggedInUserID . "," . $loggedInUserName;
    // $uniqueID = $empId . '_' . $presentDate;

    $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->updateClaim(
            $empId,$presentDate,
            $claimStatus,
            $TotalAmount,
            $DepuationAllowance,
            $DaAmount,
            $hotelBill,
            $otherBill,
            $loggedInUserDepartment,
            $loggedInUserID,
            $loggedInUserName,
            $EditedDate,
            $claimStatusUpdatedBy,
            $deductedAmount,
            $totalDeductedAmount,
            $deductedReason,
            $totalDistance,
            $distanceArray,
            $projectArray,
            $stageOfAuditArray,
            $ftaArray,
            $rowIdArray
        );
            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 updateClaim(
        $empId,
        $presentDate,
        $claimStatus,
        $TotalAmount,
        $DepuationAllowance,
        $DaAmount,
        $hotelBill,
        $otherBill,
        $loggedInUserDepartment,
        $loggedInUserID,
        $loggedInUserName,
        $EditedDate,
        $claimStatusUpdatedBy,
        $deductedAmount,
        $totalDeductedAmount,
        $deductedReason,
        $totalDistance,
        $distanceArray,
        $projectArray,
        $stageOfAuditArray,
        $ftaArray,
        $rowIdArray
    ) // here  $Reason is not used, it need to insert
    {
        $constrectQuery;
        $querytesf;
        $uniqueID = $empId . '_' . $presentDate;
        $constrectQuery = $this->construct_tesf_table_Query_for_TL($projectArray, $stageOfAuditArray, $ftaArray, $rowIdArray);
        $fortNightQuery=$this->update_fort_night_clame_status($presentDate,$empId);
        try {
                if ($loggedInUserDepartment == TL_DEPARTMENT) {
                    $constrectQuery=$this->construct_tesf_table_Query_for_TL($projectArray,$stageOfAuditArray, $ftaArray,$rowIdArray);
                    $querytesf=$this->db->prepare($constrectQuery);
                    $query = $this->db->prepare("UPDATE `tesf-2` SET `CLAIM_STATUS`=?, `TL_APPROVED_DEPUTATION_ALLOWANCE`=?, `TL_APPROVED_DA_AMOUNT`=?, `TL_APPROVED_HOTEL_BILLS`=?,`TL_APPROVED_OTHER_BILLS`=?, `TL_APPROVED_FINAL_AMOUNT`=?, `TL_APPROVED_DATE`=?, `TL_DEDUCTED_AMOUNT`=?,`TOTAL_DEDUCTED_AMOUNT`=?,`TL_DEDUCTED_REASON`=?, `FINANCE_APPROVED_DEPUTATION_ALLOWANCE`=?, `FINANCE_APPROVED_DA_AMOUNT`=?,`FINANCE_APPROVED_HOTEL_BILLS`=?, `FINANCE_APPROVED_OTHER_BILLS`=?, `FINANCE_APPROVED_FINAL_AMOUNT`=?,`CLAIM_STATUS_UPDATED_BY`=?  WHERE `UNIQUE_ID`=?");
                    $query->bind_param("isddddsddssddddss", $claimStatus, $DepuationAllowance, $DaAmount, $hotelBill, $otherBill, $TotalAmount, $EditedDate, $deductedAmount, $totalDeductedAmount, $deductedReason, $DepuationAllowance, $DaAmount,$hotelBill, $otherBill, $TotalAmount, $claimStatusUpdatedBy, $uniqueID);
                    $this->db_Pdo->beginTransaction();
                        $stmt1Excn=$query->execute();
                        $stmt2Excn=$querytesf->execute();
                        $stmt3Excn=$fortNightQuery->execute();
                    $this->db_Pdo->commit();
                    if($stmt1Excn && $stmt2Excn && $stmt3Excn){
                        echo "UPDATED";
                    }else{
                        echo "FAILURE";
                    }
                } elseif ($loggedInUserDepartment == FINANCE_DEPARTMENT) {
                    $constrectQuery=$this->construct_tesf_table_Query($distanceArray,$projectArray,$stageOfAuditArray, $ftaArray,$rowIdArray);
                    $querytesf=$this->db->prepare($constrectQuery);
                    $query = $this->db->prepare("UPDATE `tesf-2` SET `CLAIM_STATUS`=?,`TOTAL_DISTANCE`=?,`FINANCE_EMP_ID`=?,`FINANCE_EMP_NAME`=?,`FINANCE_APPROVED_DATE`=?,`FINANCE_APPROVED_DEPUTATION_ALLOWANCE`=?,`FINANCE_APPROVED_DA_AMOUNT`=?,`FINANCE_APPROVED_HOTEL_BILLS`=?,`FINANCE_APPROVED_OTHER_BILLS`=?,`FINANCE_APPROVED_FINAL_AMOUNT`=?, `FINANCE_DEDUCTED_AMOUNT`=?,`TOTAL_DEDUCTED_AMOUNT`=?,`FINANCE_DEDUCTED_REASON`=?, `CLAIM_STATUS_UPDATED_BY`=? WHERE `UNIQUE_ID`=?");
                    $query->bind_param("idssssddddddsss", $claimStatus,$totalDistance,$loggedInUserID, $loggedInUserName, $EditedDate, $DepuationAllowance, $DaAmount, $hotelBill, $otherBill, $TotalAmount, $deductedAmount, $totalDeductedAmount, $deductedReason, $claimStatusUpdatedBy, $uniqueID);
                    $finalPayableValStmt=$this->update_final_payable_value_procedure($presentDate, $empId);
                    $this->db_Pdo->beginTransaction();
                        $stmt1Excn=$query->execute();
                        $stmt2Excn=$querytesf->execute();
                        $stmt3Excn=$fortNightQuery->execute();
                        $stmt4Excn=$finalPayableValStmt->execute();
                    $this->db_Pdo->commit();
                    if($stmt1Excn && $stmt2Excn && $stmt3Excn && $stmt4Excn){
                        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 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){
        $time=strtotime($siteVisitDate);
        $siteVisitedYear=date('Y',$time);
        $stmnt=$this->db->prepare("CALL `update_final_payable_value`(?,?)");
        $stmnt->bind_param('ss',$empId,$siteVisitedYear);
        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();
        }
    }
}
