<?php

// app/Models/OrderItemModel.php

namespace App\Models;

use CodeIgniter\Model;

class OrderItemModel extends Model
{
    protected $table = 'orders_item';
    protected $primaryKey = 'id';
    protected $allowedFields = ['order_id', 'product_id', 'item_code', 'qty', 'rate', 'amount', 'details', 'width', 'length', 'pcs','tipe', 'image', 'reject', 'hasilqc', 'totalqc', 'totalreject'];
    
    public function insertOrderItem($data)
    {
        return $this->insert($data);
    }

    public function getItemby($id)
    {

            if ($id) {
                return $this->where('order_id', $id)
                ->findAll();
            } else {
                return $this->orderBy('order_id', 'DESC')->findAll();
            }

    }

    public function getItemByItemCode($item_code)
    {

            if ($item_code) {
                return $this->where('item_code', $item_code)
                ->findAll();
            } else {
                return $this->orderBy('item_code', 'DESC')->findAll();
            }

    }

    // Dalam model orderItemModel
public function getDetailsByItemCode($item_code) {
    // Lakukan query ke database untuk mengambil detail berdasarkan item_code
    $query = $this->db->table('orders_item')
                     ->select('details')
                     ->where('item_code', $item_code)
                     ->get();
    
    // Periksa apakah ada hasil yang ditemukan
    if ($query->numRows() > 0) {
        // Jika ada, kembalikan hasilnya dalam bentuk array
        return $query->getRowArray();
    } else {
        // Jika tidak ada, kembalikan array kosong atau nilai null, tergantung pada kebutuhan Anda
        return null;
    }
}

    public function deleteOrderItemsByOrderId($orderId)
    {
        return $this->where('order_id', $orderId)->delete();
    }

    public function getTotalBarangKeluar($productId)
    {
        return $this->selectSum('totalqc')
        ->where('product_id', $productId)
        ->first()['totalqc'];
    }


    public function updateOrder($orderId, $data)
    {
        // Misalnya, kita ingin memperbarui data berdasarkan order_id
        $this->where('order_id', $orderId)->update($data);
    }

    public function getByItemCode($itemCode)
    {
        return $this->where('item_code', $itemCode)->first();
    }

    public function updateOrderItem($orderItemId, $orderItemData)
    {
        // Begin transaction
        $this->db->transBegin();

        try {
            // Update order item for the given order item ID
            $this->update($orderItemId, $orderItemData);

            // Commit transaction if all queries succeed
            $this->db->transCommit();

            return true;
        } catch (\Exception $e) {
            // Rollback transaction if any query fails
            $this->db->transRollback();
            log_message('error', 'Error in OrderItemModel: ' . $e->getMessage());
            return false;
        }
    }
    
    
}
