<?php
session_start();

require_once '../Config/Database.php';
require_once '../Model/Payroll.php';
require_once '../Model/Employee.php';
$payroll = new Payroll();
$employee = new Employee();
// Settings
$current_month = date('m');

$payrolls = $payroll->read_all_payrolls();
if(isset($_GET['all_payrolls'])){
    echo json_encode(
        array("data"=>$payrolls)
    ); 
}

if(isset($_POST['add_payroll'])){
    $employee_name = $_POST['employee_name'];
    $employee_details = $employee->get_employee_by_name($employee_name);
    $employee_id = $employee_details[0]['employee_id'];
    $total = 0;
    $employee_achievements = $employee->read_user_reward($employee_id,$current_month);
    if($employee_achievements){
        foreach($employee_achievements as $key){
            $total += floatval($key['achievement_reward']);
        }
    }else{
        $total = 0;
    }
    
    $basic_salary = $_POST['basic_salary'];
    $commission = $total;
    $payment_date = $_POST['payment_date'];
    $tax = $_POST['tax'];
    $initiator = $_SESSION['employee_id'];
    $data = array(
        "employee_id"=>$employee_id,
        "basic_salary"=>$basic_salary,
        "reward"=>$commission,
        "payment_date"=>$payment_date,
        "tax"=>$tax,
        "initiator"=>$initiator
    );
    $success = $payroll->add_payroll($data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['update_payroll'])){
    $payroll_id = $_POST['payroll_id'];
    $payroll_name = $_POST['payroll_name'];
    $data = array(
        "payroll_name"=>$payroll_name
    );
    $key = array(
        "payroll_id"=>$payroll_id
    );
    $success = $payroll->update_payroll($key,$data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}


if(isset($_POST['remove_payroll'])){
    $payroll_id = $_POST['payroll_id'];
    $data = $payroll->remove_payroll($payroll_id);
    if(!$data){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}