<?php
require('../config.php');
require '../../../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);


if (isset($_POST['importAttendanceChunk'])) {

    $data = json_decode($_POST['data'], true);

    $dataLength = sizeof($data);
    $insertCount = 0;
    $empExist = '';
    foreach ($data as $inner) {

        $employee_id = trim($inner['employee_id']);
        $attendance_status = trim($inner['attendance_status']);
        $punch_in = trim($inner['punch_in']);
        $punch_out = trim($inner['punch_out']);
        $which_month = trim($inner['which_month']);
        $attendance_change = 0;

        if (!empty($punch_in)) {
            $punch_in = date("h:i A", strtotime($punch_in));
        }
        if (!empty($punch_out)) {
            $punch_out = date("h:i A", strtotime($punch_out));
        }
        if (!empty($which_month)) {
            $which_month = date("M d Y", strtotime($which_month));
        }

        // echo $employee_id . " " . $attendance_status . " " . $punch_in . " " . $punch_out . " " . $which_month . "<br>";

        // ##################################################################
        $jwDate = mysqli_fetch_assoc(mysqli_query($db, "SELECT joining_date, working_status_date, employee_time FROM users WHERE employee_id='$employee_id' "));
        if (!empty($jwDate['joining_date']) && (strtotime($jwDate['joining_date']) > strtotime($which_month))) {
            continue;
        }
        if (!empty($jwDate['working_status_date']) && (strtotime($jwDate['working_status_date']) < strtotime($which_month))) {
            continue;
        }
        // ##################################################################

        $aCount = mysqli_num_rows(mysqli_query($db, "SELECT * FROM `attendance` WHERE `employee_id`='$employee_id' AND str_to_date(`which_month`, '%M %d %Y')=str_to_date('$which_month', '%M %d %Y') "));

        $q = false;
        if ($aCount == 0) {

            if(!in_array($attendance_status, ['Holiday', 'Week Off', 'Work From Home', 'Worked on Week Off', 'Worked on Week Off HD'])) {
  
                $policy_applicable_from = date("Y-m", strtotime($which_month));
                // $work_policy = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM work_policy WHERE employee_id='$employee_id' AND applicable_from<='$policy_applicable_from' AND (CASE WHEN COALESCE(applicable_to, '')='' THEN DATE_FORMAT(CURRENT_DATE, '%Y-%m') ELSE applicable_to END)>=DATE_FORMAT(CURRENT_DATE, '%Y-%m') "));

                $work_policy = mysqli_fetch_assoc(mysqli_query($db, "SELECT wp.*, u.department FROM work_policy wp INNER JOIN users u ON wp.employee_id = u.employee_id WHERE wp.employee_id='$employee_id' AND wp.applicable_from<='$policy_applicable_from' AND (CASE WHEN COALESCE(wp.applicable_to, '')='' THEN DATE_FORMAT(CURRENT_DATE, '%Y-%m') ELSE wp.applicable_to END)>=DATE_FORMAT(CURRENT_DATE, '%Y-%m')"));


                if (empty($work_policy)) {
                    $check_punch_in = '10:00 AM';
                    $check_punch_out = '6:55 PM';
                    $check_hours_seconds = strtotime($check_punch_in) - strtotime($check_punch_out);
                    $half_day_time = "04:00"; // Default half day hours in seconds
                    list($hours, $minutes) = explode(':', $half_day_time);
                    $check_half_day_hours_seconds = ($hours * 3600) + ($minutes * 60);
                } else {
                    $check_punch_in = date("h:i A", strtotime($work_policy['relaxation_from']));
                    $check_punch_out = date("h:i A", strtotime($work_policy['relaxation_to']));
                    $check_hours_seconds = strtotime($check_punch_out) - strtotime($check_punch_in);
                    $half_day_time = !empty($work_policy['half_day_hours']) ? $work_policy['half_day_hours'] : "04:00"; // Default half day hours in seconds
                    list($hours, $minutes) = explode(':', $half_day_time);
                    $check_half_day_hours_seconds = ($hours * 3600) + ($minutes * 60);
                }

                if($work_policy['department'] == '17'){
                    $check_hours_seconds = 12600; // 3.5 hours in seconds
                }

                // Convert working hours to seconds for proper comparison
                $punch_in_time  = strtotime($punch_in);
                $punch_out_time = strtotime($punch_out);
                $check_in_time  = strtotime($check_punch_in);
                $check_out_time = strtotime($check_punch_out);
                $worked_seconds = $punch_out_time - $punch_in_time;


                // $leaveDate = date("d M Y", strtotime($which_month));
                $working_days = json_decode($work_policy['working_days'], true);
                $dayOfWeek = date('l', strtotime($which_month));
                if (is_array($working_days) && !empty($working_days)) {
                    if (!in_array($dayOfWeek, $working_days)) {
                        if ($punch_in == '' && $punch_out == '') {
                            $attendance_status = 'Week Off';
                        } else if ($punch_in == '' || $punch_out == '' || ($punch_in_time > $check_in_time) || ($punch_out_time < $check_out_time)) {
                            // $attendance_status = 'Worked on Week Off HD';
                        } else {
                            // $attendance_status = 'Worked on Week Off';
                        }
                    } else {
                        if ($punch_in == '' || $punch_out == '' || $worked_seconds < $check_half_day_hours_seconds) {
                            $attendance_status = 'Absent';
                        } else if (($punch_in_time > $check_in_time || $punch_out_time < $check_out_time || $worked_seconds < $check_hours_seconds) && $work_policy['department'] != '17') {
                            $attendance_status = 'Half Day';
                        } else if ($work_policy['department'] == '17' && $worked_seconds < $check_hours_seconds) {
                            $attendance_status = 'Half Day';
                        }
                        else {
                            $attendance_status = 'Present';
                        }
                    }
                } else {
                    if ($dayOfWeek == 'Sunday') {
                        if ($punch_in == '' && $punch_out == '') {
                            $attendance_status = 'Week Off';
                        } else if ($punch_in == '' || $punch_out == '' || (($punch_in_time > $check_in_time) || ($punch_out_time < $check_out_time))) {
                            // $attendance_status = 'Worked on Week Off HD';
                        } else {
                            // $attendance_status = 'Worked on Week Off';
                        }
                    } else {
                        if ($punch_in == '' || $punch_out == '' || $worked_seconds < $check_half_day_hours_seconds) {
                            $attendance_status = 'Absent';
                        } else if (($punch_in_time > $check_in_time || $punch_out_time < $check_out_time || $worked_seconds < $check_hours_seconds) && $work_policy['department'] != '17') {
                            $attendance_status = 'Half Day';
                        } else if ($work_policy['department'] == '17' && $worked_seconds < $check_hours_seconds) {
                            $attendance_status = 'Half Day';
                        } else {
                            $attendance_status = 'Present';
                        }
                    }
                }

            }

            $requestLeave = mysqli_query($db, "SELECT * from request_leave where employee_id='$employee_id' and leave_status='1' and leave_type='Work From Home' and created_at>now() - interval 30 day ");
            if (mysqli_num_rows($requestLeave) > 0) {

                while ($reqLeave = mysqli_fetch_assoc($requestLeave)) {

                    if (strpos($reqLeave['leave_date'], 'to') == false) {

                        if (strtotime($reqLeave['leave_date']) == strtotime($which_month)) {
                            $gid = mysqli_fetch_assoc(mysqli_query($db, "select id from attendance order by id desc limit 1"));
                            $gid = $gid['id']++;
                            $qi = mysqli_query($db, "INSERT into attendance_change (attendance_id,employee_id,attendance_status,punch_in,punch_out,which_month) values ('$gid','$employee_id', '$attendance_status', '$punch_in', '$punch_out', '$which_month')  ");
                            $attendance_change = 1;
                            $attendance_status = 'Work From Home';
                            break;
                        }
                    } else {
                        $exDate = explode("to", $reqLeave['leave_date']);

                        if ((strtotime(trim($exDate[0])) <= strtotime($which_month)) && (strtotime(trim($exDate[1])) >= strtotime($which_month))) {
                            $gid = mysqli_fetch_assoc(mysqli_query($db, "select id from attendance order by id desc limit 1"));
                            $gid = $gid['id']++;
                            $qi = mysqli_query($db, "INSERT into attendance_change (attendance_id,employee_id,attendance_status,punch_in,punch_out,which_month) values ('$gid','$employee_id', '$attendance_status', '$punch_in', '$punch_out', '$which_month')  ");
                            $attendance_change = 1;
                            $attendance_status = 'Work From Home';
                            break;
                        }
                    }
                }
            }

            $holidays = mysqli_num_rows(mysqli_query($db, "SELECT * from holidays where date='$which_month' "));
            if ($holidays == 1) {
                $attendance_status = 'Holiday';
            }

            $q = mysqli_query($db, "INSERT INTO `attendance` (`employee_id`, `attendance_status`, `punch_in`, `punch_out`, `which_month`, `attendance_change`) VALUES ('$employee_id', '$attendance_status', '$punch_in', '$punch_out', '$which_month', $attendance_change) ");
        } else {
            $empExist .= $employee_id . ", ";
            $q = false;
        }

        if ($q) {
            $insertCount++;
        }
    }

    if ($dataLength == $insertCount) {
        echo "<script>alert('All Data imported Successfully !');</script>";
    } else if (!empty(trim($empExist, ','))) {
        echo "<script>alert('" . $empExist . " These Employee id data already exist in database and other data imported Successfully !');</script>";
    } else {
        echo "<script>alert('" . ($dataLength - $insertCount) . " rows not imported !');</script>";
    }
    // echo "<script>location.href='../importAttendance';</script>";
    exit();
}
