<?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';	

	date_default_timezone_set('Asia/Bangkok'); 
	session_start();

	$database = new Database();
	$db = $database->getConnection();
	 
	$attendance = new Attendance($db);
	$data = json_decode(file_get_contents("php://input"));
	
	$staff_id = $_SESSION["staff_id"];
	if($staff_id!=""){

		$attendance->staff_id = $staff_id;	
		$attendance->att_date = date("Y-m-d");	
		$attendance->duty_out = date("H:i");	
		
		$duty_out_photo = "";

		if($data->photo){
	        if (!is_dir('./upload/' . $staff_id)) {
	            mkdir('./upload/' . $staff_id, 0777, true);
	        }
	        $img = $data->photo;
	        $img_data = base64_decode(explode(',', $img)[1]);
	        $duty_out_photo = date("Y.m.d.H.i.s-") . mt_rand(1000, 9999) . "-dutyout.png";
	        $file = "./upload/" . $staff_id . "/" . $duty_out_photo;
	        $success = file_put_contents($file, $img_data);
		}

		$attendance->duty_out_photo = $duty_out_photo;

		if($attendance->updateDutyOut()){
			$_SESSION['duty_out'] = date('h:i A', strtotime($attendance->duty_out));
			$msg_arr = array(
				"message" => "updated"
			);
		}else{
			$msg_arr = array(
				"message" => "error"
			);
		}
	}else{
		$msg_arr = array(
			"message" => "session expire"
		);
	}
	echo json_encode($msg_arr);
?>