<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductionQueueHistoryModel extends Model
{
    protected $table = 'production_queue_history';

    protected $primaryKey = 'id_history';

    protected $returnType = 'array';

    protected $useTimestamps = false;

    protected $allowedFields = [

        'id_queue',

        'status_sebelum',

        'status_sesudah',

        'updated_at'

    ];

    /**
     * Ambil history berdasarkan queue
     */
    public function getHistory($idQueue)
    {
        return $this

            ->where('id_queue', $idQueue)

            ->orderBy('updated_at', 'DESC')

            ->findAll();
    }

    /**
     * Simpan history perubahan status
     */
    public function saveHistory($idQueue, $before, $after)
    {
        return $this->insert([

            'id_queue'        => $idQueue,

            'status_sebelum'  => $before,

            'status_sesudah'  => $after,

            'updated_at'      => date('Y-m-d H:i:s')

        ]);
    }

    /**
     * History terbaru
     */
    public function latest($limit = 20)
    {
        return $this

            ->orderBy('updated_at', 'DESC')

            ->findAll($limit);
    }

    /**
     * Hapus history berdasarkan queue
     */
    public function deleteQueueHistory($idQueue)
    {
        return $this

            ->where('id_queue', $idQueue)

            ->delete();
    }

    /**
     * Jumlah perubahan status
     */
    public function totalHistory($idQueue)
    {
        return $this

            ->where('id_queue', $idQueue)

            ->countAllResults();
    }

    /**
     * History berdasarkan status tujuan
     */
    public function byStatus($status)
    {
        return $this

            ->where('status_sesudah', $status)

            ->orderBy('updated_at', 'DESC')

            ->findAll();
    }

    /**
     * History berdasarkan rentang tanggal
     */
    public function between($start, $end)
    {
        return $this

            ->where('updated_at >=', $start)

            ->where('updated_at <=', $end)

            ->orderBy('updated_at', 'DESC')

            ->findAll();
    }

}