<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Vehicles extends Model
{
    const DEFAULT_CAT_ID = 1; // truck
    const DEFAULT_TRACK_HOLIDAY = 1;
    const DEFAULT_TRACK_SCH_H = 24;
    const DEFAULT_TRACK_SCH_D = 7;

    const MAX_DEVICE_ID = 16;
    const ENABLED_TRACK_HOLIDAY = 1;
    const DISABLED_TRACK_HOLIDAY = 2;

    const STTS_ACTIVE = 1;
    const STTS_INACTIVE = 2;

    const IN_ORD_YES = 1;
    const IN_ORD_NO = 2;

    private const defaultSelectVehicle =
        "" .
        "v.*,vd.*," .
        "v.id as vid,vd.id as vd_id,v.sum_milleage," .
        "c.name as cat_name,t.name as type_name,b.name as brand_name,m.name as model_name," .
        "dc.fullname as dc_fullname,dc.phone as dc_phone,dc.phone_code as dc_phone_code," .
        "da.fullname as da_fullname,da.phone as da_phone,da.phone_code as da_phone_code," .
        "dvc.name as dvc_name,dvc.type as dvc_type";

    public static function listVehicles($auth, $filter = [])
    {
        $params = [];
        $select = "";
        $where = "";

        // if ($auth->role == Users::ROLE_VENDOR) {
        //     $where .= " AND v.vendor_id = " . $auth->uid;
        // }

        if (isset($filter["company"])) {
            $where .= " AND client.id = ?";
            $params[] = $filter["company"];
        }

        // vd.speed_limit,vd.fuel_capacity,vd.fuel_drop_treshold,vd.max_pressure,vd.fvhc_img,
        return DB::select(
            "SELECT
		" .
                self::defaultSelectVehicle .
                "
		,client.c_name as company_name
		" .
                $select .
                "
		FROM t_vehicles as v
		INNER JOIN t_vehicles_detail AS vd ON v.id = vd.vid
		LEFT JOIN t_vehicles_cats AS c ON v.cat_id = c.id
		LEFT JOIN t_vehicles_types AS t ON v.type_id = t.id
		LEFT JOIN t_vehicles_brands AS b ON v.brand_id = b.id
		LEFT JOIN t_vehicles_models AS m ON v.model_id = m.id
		LEFT JOIN t_drivers AS dc ON v.c_did = dc.id
		LEFT JOIN t_drivers AS da ON v.a_did = da.id
		LEFT JOIN t_users AS vdr ON v.vendor_id = vdr.id
		LEFT JOIN t_clients AS client ON vdr.client_group_id = client.id
		LEFT JOIN t_devices AS dvc ON v.device_id = dvc.device_id
		WHERE v.dlt is null
		" .
                $where .
                "
		ORDER BY v.id ASC;",
            $params
        );
    }

    public static function getVehicles()
    {
        return DB::select("SELECT * FROM t_vehicles WHERE dlt is null;");
    }

    public static function showVehicleById($vid)
    {
        return DB::select(
            "SELECT
		" .
                self::defaultSelectVehicle .
                "
		FROM t_vehicles as v
		INNER JOIN t_vehicles_detail AS vd ON v.id = vd.vid
		LEFT JOIN t_vehicles_cats AS c ON v.cat_id = c.id
		LEFT JOIN t_vehicles_types AS t ON v.type_id = t.id
		LEFT JOIN t_vehicles_brands AS b ON v.brand_id = b.id
		LEFT JOIN t_vehicles_models AS m ON v.model_id = m.id
		LEFT JOIN t_drivers AS dc ON v.c_did = dc.id
		LEFT JOIN t_drivers AS da ON v.a_did = da.id
		LEFT JOIN t_devices AS dvc ON v.device_id = dvc.device_id
		WHERE v.dlt is null
		AND v.id = ?
		LIMIT 1;",
            [$vid]
        );
    }

    public static function getVehicleById($vid)
    {
        return DB::select("SELECT * FROM t_vehicles WHERE dlt is null AND id = ? LIMIT 1;", [$vid]);
    }

    public static function getVehicleByDeviceId($device_id)
    {
        return DB::select(
            "SELECT v.*,vd.tax_exp,vd.kir_exp FROM t_vehicles as v INNER JOIN t_vehicles_detail as vd ON v.id = vd.vid WHERE v.dlt is null AND v.device_id = ? LIMIT 1;",
            [$device_id]
        );
    }

    public static function getVehicleBySimcard($simcard)
    {
        return DB::select("SELECT * FROM t_vehicles WHERE dlt is null AND simcard = ? LIMIT 1;", [$simcard]);
    }

    public static function getVehicleByPlatNo($nopol1, $nopol2, $nopol3)
    {
        return DB::select(
            "SELECT v.*,vd.tax_exp,vd.kir_exp FROM t_vehicles as v INNER JOIN t_vehicles_detail as vd ON v.id = vd.vid WHERE v.dlt is null AND v.nopol1 = ? AND v.nopol2 = ? AND v.nopol3 = ? LIMIT 2;",
            [$nopol1, $nopol2, $nopol3]
        );
    }

    public static function searchVehicleByPlatNo($nopol1, $nopol2, $nopol3)
    {
        return DB::select(
            "SELECT v.*,vd.tax_exp,vd.kir_exp FROM t_vehicles as v INNER JOIN t_vehicles_detail as vd ON v.id = vd.vid WHERE v.dlt is null AND v.nopol1 LIKE '%" .
                $nopol1 .
                "%' AND v.nopol2 LIKE '%" .
                $nopol2 .
                "%' AND v.nopol3 LIKE '%" .
                $nopol3 .
                "%';"
        );
    }

    public static function getVehicleByIdAllData($vid)
    {
        return DB::select(
            "SELECT
		*,v.id as vhc_id
		FROM t_vehicles as v
		INNER JOIN t_vehicles_detail as vd ON v.id = vd.vid
		WHERE v.dlt is null
		AND v.id = ?
		LIMIT 1;",
            [$vid]
        );
    }

    public static function getVehiclesInIds($vids)
    {
        $params = [];
        $where_in = "";

        $vids = explode(",", $vids);
        foreach ($vids as $vid) {
            $where_in .= "?,";
            array_push($params, $vid);
        }
        if (strpos($where_in, ",") !== false) {
            $where_in = substr($where_in, 0, -1);
        }
        return DB::select(
            "SELECT * FROM t_vehicles WHERE dlt is null AND id IN (" . $where_in . ");",
            $params
        );
    }

    public static function getVehiclesInIdsActiveNoInOrder($vids)
    {
        $params = [];
        $where_in = "";

        $vids = explode(",", $vids);
        foreach ($vids as $vid) {
            $where_in .= "?,";
            array_push($params, $vid);
        }
        if (strpos($where_in, ",") !== false) {
            $where_in = substr($where_in, 0, -1);
        }
        return DB::select(
            "SELECT
		v.*,ord.status as ord_status
		FROM t_vehicles as v
		LEFT JOIN (SELECT MAX(ord_id) as max_ord_id,vhc_id FROM t_orders_vehicles GROUP BY vhc_id) as ord_vhc1 ON (v.id = ord_vhc1.vhc_id)
        LEFT JOIN t_orders as ord ON (ord_vhc1.max_ord_id = ord.id)
		WHERE v.dlt is null
		AND v.status = " .
                Vehicles::STTS_ACTIVE .
                "
		AND v.is_in_ord = " .
                Vehicles::IN_ORD_NO .
                "
		AND (ord.status is null OR ord.status IN (" .
                Orders::STTS_CLIENT_PAY .
                "," .
                Orders::STTS_VENDOR_PAYED .
                "," .
                Orders::STTS_CLOSE .
                "," .
                Orders::STTS_CANCEL .
                "))
		AND v.id IN (" .
                $where_in .
                ")
		;",
            $params
        );
    }

    public static function getVehiclesInVendorIdsActiveNoInOrder($vendorIds, $prefer_truck_type = 0)
    {
        $params = [];
        $where_in = "";
        $where_where = "";

        $vendorIds = explode(",", $vendorIds);
        foreach ($vendorIds as $vendorId) {
            $where_in .= "?,";
            array_push($params, $vendorId);
        }
        if (strpos($where_in, ",") !== false) {
            $where_in = substr($where_in, 0, -1);
        }

        if ($prefer_truck_type != 0) {
            $where_where = " AND v.type_id = ?";
            array_push($params, $prefer_truck_type);
        }

        return DB::select(
            "SELECT
		v.*,ord.status as ord_status
		FROM t_vehicles as v
		LEFT JOIN (SELECT MAX(ord_id) as max_ord_id,vhc_id FROM t_orders_vehicles GROUP BY vhc_id) as ord_vhc1 ON (v.id = ord_vhc1.vhc_id)
        LEFT JOIN t_orders as ord ON (ord_vhc1.max_ord_id = ord.id)
		INNER JOIN t_gps_tracks as tr ON v.device_id = tr.device_id
		WHERE v.dlt is null
		AND v.status = " .
                Vehicles::STTS_ACTIVE .
                "
		AND v.is_in_ord = " .
                Vehicles::IN_ORD_NO .
                "
		AND (ord.status is null OR ord.status IN (" .
                Orders::STTS_CLIENT_PAY .
                "," .
                Orders::STTS_VENDOR_PAYED .
                "," .
                Orders::STTS_CLOSE .
                "," .
                Orders::STTS_CANCEL .
                "))
		AND v.vendor_id IN (" .
                $where_in .
                ")
		$where_where
		GROUP BY v.id
		;",
            $params
        );
    }

    public static function addVehicle($data)
    {
        $vid = DB::table("t_vehicles")->insertGetId($data);
        return $vid;
    }

    public static function updateVehicle($vid, $data)
    {
        return DB::table("t_vehicles")
            ->where("id", $vid)
            ->update($data);
    }

    public static function deleteVehicle($vid)
    {
        return DB::table("t_vehicles")
            ->where("id", $vid)
            ->delete();
    }

    // default 1: truck
    public static function listCats()
    {
        return DB::select("SELECT * FROM t_vehicles_cats WHERE dlt is null AND is_active = 1;");
    }

    // default 1: unknown
    public static function listBrands()
    {
        return DB::select("SELECT * FROM t_vehicles_brands WHERE dlt is null AND is_active = 1;");
    }

    public static function listTypes()
    {
        return DB::select("SELECT * FROM t_vehicles_types WHERE dlt is null AND is_active = 1;");
    }

    public static function listModels()
    {
        return DB::select("SELECT * FROM t_vehicles_models WHERE dlt is null AND is_active = 1;");
    }
}
