<?php 
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Max-Age: 3600");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

    include_once '../config/database.php';
    include_once '../objects/attendance.php'; 
    include_once '../config/_globle.php';
    session_start();

    $database = new Database();
    $db = $database->getConnection();

    $attendance = new Attendance($db);
    $data = json_decode(file_get_contents("php://input")); 

    $ym = $data->date;
    $ym_split = explode("-", $ym);

    $prev_month = date('m', strtotime('-1 months', strtotime($ym))); 
    $prev_year = date('Y', strtotime('-1 months', strtotime($ym))); 

    $total_days_prev_month = cal_days_in_month(CAL_GREGORIAN, $prev_month, $prev_year);
    $total_days_current_month = cal_days_in_month(CAL_GREGORIAN, $ym_split[1], $ym_split[0]);

    $df = $prev_year . '-' . $prev_month . '-' . ($total_days_prev_month - 1);
    $dt = $ym_split[0] . '-' . $ym_split[1] . '-' . ($total_days_current_month - 2);

    $attendance->df = $df;
    $attendance->dt = $dt;
    $attendance->staff_id = $_SESSION["staff_id"];

    $stmt = $attendance->getAttendanceByStaff();
    $num = $stmt->rowCount();

    $arr = array();
    $arr["records"] = array();

    if($num>0){
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row); 
            $detail = array(
                "date" => $att_date,
                "duty_in_time" => ($duty_in!="")?date('h:i A', strtotime($duty_in)):"",
                "duty_out_time" => ($duty_out!="")?date('h:i A', strtotime($duty_out)):"",
                "second_duty_in_time" => ($second_duty_in!="")?date('h:i A', strtotime($second_duty_in)):"",
                "second_duty_out_time" => ($second_duty_out!="")?date('h:i A', strtotime($second_duty_out)):"",
                "total_min" => (int)$total_min,
                "late_min" => (int)(($total_min>=540 || $total_min==0)?0:540 - $total_min),
                "extra_min" => (($total_min>540)?((int)$total_min - 540):0)
            );  
            array_push($arr["records"], $detail);
        }
    }
    echo json_encode($arr);
?>