<?php

require('../config.php');
require_once "../salaryCodeCalculate.php";
require_once('../salaryCode.php');

// Fetch records from database  
$financial_year_start = $_GET['from'];
$financial_year_end = $_GET['to'];

$financial_year_start = date("Y-m", strtotime($financial_year_start));
$financial_year_end = date("Y-m", strtotime($financial_year_end));


while($financial_year_start <= $financial_year_end) {
    $firstDayLast = date("Y-m-01", strtotime($financial_year_start));
    $lastDayLast = date("Y-m-t", strtotime($financial_year_start));
    $sameMonth = date("Y-m", strtotime($firstDayLast));
    
    $join_month = date("Y-m", strtotime($firstDayLast));
    $wsDate = date("Y-m", strtotime($lastDayLast));
    $query = "SELECT u.employee_id, u.name, u.department, u.joining_date, u.working_status_date, '$firstDayLast' as firstDayLast, '$lastDayLast' as lastDayLast
                FROM users as u 
                JOIN attendance AS a ON u.employee_id = a.employee_id 
                WHERE (STR_TO_DATE(a.which_month, '%M %d %Y') BETWEEN '$firstDayLast' AND '$lastDayLast')
                AND (COALESCE(u.joining_date,'') = '' OR DATE_FORMAT(STR_TO_DATE(u.joining_date, '%Y-%m-%d'),'%Y-%m') <= '$join_month')
                AND (COALESCE(u.working_status_date,'') = '' OR DATE_FORMAT(STR_TO_DATE(u.working_status_date, '%Y-%m-%d'),'%Y-%m') >= '$wsDate')
                GROUP BY u.id 
                ORDER BY u.id ASC";
    $users = mysqli_query($db, $query);
    
    $newFirstDayLast = $firstDayLast;
    $newLastDayLast = $lastDayLast;
    while ($user = mysqli_fetch_assoc($users)) {
    
        $s_code = salaryCode($user, $firstDayLast, $firstDayLast);

        $netCTC = json_encode($s_code['monthSalaryDetails'] ?? []);
        $netPayable = json_encode($s_code['working_salary'] ?? []);
        $leaves = json_encode($s_code['leaves'] ?? []);
        $deduction = json_encode($s_code['deduction'] ?? []);
        $final_salary = json_encode($s_code['final_salary'] ?? []);

    
        $exist = mysqli_query($db, "DELETE FROM employee_yearly_salary WHERE employee_id='$user[employee_id]' and which_month='$sameMonth'");

        $q = mysqli_query($db, "INSERT INTO `employee_yearly_salary` (`employee_id`, `which_month`, `net_ctc`, `net_payable`, `leaves`, `deduction`, `final_salary`) VALUES ('$user[employee_id]', '$sameMonth', '$netCTC', '$netPayable', '$leaves', '$deduction', '$final_salary')");

        if (!$q) {
            echo json_encode(["status" => 500, 'message' => 'Some Error Occurred!', 'error' => mysqli_error($db)]);
            exit();
        }
    }
    
    $financial_year_start = date("Y-m", strtotime("$financial_year_start + 1 month"));
}
echo json_encode(["status" => 200, 'message' => 'All Data Saved Successfully!']);


