<?php

namespace App\Models;

use CodeIgniter\Model;

class OutModel extends Model
{
    protected $table            = 'tbl_buy';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useSoftDeletes   = false;
    protected $protectFields    = false;
    protected $allowedFields    = [];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

    // 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 _set_query()
    {

        if(!empty($this->search)){
            $this->groupStart();
            $this->like('DATE(date)',$this->search);
            $this->orLike('UPPER(name)',strtoupper($this->search));
            $this->orLike('UPPER(type)',strtoupper($this->search));
            $this->orLike('UPPER(description)',strtoupper($this->search));
            $this->orLike('total',$this->search);
            $this->groupEnd();
        }
    }

    public function getAllData()
    {
        $data = [];

        if ($this->columns[$this->order[0]['column']]['data'] == 'no') {
            $this->columns[$this->order[0]['column']]['data'] = $this->table . '.id';
        }

        //all data
        $this->select($this->table . '.id');
        $this->countData = $this->countAllResults();

        //filtered
        $this->select($this->table . '.id');
        $this->_set_query();
        $this->filterData = $this->countAllResults();

        //view data
        $this->select($this->table.'.*');
        $this->_set_query();
        $this->orderBy($this->columns[$this->order[0]['column']]['data'], $this->order[0]['dir']);
        $this->limit( intval($this->limit), intval($this->start));
        $getData = $this->findAll();
        $no      = $this->start;
        
        if ( count((array) $getData) > 0) {
            foreach ($getData as $row) {
                $row->no = ++$no;
                $row->evidance = '<img src="'.base_url().'uploads/evidance-buy/'.$row->evidance.'" style="width: 50px; height: 50px; border-radius: 4px;">';
                $row->date = date('d-m-Y', strtotime($row->date));
                $row->description = empty($row->description) ? '-' : $row->description;
                $row->total = '<span class="text-danger">Rp. '.number_format($row->total, 0, ',', '.').'</span>';
                $row->option = '<p class="m-0 text-nowrap">';


                if(getAccessMenu(8,"is_edit", session()->get('role_id'))){

                    $row->option = $row->option . '<a href="javascript:void(0)" title="Ubah data" data-link="' . base_url() . 'out/edit/' . $row->id . '" class=" datatable-edit me-2"><i class="bx bx-edit text-warning" style="font-size: 20px;"></i></a>';
                }


                if(getAccessMenu(8,"is_update", session()->get('role_id'))){

                    $row->option = $row->option . ' <a href="javascript:void(0)" data-id="' . $row->id . '" title="Hapus data" data-link="' . base_url() . 'out/delete" class=" datatable-delete"><i class="bx bx-trash text-danger" style="font-size: 20px;"></i></a>';
                }

                $row->option    = $row->option . '</p>';




                $data[]      = $row;
            }
        }

        $result = array(
            "draw"            => $this->draw,
            "recordsTotal"    => $this->countData,
            "recordsFiltered" => $this->filterData,
            "data"            => $data,
        );

        return json_encode($result);
    }


}
