<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class StatisticController extends Controller
{
    function index(){
		
		$data['title'] = 'Statistik Parkir';
		return view("statistic",$data);
	}
	
	public function graphic(Request $r)
	{
		$curdate = $r->date1;

		$columns = [];
		$labels = [];
		$t = 1;
		for ($h = 0; $h <= 23; $h++) {
			$columns[] = "COUNT(CASE WHEN HOUR(datetimein) = '$h' THEN 1 END) AS keluar$h";
			$labels[] = "$h-$t";
			$t++;
		}

		$queryString = "SELECT vehicle, " . implode(", ", $columns) . " FROM parking_out WHERE LEFT(datetimein, 10) = ? GROUP BY vehicle";
		
		$vehicles = DB::select($queryString, [$curdate]);

		$chartData = [];
		$colors = ["#FF5733", "#33FF57", "#3357FF", "#F3FF33"];
		$no = 0;

		foreach ($vehicles as $vehicle) {
			$dataPoints = [];
			for ($h = 0; $h <= 23; $h++) {
				$key = "keluar$h";
				$dataPoints[] = $vehicle->$key ?? 0;
			}

			$chartData[] = [
				'data' => $dataPoints,
				'label' => $vehicle->vehicle,
				'borderColor' => $colors[$no % count($colors)],
				'fill' => false,
			];

			$no++;
		}

		return response()->json([
			'jam' => json_encode($labels),
			'chars' => json_encode($chartData)
		]);
	}
	
	public function graphic_keluar(Request $r)
	{
		$curdate = $r->date1;

		$columns = [];
		$labels = [];
		$t = 1;
		for ($h = 0; $h <= 23; $h++) {
			$columns[] = "COUNT(CASE WHEN HOUR(datetimeout) = '$h' THEN 1 END) AS keluar$h";
			$labels[] = "$h-$t";
			$t++;
		}

		$queryString = "SELECT vehicle, " . implode(", ", $columns) . " FROM parking_out WHERE LEFT(datetimeout, 10) = ? GROUP BY vehicle";
		
		$vehicles = DB::select($queryString, [$curdate]);

		$chartData = [];
		$colors = ["#FF5733", "#33FF57", "#3357FF", "#F3FF33"];
		$no = 0;

		foreach ($vehicles as $vehicle) {
			$dataPoints = [];
			for ($h = 0; $h <= 23; $h++) {
				$key = "keluar$h";
				$dataPoints[] = $vehicle->$key ?? 0;
			}

			$chartData[] = [
				'data' => $dataPoints,
				'label' => $vehicle->vehicle,
				'borderColor' => $colors[$no % count($colors)],
				'fill' => false,
			];

			$no++;
		}

		return response()->json([
			'jam' => json_encode($labels),
			'chars' => json_encode($chartData)
		]);
	}

}
