<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Enums\MovementDirection;
use App\Domain\Inventory\Models\InventoryMovement;
use App\Domain\Inventory\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل المنتج')]
class ProductShow extends Component
{
    public Product $product;

    public function mount(Product $product): void
    {
        $this->authorize('inventory.list');
        $this->product = $product->load(['category', 'inventoryLevels.warehouse', 'branch']);
    }

    public function render()
    {
        $levels = $this->product->inventoryLevels;

        $totalOnHand = $levels->sum('quantity_on_hand');
        $totalReserved = $levels->sum('quantity_reserved');
        $totalAvailable = $levels->sum('quantity_available');

        $movements = InventoryMovement::where('product_id', $this->product->id)
            ->with('warehouse')
            ->orderByDesc('created_at')
            ->limit(30)
            ->get();

        // Analytics
        $totalIn = InventoryMovement::where('product_id', $this->product->id)
            ->where('direction', MovementDirection::In->value)
            ->sum('quantity');

        $totalSold = InventoryMovement::where('product_id', $this->product->id)
            ->where('direction', MovementDirection::Out->value)
            ->where('movement_type', 'sale')
            ->sum('quantity');

        $firstMovement = InventoryMovement::where('product_id', $this->product->id)
            ->orderBy('created_at')
            ->value('created_at');

        $monthsActive = 1;
        if ($firstMovement) {
            $monthsActive = max(1, (int) now()->diffInMonths($firstMovement));
        }

        $totalMovements = InventoryMovement::where('product_id', $this->product->id)->sum('quantity');
        $avgMonthlyMovement = round($totalMovements / $monthsActive, 1);

        // Profit margin
        $margin = 0;
        if ($this->product->selling_price > 0 && $this->product->cost_price > 0) {
            $margin = round((($this->product->selling_price - $this->product->cost_price) / $this->product->selling_price) * 100, 1);
        }

        return view('livewire.inventory.product-show', [
            'levels' => $levels,
            'totalOnHand' => $totalOnHand,
            'totalReserved' => $totalReserved,
            'totalAvailable' => $totalAvailable,
            'movements' => $movements,
            'totalIn' => $totalIn,
            'totalSold' => $totalSold,
            'avgMonthlyMovement' => $avgMonthlyMovement,
            'margin' => $margin,
        ]);
    }
}
