<?php

namespace App\Models;

class PosOrderItemModel extends TenantModel
{
    protected $table            = 'pos_order_items';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'pos_order_id',
        'menu_item_id',
        'item_name',
        'quantity',
        'unit_price',
        'kitchen_status',
    ];

    protected $validationRules = [
        'pos_order_id' => 'required|integer',
        'menu_item_id' => 'required|integer',
        'item_name'    => 'required|max_length[150]',
        'quantity'     => 'required|integer|greater_than[0]',
        'unit_price'   => 'required|decimal',
    ];

    public function forOrder(int $orderId): array
    {
        return $this->where('pos_order_id', $orderId)->orderBy('id')->findAll();
    }

    public function markReady(int $itemId): bool
    {
        return $this->update($itemId, ['kitchen_status' => 'ready']);
    }

    public function orderTotal(int $orderId): string
    {
        $result = $this->db->query(
            'SELECT SUM(quantity * unit_price) AS total FROM pos_order_items WHERE pos_order_id = ?',
            [$orderId]
        )->getRow();

        return $result->total ?? '0.00';
    }
}
