<?php

namespace App\Livewire\Inventory\StockMovements;

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

class Create extends Component
{
    public $part_id = '';
    public $movement_type = 'adjustment';
    public $quantity = '';
    public $notes = '';
    public $reference_type = 'manual_adjustment';

    public function mount()
    {
        // Pre-select part if passed in URL
        if (request()->has('part_id')) {
            $this->part_id = request()->get('part_id');
        }
    }

    protected $rules = [
        'part_id' => 'required|exists:parts,id',
        'movement_type' => 'required|in:in,out,adjustment',
        'quantity' => 'required|integer|min:1',
        'notes' => 'required|string|max:500',
    ];

    public function save()
    {
        $this->validate();

        $part = Part::find($this->part_id);
        
        // Create stock movement
        StockMovement::create([
            'part_id' => $this->part_id,
            'movement_type' => $this->movement_type,
            'quantity' => $this->quantity,
            'reference_type' => $this->reference_type,
            'notes' => $this->notes,
            'created_by' => auth()->id(),
        ]);

        // Update part stock
        if ($this->movement_type === 'in' || $this->movement_type === 'adjustment') {
            $part->increment('quantity_on_hand', $this->quantity);
        } elseif ($this->movement_type === 'out') {
            $part->decrement('quantity_on_hand', $this->quantity);
        }

        session()->flash('success', 'Stock movement recorded successfully!');
        
        return $this->redirect(route('inventory.stock-movements.index'), navigate: true);
    }

    public function render()
    {
        $parts = Part::orderBy('name')->get();

        return view('livewire.inventory.stock-movements.create', [
            'parts' => $parts,
        ]);
    }
}
