<?php

namespace App\Livewire\Inventory\PurchaseOrders;

use App\Models\PurchaseOrder;
use App\Models\StockMovement;
use Livewire\Component;

class Show extends Component
{
    public PurchaseOrder $purchaseOrder;
    public $receivingMode = false;
    public $receivedQuantities = [];

    public function mount(PurchaseOrder $purchaseOrder)
    {
        $this->purchaseOrder = $purchaseOrder->load(['supplier', 'items.part']);
        
        // Initialize received quantities
        foreach ($this->purchaseOrder->items as $item) {
            $this->receivedQuantities[$item->id] = $item->quantity_received ?? 0;
        }
    }

    public function startReceiving()
    {
        $this->receivingMode = true;
    }

    public function cancelReceiving()
    {
        $this->receivingMode = false;
        // Reset quantities
        foreach ($this->purchaseOrder->items as $item) {
            $this->receivedQuantities[$item->id] = $item->quantity_received ?? 0;
        }
    }

    public function receiveItems()
    {
        $this->validate([
            'receivedQuantities.*' => 'required|integer|min:0',
        ]);

        $totalReceived = 0;
        $totalOrdered = 0;

        foreach ($this->purchaseOrder->items as $item) {
            $receivedQty = $this->receivedQuantities[$item->id];
            $previouslyReceived = $item->quantity_received ?? 0;
            $newlyReceived = $receivedQty - $previouslyReceived;

            if ($newlyReceived > 0) {
                // Update item received quantity
                $item->update(['quantity_received' => $receivedQty]);

                // Add to part stock
                $item->part->increment('quantity_on_hand', $newlyReceived);

                // Create stock movement
                StockMovement::create([
                    'part_id' => $item->part_id,
                    'movement_type' => 'in',
                    'quantity' => $newlyReceived,
                    'reference_type' => 'purchase_order',
                    'reference_id' => $this->purchaseOrder->id,
                    'notes' => "Received from PO #{$this->purchaseOrder->po_number}",
                    'created_by' => auth()->id(),
                ]);
            }

            $totalReceived += $receivedQty;
            $totalOrdered += $item->quantity_ordered;
        }

        // Update purchase order status
        if ($totalReceived == 0) {
            $status = $this->purchaseOrder->status;
        } elseif ($totalReceived >= $totalOrdered) {
            $status = 'received';
        } else {
            $status = 'partial';
        }

        $this->purchaseOrder->update([
            'status' => $status,
            'received_date' => $totalReceived > 0 ? now() : null,
        ]);

        $this->receivingMode = false;
        $this->purchaseOrder->refresh();

        session()->flash('success', 'Items received successfully!');
    }

    public function markAsOrdered()
    {
        $this->purchaseOrder->update(['status' => 'ordered']);
        $this->purchaseOrder->refresh();
        
        session()->flash('success', 'Purchase order marked as ordered!');
    }

    public function cancelOrder()
    {
        $this->purchaseOrder->update(['status' => 'cancelled']);
        $this->purchaseOrder->refresh();
        
        session()->flash('success', 'Purchase order cancelled!');
    }

    public function render()
    {
        return view('livewire.inventory.purchase-orders.show');
    }
}
