<?php

namespace App\Models;

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

class Checkpoints extends Model
{
    const defaultSelectedCheckpoints = "
    point.*
	,pck.name as pck_name,pck.fulladdress as pck_fulladdress
	,drp.name as drop_name,drp.fulladdress as drop_fulladdress
    ";

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

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

        return DB::select("SELECT "
        . Checkpoints::defaultSelectedCheckpoints . "
        FROM t_checkpoints as point
        INNER JOIN t_zones as pck ON point.pck_id = pck.id
        LEFT JOIN t_zones as drp ON point.drop_id = drp.id
        WHERE point.dlt is null $where;", $params);
    }

    public static function showCheckpointById($pocket_id)
    {
        return DB::select("SELECT "
        . Checkpoints::defaultSelectedCheckpoints . "
        FROM t_checkpoints as point
        LEFT JOIN t_zones as pck ON point.pck_id = pck.id
        LEFT JOIN t_zones as drp ON point.drop_id = drp.id
        WHERE point.dlt is null AND point.id = ?
        LIMIT 1;", [$pocket_id]);
    }

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

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

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

    public static function addCheckpoint($data)
    {
        $pid = DB::table("t_checkpoints")->insertGetId($data);
        return $pid;
    }

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

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

	public static function deleteCheckpointByPocketId($pocket_id)
    {
        return DB::table("t_checkpoints")->where("pocket_id", $pocket_id)->delete();
    }
}
