<?php

namespace App\Models;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Model;
use Config\Database;
use App\Entities\CustomerEntity;

class CustomerModel extends Model
{
    protected $DBGroup = "default";
    protected $table = "customer";
    protected $primaryKey = "row_id";
    protected $useAutoIncrement = true;
	protected $insertID = 0;
	protected $returnType = "App\Entities\CustomerEntity";
	protected $useSoftDelete = false;
	protected $protectFields = true;
    protected $useTimestamps = false;
	protected $dateFormat = "datetime";
    protected $createdField = "";
    protected $updatedField = "";
    protected $deletedField = "";
	protected $skipValidation = false;
	protected $cleanValidationRules = true;
	protected $validationRules = [];
	protected $validationMessages = [];
    protected $db;
    protected $builder;
    protected $request;
    protected $order = ["row_id" => "DESC"];
    protected $allowedFields = [
        "row_id", 
        "name",
        "email",
        "phone",
        "address",
        "is_deleted",
        "created_date",
        "created_by",
        "modified_date",
        "modified_by",
        "deleted_date",
        "deleted_by",
    ];
    protected $column_order = ["row_id"];
    protected $column_search = [
        "customer.name",
        "customer.email",
        "customer.phone",
        "customer.address",
    ];
    public $fieldValue = [
        "row_id" => 0,
        "name" => "",
        "email" => "",
        "phone" => "",
        "address" => "",
        "created_date" => "",
        "created_by" => "",
        "modified_date" => "",
        "modified_by" => "",
        "deleted_date" => "",
        "deleted_by",
    ];

    public function __construct(RequestInterface $request=null)
    {
        parent::__construct();
        $this->request = $request;
        $this->db = Database::connect();
        $this->builder = $this->db->table($this->table);
    }

    public function deleteData($id) 
    {
        $data = [
            'is_deleted' => 1,
            'deleted_date'  => getDatetime(),
            'deleted_by' => session()->get("name"),
        ];        
        $this->builder->set($data);
        $this->builder->where("row_id", $id);
        $this->builder->update();
    }

    public function getSelect($where=null) 
    {
        $condition = "customer.is_deleted = 0";
		if ($where != null) {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("customer.*");
        $this->builder->where($condition);
        $query = $this->builder->get();
        $result = $query->getResultArray();
        if($result == null) {
            return (object)$this->fieldValue;
        } else {
		    $data = new CustomerEntity();
            $data->fill($result[0]);
            return $data;
        }
    }

    public function getList($where=null)
    {                   
        $condition = "customer.is_deleted = 0";
		if ($where != null) {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("customer.*");
        $this->builder->where($condition);
        $query = $this->builder->get();
        $result = $query->getResult(); 
        if($result == null) {
            $result = (object)$this->fieldValue;
        }
        return $result;
    }

    public function exportExcel($where=null)
    {                                
        $condition = "customer.is_deleted = 0";
		if ($where != null) {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("customer.*");
        $this->builder->where($condition);
        $query = $this->builder->get();
        return $query;
    }

    public function checkValidation($data=null) 
    {        
        $where = "";
        $unique = "";
        $valid = true;
        $msg = "";
        foreach($data as $row) {
            $type = array_key_exists('type', $row) ? $row['type'] : "";
            $field = array_key_exists('field', $row) ? $row['field'] : "";
            $value = array_key_exists('value', $row) ? $row['value'] : "";  
            
            if($type == "unique") {
                if($unique == "") {
                    $unique .= $field." = '".$value ."'";
                } else {
                    $unique .= " OR ".$field." = '".$value ."'";
                }
            }
        }
        
        if($unique != "") {
            if($where != "") {
                $where .= " and (".$unique.")";
            } else {
                $where .= " (".$unique.")";
            }
        }

        $condition = "customer.is_deleted = 0";
		if ($where != "") {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("customer.*");
        $this->builder->where($condition);
        $query = $this->builder->get();
        $result = $query->getResult();
        if($result == null) {
            $valid = true;
        } else {
            $valid = false;    
            foreach($result as $line)
            {
                foreach($data as $row) {
                    $type = array_key_exists('type', $row) ? $row['type'] : "";
                    $field = array_key_exists('field', $row) ? $row['field'] : "";
                    $value = array_key_exists('value', $row) ? $row['value'] : "";  
                    
                    if($type == "unique") {
                        if($line->$field == $value) {
                            if($msg == "") {
                                $msg .= str("duplicate_date")." ".$value;
                            } else {
                                $msg .= ', '.str("duplicate_date").' '.$value;
                            }
                        }
                    }
                }
            }        
        }
        $ret = [
            "valid" => $valid,
            "msg" => $msg
        ];
        return $ret;
    }

    private function getDatatablesQuery($where)
    {
        $i = 0;
        $this->builder->select('customer.*');

        foreach ($this->column_search as $item) {
            if ($this->request->getPost('search')['value']) {
                if ($i === 0) {
                    $this->builder->groupStart();
                    $this->builder->like($item, $this->request->getPost('search')['value']);
                } else {
                    $this->builder->orLike($item, $this->request->getPost('search')['value']);
                }
                if (count($this->column_search) - 1 == $i)
                    $this->builder->groupEnd();
            }
            $i++;
        }

        if($where != "") {
            $where = " and ".$where;
        }
        $this->builder->where("customer.is_deleted = 0".$where);

        if ($this->request->getPost('order')) {
            $this->builder->orderBy($this->column_order[$this->request->getPost('order')['0']['column']], $this->request->getPost('order')['0']['dir']);
        } else if (isset($this->order)) {
            $order = $this->order;
            $this->builder->orderBy(key($order), $order[key($order)]);
        }
    }

    public function getDatatables($where)
    {
        $this->getDatatablesQuery($where);
        if ($this->request->getPost('length') != -1) {
            $this->builder->limit($this->request->getPost('length'), $this->request->getPost('start'));
        }
        $query = $this->builder->get();
        return $query->getResultArray();
    }

    public function countFiltered($where)
    {
        $this->getDatatablesQuery($where);
        return $this->builder->countAllResults();
    }

    public function countAll()
    {
        $tbl_storage = $this->db->table($this->table);
        return $tbl_storage->countAllResults();
    }    
}