<?php

namespace App\Models;

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

class OrdersInvoices extends Model
{
    const FLOW_TYPE_PAYMENT = 1;
    const FLOW_TYPE_BILLING = 2;
    const FLOW_TYPE_HYBRID = 3;

    const TYPE_CASH_OUT = 1;
    const TYPE_CASH_IN = 2;
    const TYPE_CASH_HYBRID = 3;

	const AMT_TYPE_FLAT = 1;
	const AMT_TYPE_PERCENT = 2;

    // 1=>refer pay_due_at, 2=>jatuh tempo 14 hari kerja
	const PAY_DUE_TYPE_TIME = 1;
	const PAY_DUE_TYPE_14_WORK_DAY = 2;

    const IS_PAID_NO = 0;
    const IS_PAID_YES = 1;

    const IS_GNRT_INVC_NO = 0;
    const IS_GNRT_INVC_YES = 1;

    // 1=>transfer
	const PAID_TYPE_TF = 1;

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

    // 1=>client
    const INVC_FOR_CLIENT = 1;

	const DFT_TAX_PERCENT = 0;

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

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

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

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

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

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

    public static function getLikeCode($code)
    {
        return DB::select("SELECT COUNT(id) as total FROM t_orders_invoices WHERE dlt is null AND code LIKE ? LIMIT 1;", [$code.'%']);
    }

    public static function getLikeCodeLastRunningNumber($code)
    {
        return DB::select("SELECT code FROM t_orders_invoices WHERE dlt is null AND code LIKE ? ORDER BY code DESC LIMIT 1;", [$code.'%']);
    }

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

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

    public static function updtByOrdId($ord_id, $data)
    {
        return DB::table("t_orders_invoices")->where("ord_id", $ord_id)->update($data);
    }

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

    public static function dltByOrdId($ord_id)
    {
        return DB::table("t_orders_invoices")->where("ord_id", $ord_id)->delete();
    }
}
