<?php

namespace App\Models;

use CodeIgniter\Model;

class OrderItemModel extends Model
{
    protected $table            = 'order_items';
    protected $primaryKey       = 'id_item';
    protected $returnType       = 'array';
    protected $useAutoIncrement = true;

    protected $useSoftDeletes = false;

    protected $allowedFields = [
        'id_order',
        'id_product',
        'product_name',
        'description',
        'qty',
        'price',
        'subtotal'
    ];

    protected $useTimestamps = false;

    protected $validationRules = [
        'id_order' => 'required|integer',
        'qty'      => 'required|integer|greater_than[0]',
        'price'    => 'required|decimal',
        'subtotal' => 'required|decimal'
    ];

    protected $validationMessages = [
        'qty' => [
            'greater_than' => 'Jumlah minimal 1.'
        ]
    ];

    protected $skipValidation = false;

    /**
     * Detail Item berdasarkan Order
     */
    public function getItems($idOrder)
    {
        return $this->select('
                order_items.*,
                products.product_photo,
                products.barcode,
                products.is_custom,
                products.stock_type
            ')
            ->join(
                'products',
                'products.id_product = order_items.id_product',
                'left'
            )
            ->where('order_items.id_order', $idOrder)
            ->orderBy('order_items.id_item', 'ASC')
            ->findAll();
    }

    /**
     * Hitung Total Order
     */
    public function calculateTotal($idOrder)
    {
        $row = $this->selectSum('subtotal')
            ->where('id_order', $idOrder)
            ->first();

        return (float) ($row['subtotal'] ?? 0);
    }

    /**
     * Jumlah Item
     */
    public function totalItem($idOrder)
    {
        return $this->where('id_order', $idOrder)
                    ->countAllResults();
    }

    /**
     * Hapus semua item berdasarkan Order
     */
    public function deleteByOrder($idOrder)
    {
        return $this->where('id_order', $idOrder)
                    ->delete();
    }

    /**
     * Semua Item
     */
    public function getAll()
    {
        return $this->select('
                order_items.*,
                orders.order_number,
                products.product_photo,
                products.barcode
            ')
            ->join(
                'orders',
                'orders.id_order = order_items.id_order'
            )
            ->join(
                'products',
                'products.id_product = order_items.id_product',
                'left'
            )
            ->orderBy('order_items.id_item', 'DESC')
            ->findAll();
    }
}
