<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Models\InventoryLevel;
use App\Domain\Inventory\Models\Product;
use App\Domain\Inventory\Models\Warehouse;
use App\Domain\Shared\Traits\UsesBranchScope;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('حركة المخزون')]
class MovementList extends Component
{
    use WithPagination, UsesBranchScope;

    #[Url]
    public string $search = '';

    #[Url]
    public string $dateFrom = '';

    #[Url]
    public string $dateTo = '';

    #[Url]
    public string $movementType = '';

    #[Url]
    public string $direction = '';

    #[Url]
    public string $warehouseFilter = '';

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedDateFrom(): void
    {
        $this->resetPage();
    }

    public function updatedDateTo(): void
    {
        $this->resetPage();
    }

    public function updatedMovementType(): void
    {
        $this->resetPage();
    }

    public function updatedDirection(): void
    {
        $this->resetPage();
    }

    public function updatedWarehouseFilter(): void
    {
        $this->resetPage();
    }

    public function render()
    {
        $branchId = $this->getActiveBranchId();

        // Query inventory_movements table directly since the model may not exist yet
        $query = DB::table('inventory_movements')
            ->join('products', 'inventory_movements.product_id', '=', 'products.id')
            ->join('warehouses', 'inventory_movements.warehouse_id', '=', 'warehouses.id')
            ->leftJoin('users', 'inventory_movements.created_by', '=', 'users.id')
            ->when($branchId, fn ($q) => $q->where('warehouses.branch_id', $branchId))
            ->select([
                'inventory_movements.*',
                'products.name_ar as product_name_ar',
                'products.sku as product_sku',
                'warehouses.name_ar as warehouse_name_ar',
                'users.name_ar as creator_name_ar',
                'users.name as creator_name',
            ])
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('products.name_ar', 'ilike', "%{$search}%")
                       ->orWhere('products.sku', 'ilike', "%{$search}%");
                });
            })
            ->when($this->dateFrom, fn ($q) => $q->where('inventory_movements.created_at', '>=', $this->dateFrom . ' 00:00:00'))
            ->when($this->dateTo, fn ($q) => $q->where('inventory_movements.created_at', '<=', $this->dateTo . ' 23:59:59'))
            ->when($this->movementType, fn ($q) => $q->where('inventory_movements.movement_type', $this->movementType))
            ->when($this->direction, fn ($q) => $q->where('inventory_movements.direction', $this->direction))
            ->when($this->warehouseFilter, fn ($q) => $q->where('inventory_movements.warehouse_id', $this->warehouseFilter))
            ->orderByDesc('inventory_movements.created_at');

        return view('livewire.inventory.movement-list', [
            'movements' => $query->paginate(25),
            'warehouses' => Warehouse::active()->orderBy('name_ar')->get(['id', 'name_ar']),
            'movementTypeOptions' => [
                'purchase_received' => 'استلام مشتريات',
                'sale' => 'بيع',
                'transfer_out' => 'تحويل صادر',
                'transfer_in' => 'تحويل وارد',
                'return_to_stock' => 'مرتجع للمخزون',
                'return_to_supplier' => 'مرتجع للمورد',
                'adjustment_up' => 'تسوية بالزيادة',
                'adjustment_down' => 'تسوية بالنقص',
                'damage' => 'تلف',
                'loss' => 'فقد',
                'consumption' => 'استهلاك',
                'kit_assembly' => 'تجميع طقم',
                'kit_disassembly' => 'تفكيك طقم',
                'initial_stock' => 'رصيد افتتاحي',
                'count_adjustment_up' => 'تسوية جرد بالزيادة',
                'count_adjustment_down' => 'تسوية جرد بالنقص',
            ],
        ]);
    }
}
