<?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 App\Responses;
use App\Helper;
use App\Models\Tracks;
use App\Models\Vehicles;
use App\Models\Zone;
use App\Models\Users;
use App\Models\Orders;

class TrackController extends Controller
{
    public function api_list_currect_track_vhc(Request $req)
    {
        try {
            $now = time();
            $input = [];
            $rulesInput = [];
            $filter = [
                "get_order_data" => 1,
            ];
            if ($req->cptid) {
                $filter["company"] = $req->cptid;
            }

            if ($req->auth->is_tracking === Users::IS_TRACK_VHC_YES) {
                if ($req->auth->vhcs) {
                    $filter["vids"] = explode(",", $req->auth->vhcs);
                } else {
                    $filter["vid"] = 0;
                }
            } elseif ($req->auth->is_tracking === Users::IS_TRACK_VHC_DEFAULT) {
                if ($req->auth->role === Users::ROLE_ADMIN) {
                    if ($req->ord_id) {
                        $ord = Orders::showOrder(["id" => $req->ord_id]);
                        if (count($ord) > 0) {
                            $filter["vid"] = $ord[0]->vhc_id;
                        } else {
                            $filter["vid"] = 0;
                        }
                    } elseif ($req->ord_code) {
                        $ord = Orders::showOrder(["code" => $req->ord_code]);
                        if (count($ord) > 0) {
                            $filter["vid"] = $ord[0]->vhc_id;
                        } else {
                            $filter["vid"] = 0;
                        }
                    }
                } elseif ($req->auth->role === Users::ROLE_VENDOR) {
                    $filter["own_by_vdr_id"] = $req->auth->uid;
                } elseif ($req->auth->role === Users::ROLE_CLIENT_ADMIN) {
                    $ords = Orders::listOrders([
                        "client_id_active_orders" => $req->auth->uid,
                        "is_accident" => Orders::IS_ACCIDENT_NO,
                    ]);
                    $filter["vids"] = [];
                    $filter["client_id"] = $req->auth->uid;
                    foreach ($ords as $k => $v) {
                        $filter["vids"][] = $v->vhc_id;
                    }
                } elseif ($req->auth->role === Users::ROLE_SPECIAL_TRACKING) {
                    $filter["company"] = $req->auth->client_group_id;
                } else {
                    $filter["vid"] = 0;
                }
            } else {
                $filter["vid"] = 0;
            }

            $list = Tracks::listCurrentTracks($filter);
            // dd($list);
            foreach ($list as $key => $row) {
                $list[$key]->DT_RowIndex = $key + 1;

                $list[$key]->is_track_holiday_text =
                    $list[$key]->is_track_holiday == Vehicles::ENABLED_TRACK_HOLIDAY ? "Enabled" : "Disabled";
                $list[$key]->alert_zones = "-";
                $list[$key]->cameras = "-";

                $insideZones = [];
                $insideZoneCircle = Zone::insideZoneCircle($row->lst_lat, $row->lst_lng);
                if (count($insideZoneCircle) > 0) {
                    array_push($insideZones, ...$insideZoneCircle);
                }
                $insideZoneShape = Zone::insideZoneShape($row->lst_lat, $row->lst_lng);
                if (count($insideZoneShape) > 0) {
                    array_push($insideZones, ...$insideZoneShape);
                }
                if (count($insideZones) > 0) {
                    $list[$key]->inside_zones = $insideZones;
                } else {
                    $list[$key]->inside_zones = null;
                }
            }
            $apiResp = Responses::success("success list vehicles");
            $apiResp["data"] = $list;
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }

    public function api_last_move_track_vhc(Request $req)
    {
        try {
            $now = time();

            $input = [
                "vid" => $req->vid,
                "end_at" => $req->end_at,
            ];
            $rulesInput = [
                "vid" => "required|integer",
                "end_at" => "nullable|date",
            ];

            // validasi input
            $isValidInput = Validator::make($input, $rulesInput);
            if (!$isValidInput->passes()) {
                $apiResp = Responses::bad_input($isValidInput->messages()->first());
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $filter = [
                "limit" => 10000,
            ];
            // default 10000, jika ada filter date maka max 100K
            if (
                $req->start_date != null &&
                $req->start_date != "" &&
                ($req->end_date != null && //
                    $req->end_date != "")
            ) {
                $filter["start_date"] = $req->start_date;
                $filter["end_date"] = $req->end_date;

                // $filter["start_date"] = strtotime(gmdate("Y-m-d H:i:s", $req->start_date));
                // $filter["end_date"] = strtotime(gmdate("Y-m-d H:i:s", $req->end_date));

                $filter["limit"] = 100000;
            } else {
                $todayStart = strtotime(gmdate("Y-m-d 00:00:00"));
                $todayEnd = strtotime(gmdate("Y-m-d 23:59:59"));

                $filter["start_date"] = $todayStart;
                $filter["end_date"] = $todayEnd;
            }

            $list = Tracks::lastMoveTracks($req->vid, $filter);

            $apiResp = Responses::success("success get last movements");
            $apiResp["data"] = $list;
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }
    public function api_conf_list_logs_gps(Request $req)
    {
        try {
            $now = time();
            $input = [];
            $rulesInput = [];

            // validasi input
            // $isValidInput = Validator::make($input, $rulesInput);
            // if (!$isValidInput->passes()) {
            // 	$apiResp = Responses::bad_input($isValidInput->messages()->first());
            // 	return new Response($apiResp, $apiResp['meta']['code']);
            // }

            $filter = [
                "limit" => 1000,
                "crt_greater_than" => 1646122574,
            ];

            $list = Tracks::listLogsGps($filter);
            foreach ($list as $key => $row) {
                $list[$key]->DT_RowIndex = $key + 1;
                $list[$key]->action = "-";
            }

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

    public function api_track_order(Request $req)
    {
        try {
            $now = time();
            $input = [];
            $rulesInput = [];

            // validasi input
            // $isValidInput = Validator::make($input, $rulesInput);
            // if (!$isValidInput->passes()) {
            // 	$apiResp = Responses::bad_input($isValidInput->messages()->first());
            // 	return new Response($apiResp, $apiResp['meta']['code']);
            // }

            $ord = [];
            $filter = [
                "get_pic_zone" => 1,
                "get_zone_data" => 1,
            ];
            if ($req->ord_id) {
                $filter["id"] = $req->ord_id;
            } elseif ($req->ord_code) {
                $filter["code"] = $req->ord_code;
            }
            $ord = Orders::showOrder($filter);

            if (count($ord) < 1) {
                $apiResp = Responses::not_found("order not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $vid = $ord[0]->vhc_id;

            $history = Tracks::lastMoveTracks($vid, [
                "start_at" => $ord[0]->confirm_at,
            ]);

            $apiResp = Responses::success("success track order");
            $apiResp["data"] = [
                "order" => $ord[0],
                "history" => $history,
            ];
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }
}
