<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class StockMovement extends Model
{
    use HasFactory;

    protected $table = 't_stock_movements';

    protected $fillable = [
        'store_id',
        'raw_material_id',
        'movement_type',
        'reference_type',
        'reference_id',
        'qty_before',
        'qty_movement',
        'qty_after',
        'uom',
        'notes',
        'movement_date',
        'movement_time',
        'created_by',
        'delete_flag'
    ];

    protected $casts = [
        'qty_before' => 'decimal:2',
        'qty_movement' => 'decimal:2',
        'qty_after' => 'decimal:2',
        'movement_date' => 'date',
        'movement_time' => 'datetime',
        'delete_flag' => 'boolean'
    ];

    // Relationships
    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id');
    }

    public function rawMaterial()
    {
        return $this->belongsTo(RawMaterial::class, 'raw_material_id');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // Static methods for stock operations
    public static function recordMovement($storeId, $rawMaterialId, $movementType, $qtyMovement, $uom, $referenceType = null, $referenceId = null, $notes = null, $userId = null)
    {
        $userId = $userId ?? auth()->id() ?? 1;
        
        // Get current stock
        $currentStock = CurrentStock::getCurrentStock($storeId, $rawMaterialId);
        $qtyBefore = $currentStock ? $currentStock->qty_total_converted : 0;
        
        // Calculate qty after based on movement type
        $qtyAfter = $qtyBefore;
        switch ($movementType) {
            case 'IN':
            case 'OPENING':
                $qtyAfter = $qtyBefore + $qtyMovement;
                break;
            case 'OUT':
                $qtyAfter = $qtyBefore - $qtyMovement;
                break;
            case 'ADJUSTMENT':
                $qtyAfter = $qtyMovement; // Direct set to new value
                break;
            case 'TRANSFER':
                // Handle transfer logic if needed
                break;
        }

        // Create movement record
        $movement = static::create([
            'store_id' => $storeId,
            'raw_material_id' => $rawMaterialId,
            'movement_type' => $movementType,
            'reference_type' => $referenceType,
            'reference_id' => $referenceId,
            'qty_before' => $qtyBefore,
            'qty_movement' => $qtyMovement,
            'qty_after' => $qtyAfter,
            'uom' => $uom,
            'notes' => $notes,
            'movement_date' => Carbon::now()->toDateString(),
            'movement_time' => Carbon::now(),
            'created_by' => $userId
        ]);

        // Update current stock
        CurrentStock::updateStock($storeId, $rawMaterialId, $qtyAfter, $userId);

        return $movement;
    }

    // Get stock movements for a specific item
    public static function getMovementHistory($storeId, $rawMaterialId, $limit = 50)
    {
        return static::where('store_id', $storeId)
            ->where('raw_material_id', $rawMaterialId)
            ->where('delete_flag', 0)
            ->with(['store', 'rawMaterial', 'createdBy'])
            ->orderBy('movement_time', 'desc')
            ->limit($limit)
            ->get();
    }

    // Get movements by date range
    public static function getMovementsByDateRange($storeId, $startDate, $endDate, $rawMaterialId = null)
    {
        $query = static::where('store_id', $storeId)
            ->whereBetween('movement_date', [$startDate, $endDate])
            ->where('delete_flag', 0)
            ->with(['rawMaterial', 'createdBy']);

        if ($rawMaterialId) {
            $query->where('raw_material_id', $rawMaterialId);
        }

        return $query->orderBy('movement_time', 'desc')->get();
    }
}