<?php

namespace App\Models;

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

class LcaLancementsModel extends Model
{
    protected $DBGroup = "default";
    protected $table = "lancements";
    protected $primaryKey = "id";
    protected $useAutoIncrement = true;
	protected $insertID = 0;
	protected $returnType = "App\Entities\LancementsEntity";
	protected $useSoftDelete = false;
	protected $protectFields =false;
    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 = ["id" => "DESC"];


    protected $allowedFields = [
        "id",
        "lancement",
        "marque",
        "preco",
        "date_preco",
        "preco_activee",
        "date_lancement",
        "date_reception",

    ];


    protected $column_order = ["id"];
    protected $column_search = [
        "lancement",
        "marque",
        "preco",
        "date_preco",
        "preco_activee",
        "date_lancement",
        "date_reception",
    ];
    public $fieldValue = [
        "id" => 0,
        "lancement" => "",
        "marque" => "",
        "preco" => "",
        "date_preco" => "",
        "preco_activee" => "",
        "date_lancement" => "",
        "date_reception" => "",

    ];

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



    public function getSelect($where=null)
    {
        $condition = "";
		if ($where != null) {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("*");

        $this->builder->where($condition);
        $query = $this->builder->get();
        $result = $query->getResultArray();
        if($result == null) {
            return (object)$this->fieldValue;
        } else {
		    $data = new SalesEntity();
            $data->fill($result[0]);
            return $data;
        }
    }

    public function getList($where=null)
    {                   
        $condition = "";
		if ($where != null) {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("*");
        $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 = "sales.is_deleted = 0";
		if ($where != null) {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("sales.*, customer_id_table.name AS customer_id_txt, product_id_table.name AS product_id_txt");
        $this->builder->join("customer customer_id_table", "customer_id_table.row_id = sales.customer_id", "left");
        $this->builder->join("product product_id_table", "product_id_table.row_id = sales.product_id", "left");
        $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 = "sales.is_deleted = 0";
		if ($where != "") {
		    $condition .= " and ".$where;
		}
        
        $this->builder->select("sales.*");
        $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('*');




        if ($this->request->getPost('order')) {
            $this->builder->orderBy('id', 'DESC');
        } else if (isset($this->order)) {
            $order = $this->order;
            $this->builder->orderBy('id', 'DESC');
        }
    }

    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();
    }    
}