<?php

namespace App\Models;

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

class AItems extends Model
{
	const IS_ACTIVE = 1;
    const IS_INACTIVE = 2;

    const IS_ADM_PRICE_NO = 0;
    const IS_ADM_PRICE_YES = 1;

    // 0=>system, 1=>admin, 2=>finance
    const CRT_TYPE_SYSTEM = 0;
    const CRT_TYPE_ADMIN = 1;
    const CRT_TYPE_FINANCE = 2;

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

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

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

        return DB::select("SELECT
        a_item.*,ut.name as type_name
        $select
        FROM
        t_a_items as a_item
        INNER JOIN t_unit_types as ut ON a_item.type = ut.id
        WHERE a_item.dlt is null
        $where
        ORDER BY a_item.name ASC
        ;",
        $params);
    }

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

    public static function get()
    {
        return DB::select("SELECT * FROM t_a_items as a_item WHERE dlt is null ORDER BY a_item.name ASC;");
    }

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

    public static function getByName($name, $filter = [])
    {
        $params = [$name];
        $where = '';
        if (isset($filter['crt_type'])) {
            $where .= ' AND a_item.crt_type = ?';
            $params[] = $filter['crt_type'];
        }
        return DB::select("SELECT * FROM t_a_items as a_item WHERE dlt is null AND name = ? $where LIMIT 1;", $params);
    }

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

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

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