<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Models;

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

class StockMovement extends Model
{
    protected static string $table = 'stock_movements';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = false;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'warehouse_id',
        'item_id',
        'movement_type',
        'direction',
        'quantity',
        'unit_cost',
        'total_cost',
        'batch_id',
        'reference_type',
        'reference_id',
        'transfer_id',
        'notes',
        'movement_date',
        'created_by',
    ];

    public static function getMovementTypes(): array
    {
        return [
            'purchase_in'     => 'شراء',
            'transfer_in'     => 'تحويل وارد',
            'return_in'       => 'مرتجع',
            'adjustment_in'   => 'تسوية (+)',
            'opening_balance' => 'رصيد افتتاحي',
            'sale_out'        => 'بيع',
            'transfer_out'    => 'تحويل صادر',
            'damage_out'      => 'تالف',
            'expired_out'     => 'منتهي صلاحية',
            'consumed_out'    => 'مستهلك',
            'adjustment_out'  => 'تسوية (-)',
        ];
    }

    public static function getMovementTypeLabel(string $type): string
    {
        $types = self::getMovementTypes();
        return $types[$type] ?? $type;
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = '1=1';
        $params = [];

        if (!empty($filters['item_id'])) {
            $where .= ' AND m.`item_id` = ?';
            $params[] = (int) $filters['item_id'];
        }

        if (!empty($filters['warehouse_id'])) {
            $where .= ' AND m.`warehouse_id` = ?';
            $params[] = (int) $filters['warehouse_id'];
        }

        if (!empty($filters['movement_type'])) {
            $where .= ' AND m.`movement_type` = ?';
            $params[] = $filters['movement_type'];
        }

        if (!empty($filters['direction'])) {
            $where .= ' AND m.`direction` = ?';
            $params[] = $filters['direction'];
        }

        if (!empty($filters['date_from'])) {
            $where .= ' AND m.`movement_date` >= ?';
            $params[] = $filters['date_from'];
        }

        if (!empty($filters['date_to'])) {
            $where .= ' AND m.`movement_date` <= ?';
            $params[] = $filters['date_to'];
        }

        $countRow = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM `stock_movements` m WHERE {$where}",
            $params
        );
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT m.*, i.`name_ar` as item_name, i.`sku`, w.`name_ar` as warehouse_name
             FROM `stock_movements` m
             JOIN `inventory_items` i ON i.`id` = m.`item_id`
             JOIN `warehouses` w ON w.`id` = m.`warehouse_id`
             WHERE {$where}
             ORDER BY m.`created_at` DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }
}
