<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Validator;
use Hidehalo\Nanoid\Client as Nanoid;
use Hidehalo\Nanoid\GeneratorInterface as NanoidInterface;
use App\Responses;
use App\Helper;
use App\Models\Vehicles;
use App\Models\UserLogs;
use Auth;

class MediaController extends Controller
{
    /**
     * View
     */

    public function view_media(Request $req)
    {
        $data = [];

		
		$log = [
			"module" => "Media",
			"action" => "View",
			"desc" => "Open Media menu",
		];
		UserLogs::insert(Auth::user()->id, $log);
        return view("menu_v1.media", $data);
    }

    /**
     * API
     */

	public function api_get_media(Request $req)
    {
		$a = $req->a;
        try {
			switch ($a) {
				case 'listVehicle':
					$list = Vehicles::listVehicles($req->auth, []);

					$apiResp = Responses::success("success list media");
					$apiResp["count"] = count($list);
					$apiResp["data"] = $list;
					return new Response($apiResp, $apiResp["meta"]["code"]);
					break;
				case 'listMedia':
					$vhcId = $req->vhcId;
					$tgl0 = $req->tgl0 * 1000 ;
					$tgl1 = $req->tgl1 * 1000 ;
					$camera = $req->camera;

					$list = DB::select("SELECT * 
						FROM t_camera 
						WHERE 
							vhc_id = ?
							AND crt_d BETWEEN ? AND ?
							and cam = IFNULL(?, cam)
						ORDER BY crt_d ASC
					", [$vhcId, $tgl0, $tgl1, $camera]);

					$apiResp = Responses::success("success list media");
					$apiResp["count"] = count($list);
					$apiResp["data"] = $list;
					return new Response($apiResp, $apiResp["meta"]["code"]);
					break;
				default:
					$apiResp = Responses::error("invalid action");
					return new Response($apiResp, $apiResp["meta"]["code"]);
					break;
			}
        } catch (\Exception $e) {
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }

}
