<?php

namespace App\Models;

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

class Devices extends Model
{
    const MAX_DEVICE_ID = 16;

    const TYPE_BUILT_IN = 1;
    const TYPE_PORTABLE = 2;

    const IS_ACTIVE = 1;
    const IS_INACTIVE = 2;

    const IS_ASSIGNED = 1;
    const IS_UNASSIGNED = 2;

    const IS_AVAIL = 1;
    const IS_UNAVAIL = 2;

    const defaultSelectedDevices = "
    devices.*,vhc.id as vhc_id,vhc.nopol1 as vhc_nopol1,vhc.nopol2 as vhc_nopol2,vhc.nopol3 as vhc_nopol3
    ";

    public static function listDevices($filter = [])
    {
        $params = [];
        $where = '';

        if (isset($filter['is_active'])) {
            $where .= ' AND devices.is_active = ?';
            $params[] = $filter['is_active'];
        }

        if (isset($filter['is_available'])) {
            $where .= ' AND devices.is_available = ?';
            $params[] = $filter['is_available'];
        }

        if (isset($filter['type'])) {
            $where .= ' AND devices.type = ?';
            $params[] = $filter['type'];
        }

        if (isset($filter['is_idle_yes'])) {
            $where .= ' AND vhc.id is null';
        }

        if (isset($filter['is_idle_no'])) {
            $where .= ' AND vhc.id is not null';
        }

        return DB::select("SELECT "
            . Devices::defaultSelectedDevices . "
        FROM t_devices as devices
        LEFT JOIN t_vehicles as vhc ON devices.device_id = vhc.device_id
        WHERE devices.dlt is null
        $where
        ;", $params);
    }

    public static function showDeviceById($id)
    {
        return DB::select("SELECT "
            . Devices::defaultSelectedDevices . "
        FROM t_devices as devices
        LEFT JOIN t_vehicles as vhc ON devices.device_id = vhc.device_id
        WHERE devices.dlt is null AND devices.id = ?
        LIMIT 1;", [$id]);
    }

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

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

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

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

    public static function addDevice($data)
    {
        $id = DB::table("t_devices")->insertGetId($data);
        return $id;
    }

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

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