<?php
require_once "../config.php";

$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['employee_id'])) {

    // Show attendance ##########################
    // $bgcolor = array('' => 'bg-success', '' => 'bg-danger');

    $eid = $data['employee_id'];
    $firstDate = date("Y-m-01", strtotime($data['selectedMonth']));
    $lastDate = date("Y-m-t", strtotime($data['selectedMonth']));
    $events = array();

    $daily_work_sql = <<<EOT
        WITH RECURSIVE date_series AS (
            SELECT DATE('$firstDate') AS date, '$eid' as d_emp_id
            UNION ALL
            SELECT DATE_ADD(date, INTERVAL 1 DAY), d_emp_id
            FROM date_series
            WHERE DATE_ADD(date, INTERVAL 1 DAY) <= '$lastDate'
        ),
        with_week_offs AS (
            SELECT
                t2.id,
                t2.name,
                t1.d_emp_id as employee_id,
                t1.date as work_date,
                t2.employee_time,
                (CASE
                    WHEN COALESCE(t2.work,'')='' and DAYNAME(t1.date) = 'Sunday' THEN 'Week Off'
                    ELSE t2.work
                END) as work
            FROM date_series t1
            LEFT JOIN (
                SELECT 
                    u.name,
                    u.employee_time,
                    d.id,
                    d.employee_id,
                    d.work_date,
                    d.work
                FROM dailyWork d
                INNER JOIN users u ON u.employee_id=d.employee_id
                where d.employee_id='$eid' and d.work_date BETWEEN '$firstDate' AND '$lastDate'
            ) t2 ON t1.date=t2.work_date AND t1.d_emp_id=t2.employee_id
        ),
        with_holidays AS (
            SELECT 
                NULL as id,
                NULL as name,
                '$eid' as employee_id,
                str_to_date(date, '%M %d %Y') as work_date,
                NULL as employee_time,
                title as work
            FROM holidays WHERE (str_to_date(date,'%M %d %Y') BETWEEN '$firstDate' AND '$lastDate')
        )
        
        SELECT * FROM with_week_offs WHERE work IS NOT NULL
        UNION ALL 
        SELECT * FROM with_holidays
    EOT;

    $q = mysqli_query($db, $daily_work_sql);
    while ($row = mysqli_fetch_assoc($q)) {

        if(!empty($row['employee_time'])){
            $employee_time = json_decode($row['employee_time'],true);
            $check_punch_in = $employee_time['punch_in'];
            $check_punch_out = $employee_time['punch_out'];
            $check_hours = date("H.i", (strtotime($check_punch_out) - strtotime($check_punch_in)));
            $check_hours = (float)$check_hours;
        }else{
            $check_hours = 9.0;
        }

        $start =  date("Y-m-d", strtotime($row['work_date']));

        if(strpos($row['work'],'[{')!==false){

            $json_data = json_decode($row['work'], true);
            $totalTime = 0;
            $hours = 0;
            $minutes = 0;
            foreach ($json_data as $key => $data) {
                if (trim(explode(" ", $data['time'])[1]) == 'Minutes') {
                    $minutes += ((float)trim(explode(" ", $data['time'])[0]));
                } else {
                    $twoTime = explode(".", trim(explode(" ", $data['time'])[0]));
                    $hours += (float)$twoTime[0];
                    $minutes += ((float)$twoTime[1]);
                }
                if ($minutes >= 60) {
                    $hours += $minutes / 60;
                    $minutes = $minutes % 60;
                }
            }
    
            if ($minutes == 0) {
                $title =  $hours . " Hours ";
            } else if ($hours == 0) {
                $title =  $minutes . " Minutes";
            } else {
                $title =  $hours . " Hours " . $minutes . " Minutes";
            }
    
            $hours = (float)($hours.'.'.$minutes);
    
            if ($hours >= $check_hours) {
                $className = 'bg-success';
            } else {
                $className = 'bg-danger';
            }
        }else{
            $title = $row['work'];
            $className = 'bg-secondary';
        }


        $event = array(
            'id' => $row['id'],
            'title' => $title,
            'start' => $start,
            'className' => $className
        );
        array_push($events, $event);
    }
    // ##############################################

    $employee = mysqli_fetch_assoc(mysqli_query($db, "SELECT name FROM `users` WHERE `employee_id`='$eid'  "));

    echo json_encode(array('events' => $events, 'name'=> $employee['name']));
}


if (isset($data['employeeWorkId'])) {

    $id = $data['eventClickId'];
    $eid = $data['employeeWorkId'];
    $date = date("Y-m-d", strtotime($data['timeDate']));

    $q = mysqli_query($db, "SELECT u.employee_id, u.name, d.work_date, d.work FROM users as u JOIN dailyWork as d on u.employee_id=d.employee_id where d.id='$id' ORDER BY d.id DESC ");
    if (mysqli_num_rows($q) > 0) {
        $qf = mysqli_fetch_assoc($q);
    } else {
        $qf = array('noData' => 0);
    }

    echo json_encode($qf);
}


if (isset($data['employeeClickWorkId'])) {

    // $id = $data['eventClickId'];
    $eid = $data['employeeClickWorkId'];
    $date = date("Y-m-d", strtotime($data['clickDate']));

    // request leave
    $workData = mysqli_query($db, "select * from dailyWork where employee_id='$eid' and work_date='$date' ");
    if (mysqli_num_rows($workData) > 0) {
        echo json_encode(mysqli_fetch_assoc($workData));
    } else {
        echo json_encode(array('noData' => 1));
    }
}
