<?php

    include("../include/connection.php");
    $json = array();

    if(isset($_POST['uuid'])){
        $uuid = $_POST['uuid'];
    } 
    else{
        $uuid = '';
    }

    $sql = "SELECT * FROM ods WHERE uuid='$uuid' AND status='verified'";
    $result = mysqli_query($link, $sql);
    if($result->num_rows > 0){
        while ($row = $result->fetch_assoc()){
            $u_uname = mysqli_real_escape_string($link, $row['uuid']);
            $br_id = mysqli_real_escape_string($link, $row['uuid']);
        }
    } 
    else{
        $json['status'] = false;
        $json['message'] = 'UUID Mismatch';
        echo json_encode($json, JSON_PRETTY_PRINT);
        exit;
    }

    $empId = $_POST['empId'];

    $sql = "SELECT * FROM `empHoliday` WHERE empId='$empId' AND salarystatus='unpaid'";
    $result = mysqli_query($link, $sql);
    if ($result->num_rows > 0) {
        while ($empHoliday = mysqli_fetch_array($result)) {
        $oldmph = $empHoliday['mph'];
        $oldlop = $empHoliday['lop'];
        $deductedSalary= $empHoliday['deductedsalary'];
        $oldFinalSalary = $empHoliday['finalsalary'];
        }
    } 
    else{
    $json['status'] = false;
    $json['message'] = 'Employee Record not found';
    echo json_encode($json, JSON_PRETTY_PRINT);
    exit;
    }

    $typeOfLeave = $_POST['typeOfLeave'];
    $startDate = date_create($_POST['startDate']);
    $endDate = date_create($_POST['endDate']);
    $diff = date_diff($startDate,$endDate);
    $days= $diff->format("%a");

    if($typeOfLeave=='mph'){
        if($days > $oldmph){
            $json['status'] = false;
            $json['message'] = 'No. of days exceed number of MPH left';
            echo json_encode($json, JSON_PRETTY_PRINT);
            exit;
        }
        $mph = $oldmph - $days;
        $lop = $oldlop;
        $newFinalSalary = $oldFinalSalary;
    }
    else{
        $mph = $oldmph;
        $lop = $oldlop + $days;
        $deductedAmount = $days*($deductedSalary/30);
        $newFinalSalary = $oldFinalSalary -  $deductedAmount;
    }

    $sql = "UPDATE `empHoliday` SET `mph`='$mph',`lop`='$lop',`finalsalary`='$newFinalSalary' WHERE empId='$empId' AND salarystatus='unpaid'";
    $result = mysqli_query($link, $sql);
    if($result) {
      $json['status'] = true;
      $json['message'] = 'Success';
    }
    else{
        $json['status'] = false;
        $json['message'] = 'Incorrect Parameters';
    }

    echo json_encode($json, JSON_PRETTY_PRINT);
    exit;
   
?>