<?php

namespace App\Http\Controllers\Personalia;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Ixudra\Curl\Facades\Curl;
use Stevebauman\Location\Facades\Location;

class AbsensiController extends Controller
{
	public function index(Request $request)
	{
		$unit = Curl::to(api_url('presensi/unit'))
		->withData([
			'sUnitID'=> $request->session()->get('sDeptID'), 
			'permission'=> 'get-berdasarkan-sUnitID',
		])->asJson()->post();
		return view('pages.personalia.absensi.index', compact('unit'));
	}

	public function verifyLocation(Request $request)
	{
		$response = Curl::to(api_url('verifylocation'))
		->withData([
			'longitude' => $request->get('longitude'),
			'latitude' => $request->get('latitude'),
			'sEmpID' => $request->session()->get('sEmpID')
		])->asJson()->post();
		echo json_encode($response);
	}

	public function store(Request $request)
	{
		$response = Curl::to(api_url('absent'))
		->withData([
			'employeeid' =>	$request->session()->get('sEmpID'),
			'request' => $request->tipe,
			'longitude' => $request->get('longitude'),
			'latitude' => $request->get('latitude'),
		])->asJson()->post();

		if ($request->tipe == "IN") {
			$tipe = "Masuk";
		} else {
			$tipe = "Pulang";
		}

		if (!empty($response->message)) {
			return redirect()->route('absensi.index')->with('msg',['type'=>'warning','text'=> $response->message ]);
		} else {
			if ($response->Success == "00") {
				return redirect()->route('absensi.index')->with('msg',['type'=>'success','text'=>'Absensi '.$tipe.' berhasil!']);
			} else {
				return redirect()->route('absensi.index')->with('msg',['type'=>'danger','text'=>'Absensi '.$tipe.' Sudah Dilakukan!']);
			}
		}
	}

	public function uploadFoto(Request $request)
	{
		$folderPath = "upload_bukti/";
		$image_parts = explode(";base64,", $request->image);
		$image_type_aux = explode("image/", $image_parts[0]);
		$image_type = $image_type_aux[1];

		$path_file = null;
		if (!empty($request->image)) {
			$fileStream = base64_decode($image_parts[1]);
			$fileName = session()->get('sEmpID').'_'.date('d-m-Y', strtotime(\Carbon\Carbon::now())).'.png';
			\Storage::disk('public')->put("/bukti_absen/".$fileName, $fileStream);
			$path_file = $fileName;
		} else {

		}

		return redirect()->route('dashboard')->with('msg',['type'=>'danger','text'=>'berhasil']);
	}
}
