<?php

namespace App\Models;

use CodeIgniter\Model;
use App\Libraries\GeneralLib;

class AgenModel extends Model
{
    protected $table      = 'agen';
    protected $primaryKey = 'id_agen';

    protected $useAutoIncrement = true;

    protected $returnType     = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['nomor', 'nama_perusahaan', 'nama_pemohon', 'sold_id', 'email', 'password', 'no_hp', 'alamat', 'kelurahan', 'kecamatan', 'kabupaten', 'provinsi', 'lat', 'lng', 'ktp', 'sk', 'kontrak_pangkalan', 'foto_lokasi', 'foto_selfie_ktp'];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function GetDT($request)
    {
        $genlib = new GeneralLib();
        $db = db_connect();
        //$builder = $db->table('vpangkalan');
        
        $return_data = array();
        $return_data['draw'] = $request['draw'];

        $where = array();
        foreach($request['columns'] as $item){
            if (($item['searchable']=='true') && (!empty($item['search']['value'])))
            {
                $where[] = $item['data']." like '%".$item['search']['value']."%'";
            }
        }

        if (!empty($request['search']['value']))
        {
            $where = array();
            foreach($request['columns'] as $item){
                if (($item['searchable']=='true'))
                {
                    $where[] = $item['data']." like '%".$request['search']['value']."%'";
                }
            }
        }

        if(isset($request['searchBuilder']))
        {
            $filter = $genlib->dt_traverse_search_builder($request['searchBuilder']);
        }else{
            $filter = implode(" or ",$where);
        }
        //die(var_dump($filter));

        $order_by = $request['columns'][$request['order'][0]['column']]['data'];
        $order = $request['order'][0]['dir'];
        
        $squery = "select * from vagen";

        $squery_total = "SELECT
                    count(vagen.id_agen) as jumlah
                    FROM
                    vagen";

        $squery_total_filtered = "SELECT
                    count(vagen.id_agen) as jumlah
                    FROM
                    vagen";

        if (!empty($filter))
        {
            $filter = "(".$filter.")";
        }

        if (!empty($extra)){
            $squery_total .= " where ".$extra;
            if (empty($filter)){
                $filter = $extra;
            }else{
                $filter .= " and (".$extra.")";
            }
        }
        
        if (!empty($order_by))
        {
            $order_by = " order by ".$order_by." ".$order;
        }
        
        if (!empty($filter))
        {
            //$data = $builder->where($filter)->orderBy($order_by, $order)->limit($request['start'],$request['length'])->get()->getResult();
            $squery .= " where ".$filter.$order_by." limit ".$request['start'].",".$request['length'];
            $squery_total_filtered .= " where ".$filter;
        }else{
            //$data = $builder->orderBy($order_by, $order)->limit($request['start'],$request['length'])->get()->getResult();
            $squery .= $order_by." limit ".$request['start'].",".$request['length'];
        }
        //die(var_dump($squery));
        //die(var_dump($registrasi));
        $query_total = $db->query($squery_total);
        $query_total_filtered = $db->query($squery_total_filtered);
        $query = $db->query($squery);

        $row_total = $query_total->getRow();
        $row_total_filtered = $query_total_filtered->getRow();
        $data = $query->getResult();

        $return_data['recordsTotal'] = $row_total->jumlah;
        $return_data['recordsFiltered'] =  $row_total_filtered->jumlah;
        $return_data['data'] = $data;

        return json_encode($return_data);
    }

    public function GetSelect($search, $page = 1, $extra_query = "")
    {
        $result['results'] = array();
        $result['pagination']['more'] = false;

        $query1 = "select id_agen as 'id', nama_perusahaan as 'text' from agen where (1=1)";
        $query2 = "select count(id_agen) as total from agen where (1=1)";
        $subQuery = "";
        if (!empty($search))
        {
            $subQuery = " and ((nama_perusahaan like '%".$search."%'))";
        }

        if ($subQuery != "")
        {
            $query1 .= $subQuery;
            $query2 .= $subQuery;
        }
        
        if (!empty($extra_query))
        {
            $query1 .= " and (".$extra_query.")";
            $query2 .= " and (".$extra_query.")";
        }

        $builder = $this->builder();
        $totalrow = $builder->countAll();

        $length = 10;
        $start = ($page - 1) * $length;

        $query1 .= " limit ".$start.",".$length;

        $db = $builder->db();
        $query = $db->query($query1);
        
        $data = $query->getResultArray();
        $result['results'] = $data;
        $result['pagination']['more'] = ($page * 10) < $totalrow;
        return $result;
    }

    public function get_count()
    {
        $db = db_connect();
        $query = $db->query('select count(id_agen) as jumlah from agen');
        return $query->getRow()->jumlah;
    }
}
?>