<?php

namespace App\Models;

use CodeIgniter\Model;
use DateTime;

class HistoryUsedModel extends Model
{
    protected $table            = 'tbl_history_used';
    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()
    {
        $this->groupStart();
        $this->like('DATE(start_date)',$this->search);
        $this->orLike('DATE(end_date)',$this->search);
        $this->groupEnd();
    }

    public function get_all_data()
    {
        $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.`id`, $this->table.`start_date`, $this->table.`end_date`, $this->table.`total`");
        $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;
        
        date_default_timezone_set('Asia/Jakarta');
        if ( count((array) $getData) > 0) {
            foreach ($getData as $row) {
                $row->no = ++$no;

                if(empty($row->end_date)){
                    $row->status = '<span class="badge bg-label-warning">Running</span>';
                    $start = new DateTime($row->start_date);
                    $end = "-";

                }else{
                    $row->status = '<span class="badge bg-label-danger">Stoped</span>';
                    $start = new DateTime($row->start_date);
                    $end = new DateTime($row->end_date);

                }

                $row->start_date    = $this->_getFormat($row->start_date);
                $row->end_date      = $this->_getFormat($row->end_date);


                // $diffInSeconds = $end->getTimestamp() - $start->getTimestamp();
                // $hours = $diffInSeconds / 3600;
                
                $total_operation_time = !empty($row->total) ? $row->total : 0;

                $total_operation_time = $this->_formatFix2($total_operation_time);
                $hours = $this->_convertToHourMinute($total_operation_time);

                if ($hours < 1) {
                    $formatted = number_format($hours, 2) . ' H';
                } elseif (fmod($hours, 1) == 0.0) {
                    $formatted = (int)$hours . ' H';
                } else {
                    $formatted = number_format($hours, 2) . ' H';
                }

                $row->total = '<span class="text-primary">'.$formatted.'</span>';

                $data[]      = $row;
            }
        }

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

        return json_encode($result);
    }


    private function _getFormat($date)
    {

        $datetime = new DateTime($date);

        // Array nama bulan dalam bahasa Indonesia
        $bulan = [
            1 => 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun',
            'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'
        ];

        // Ambil bagian-bagian tanggal
        $jam = $datetime->format('H:i'); // 13:01
        $tanggal = $datetime->format('d'); // 22
        $bulanIndo = $bulan[(int)$datetime->format('m')]; // Mei
        $tahun = $datetime->format('Y'); // 2025

        // Format final
        return $tanggal . ' ' . $bulanIndo . ' ' . $tahun . ' <br> ' . $jam ;

    }


    private function _formatFix2($time) {
        $time = floatval($time);
        return ($time == floor($time)) ? strval($time) : number_format($time, 2, '.', '');
    }

    private function _convertToHourMinute($decimalHour) {
        $decimalHour = floatval($decimalHour);

        $jam = floor($decimalHour);
        $menit = round(($decimalHour - $jam) * 60);

        if ($menit === 0) {
            return strval($jam);
        } else {
            return $jam . '.' . str_pad($menit, 2, '0', STR_PAD_LEFT);
        }
    }




}
