<?php

namespace App\Models;

use CodeIgniter\Model;

class SaleModel extends Model
{
    protected $table            = 'tbl_sale';
    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('UPPER(tbl_good.name)',$this->search);
            $this->orLike('UPPER(tbl_good.description)',$this->search);
            $this->orLike('UPPER(tbl_good.stock)',$this->search);
            $this->orLike('UPPER(tbl_good.price_sale)',$this->search);
            $this->orLike('UPPER(tbl_good.price_buy)',$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->image = '<img src="'.base_url().'uploads/goods/'.$row->image.'" style="width: 60px; height: 60px;">';

                $row->price_sale = '<span class="text-success fw-semibold"> Rp. '.number_format($row->price_sale, 0, ',', '.').'</span>';
                $row->price_buy = '<span class="text-danger fw-semibold"> Rp. '.number_format($row->price_buy, 0, ',', '.').'</span>';


                if(intval($row->stock)>=25){
                    $row->stock = '<span class="badge bg-success">'.$row->stock.'</span>';
                }else if(intval($row->stock)>=15 && intval($row->stock)<25){
                    $row->stock = '<span class="badge bg-warning">'.$row->stock.'</span>';
                }else{
                    $row->stock = '<span class="badge-danger-blink">'.$row->stock.'</span>';
                }

                
                $row->option = '<p class="m-0 text-nowrap">';

                $row->option = $row->option . '<a href="javascript:void(0)" title="Detail data" data-link="' . base_url() . 'good/detail/' . $row->id . '" class=" datatable-detail me-3"><i class="bx bx-show text-dark" style="font-size: 20px;"></i></a>';

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

                $row->option = $row->option . ' <a href="javascript:void(0)" data-id="' . $row->id . '" title="Hapus data" data-link="' . base_url() . 'good/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);
    }


    public function saveData()
    {



        if(empty($this->image)){
            return [
                'code'      => 200,
                'success'   => false,
                'message'   => "Gambar produk tidak boleh kosong"
            ];
        }


        $data = [
            'name'  => $this->name,
            'category_id'  => $this->category,
            'unit_id'  => $this->unit,
            'price_buy'  => $this->price_buy,
            'price_sale'  => $this->price_sale,
            'discount'  => empty($this->discount) ? null : $this->discount,
            'description'  => $this->description,
            'created_by'  => session()->get('id'),
            'created_at'  => date('Y-m-d H:i:s'),
        ];


        preg_match("/^data:(image\/[a-zA-Z]+);base64,/", $this->image, $matches);
        $mime = $matches[1];
        $ext = explode('/', $mime)[1]; 
        $image = 'area_' . date('Ymd_His') . '.' . $ext;

        if ($this->_uploadImage('./uploads/goods/', $image)) {
            $data['image'] = $image;
        }


        if(!$this->insert($data)){
            return [
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ];
        }

        return [
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ];


    }


    public function updateData()
    {


        $oldData = $this->find($this->id);

        if(empty($this->image)){
            return [
                'code'      => 200,
                'success'   => false,
                'message'   => "Gambar produk tidak boleh kosong"
            ];
        }


        $data = [
            'name'  => $this->name,
            'category_id'  => $this->category_id,
            'unit_id'  => $this->unit_id,
            'price_buy'  => $this->price_buy,
            'price_sale'  => $this->price_sale,
            'discount'  => empty($this->discount) ? null : $this->discount,
            'description'  => $this->description,
            'updated_by'  => session()->get('id'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ];

        if(strtoupper($this->image)!=strtoupper($oldData->image)){

            preg_match("/^data:(image\/[a-zA-Z]+);base64,/", $this->image, $matches);
            $mime = $matches[1];
            $ext = explode('/', $mime)[1]; 
            $image = 'area_' . date('Ymd_His') . '.' . $ext;

            if ($this->_uploadImage('./uploads/goods/', $image)) {
                $data['image'] = $image;
            }

            try {
                 $imagePath = './uploads/goods/' . $oldData->image;

                 if (is_file($imagePath) && strtolower($oldData->image) !== 'default.png') {
                    
                     if (!unlink($imagePath)) {
                     }
                 }
            } catch (Exception $e) {

            }



        }


        if(!$this->update($this->id,$data)){
            return [
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ];
        }

        return [
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ];


    }


    private function _uploadImage($upload_dir = './uploads/goods/', $image = 'default.png')
    {

        if ($image === 'default.png') {
            return false;
        }


        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        preg_match("/^data:(image\/[a-zA-Z]+);base64,/", $this->image, $matches);
        $mime = $matches[1];
        $ext = explode('/', $mime)[1]; 

        $img = str_replace(['data:image/'.$ext.';base64,', ' '], ['', '+'], $this->image);
        $data = base64_decode($img);

        if ($data === false) {
            return false;
        }

        // Tentukan lokasi file dan simpan data
        $file = $upload_dir . $image;

        return file_put_contents($file, $data) !== false;

    }



    public function getAllProduct()
    {


        if(!empty($this->category)&&!empty($this->type)){

            if(strtoupper($this->type)=="CATEGORY"){
                $this->where('category_id',$this->category);
            }else{
                if(strtoupper($this->category)=="POPULER"){

                }else if(strtoupper($this->category)=="CHEAP"){

                    $this->orderBy('price_sale',"ASC");
                
                }else if(strtoupper($this->category)=="EXPENSIVE"){

                    $this->orderBy('price_sale',"DESC");
                
                }else if(strtoupper($this->category)=="DISCOUNT"){

                    $this->where('discount!=',null);
                }
            }
        }
        if(!empty($this->search)){
            $this->groupStart();
                $this->like('UPPER(name)',strtoupper($this->search));
            $this->groupEnd();
        }
        $this->offset(intval($this->startData));
        $this->limit(intval($this->limitData));
        $results = $this->findAll();


        $this->select('id');
        
        if(!empty($this->category)&&!empty($this->type)){

            if(strtoupper($this->type)=="CATEGORY"){
                $this->where('category_id',$this->category);
            }else{
                if(strtoupper($this->category)=="POPULER"){

                }else if(strtoupper($this->category)=="CHEAP"){

                    $this->orderBy('price_sale',"ASC");
                
                }else if(strtoupper($this->category)=="EXPENSIVE"){

                    $this->orderBy('price_sale',"DESC");
                
                }else if(strtoupper($this->category)=="DISCOUNT"){

                    $this->where('discount!=',null);
                }
            }
        }
        if(!empty($this->search)){
            $this->groupStart();
                $this->like('UPPER(name)',strtoupper($this->search));
            $this->groupEnd();
        }
        $this->offset( (intval($this->startData) + intval($this->limitData)) );
        $this->limit(intval($this->limitData));
        $hasNext = count($this->findAll()) > 0 ? true : false;
        
        return [
            'code'      => 200,
            'success'   => true,
            'data'      => [
                'data'      => $results,
                'hasNext'   => $hasNext
            ]
        ];


    }



}
