<?php

namespace App\Models;

use CodeIgniter\Model;
use DateTime;

class OrderItems extends Model
{
    protected $table = 'orders_item';
    protected $allowedFields = ['order_id', 'product_id', 'puissance', 'rate', 'amount','qty'];

    public function insertOrderItem($data)
    {
        return $this->insert($data);
    }

    public function getOrdersItemData($order_id = null)
    {
        if (!$order_id) {
            return false;
        }
        
        return $this->where('order_id', $order_id)->findAll();
    }

    public function getAllSoldProductToday() {
        return $this->select('
                    COUNT(orders_item.id) as total_product_sold, 
                    (SELECT SUM(products.qty) FROM products) as total_unsold_product
                ')
                ->join('orders', 'orders_item.order_id = orders.id')
                ->where('DATE(orders.date_time)', date('Y-m-d')) 
                ->get()
                ->getRow();
    }
    
    public function getSumOrdersItemData($order_id = null)
    {
        if (!$order_id) {
            return 0;
        }
    
        return $this->where('order_id', $order_id)->countAllResults();
    }
    
    public function updateOrderItem(int $id, array $data)
    {
        return $this->where('order_id', $id)
                    ->set($data)
                    ->update();
    }

    public function getProductIds(array $orderIds): array
    {
        if (empty($orderIds)) {
            return [];
        }

        $items = $this->select('product_id')
                      ->whereIn('order_id', $orderIds)
                      ->findAll();

        return array_column($items, 'product_id');
    }
}