<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Models;

use App\Core\Model;
use App\Core\App;

class ItemBatch extends Model
{
    protected static string $table = 'item_batches';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'item_id',
        'warehouse_id',
        'batch_number',
        'expiry_date',
        'quantity',
        'initial_quantity',
        'unit_cost',
        'received_date',
        'status',
        'notes',
        'created_by',
    ];

    public static function getStatuses(): array
    {
        return [
            'active'   => 'نشط',
            'expired'  => 'منتهي',
            'depleted' => 'مستنفد',
        ];
    }

    /**
     * Get active batches for an item in a warehouse, ordered by expiry (FEFO).
     */
    public static function getActiveBatches(int $itemId, int $warehouseId): array
    {
        return static::query()
            ->where('item_id', '=', $itemId)
            ->where('warehouse_id', '=', $warehouseId)
            ->where('status', '=', 'active')
            ->whereRaw('`quantity` > 0')
            ->orderBy('expiry_date', 'ASC')
            ->get();
    }

    /**
     * Get near-expiry batches (within given days).
     */
    public static function getNearExpiry(int $days = 30): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT b.*, i.`name_ar` as item_name, i.`sku`, w.`name_ar` as warehouse_name
             FROM `item_batches` b
             JOIN `inventory_items` i ON i.`id` = b.`item_id`
             JOIN `warehouses` w ON w.`id` = b.`warehouse_id`
             WHERE b.`status` = 'active'
               AND b.`quantity` > 0
               AND b.`expiry_date` BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL ? DAY)
             ORDER BY b.`expiry_date` ASC",
            [$days]
        );
    }

    /**
     * Get already expired batches that are still active.
     */
    public static function getExpired(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT b.*, i.`name_ar` as item_name, i.`sku`, w.`name_ar` as warehouse_name
             FROM `item_batches` b
             JOIN `inventory_items` i ON i.`id` = b.`item_id`
             JOIN `warehouses` w ON w.`id` = b.`warehouse_id`
             WHERE b.`status` = 'active'
               AND b.`quantity` > 0
               AND b.`expiry_date` < CURDATE()
             ORDER BY b.`expiry_date` ASC"
        );
    }
}
