<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\DB;
use App\Models\ProductStock;
use App\Models\StockTransaction;

class StockTransfer extends Model
{
    protected $guarded = [];

    protected $casts = [
        'transfer_date' => 'date',
        'quantity' => 'float',
        'conversion_value' => 'float',
    ];

    // --- LOGIKA OTOMATIS (MUTASI) ---
    protected static function booted()
    {
        // 1. SEBELUM SIMPAN: Cek Stok Asal Cukup Gak?
        static::creating(function ($transfer) {
            // Generate Nomor TRF jika kosong
            if (empty($transfer->transfer_number)) {
                $transfer->transfer_number = 'TRF-' . date('ymd') . '-' . rand(100, 999);
            }

            // Cek Stok Gudang Asal
            $stockAsal = ProductStock::where('branch_id', $transfer->source_branch_id)
                ->where('product_id', $transfer->product_id)
                ->first();
            
            $sisaStok = $stockAsal ? $stockAsal->quantity : 0;
            
            // Hitung kebutuhan dalam satuan dasar
            $qtyNeeded = $transfer->quantity * $transfer->conversion_value;

            if ($sisaStok < $qtyNeeded) {
                // Batalkan jika stok kurang
                throw new \Exception("Stok di Gudang Asal tidak cukup! Sisa: " . $stockAsal->product->stok_terbilang($sisaStok));
            }
        });

        // 2. SETELAH SIMPAN: Eksekusi Perpindahan
        static::created(function ($transfer) {
            DB::transaction(function () use ($transfer) {
                // A. KELUAR DARI GUDANG ASAL (Minus)
                StockTransaction::create([
                    'branch_id'      => $transfer->source_branch_id,
                    'product_id'     => $transfer->product_id,
                    'type'           => 'transfer_out', // Tipe Mutasi Keluar
                    'input_quantity' => -1 * abs($transfer->quantity), // NEGATIF
                    'input_unit'     => $transfer->unit,
                    'user_id'        => $transfer->user_id,
                    'note'           => 'Mutasi Ke: ' . $transfer->destinationBranch->name . ' (' . $transfer->transfer_number . ')',
                ]);

                // B. MASUK KE GUDANG TUJUAN (Plus)
                StockTransaction::create([
                    'branch_id'      => $transfer->destination_branch_id,
                    'product_id'     => $transfer->product_id,
                    'type'           => 'transfer_in', // Tipe Mutasi Masuk
                    'input_quantity' => abs($transfer->quantity), // POSITIF
                    'input_unit'     => $transfer->unit,
                    'user_id'        => $transfer->user_id,
                    'note'           => 'Mutasi Dari: ' . $transfer->sourceBranch->name . ' (' . $transfer->transfer_number . ')',
                ]);
            });
        });
    }

    // RELASI
    public function sourceBranch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'source_branch_id');
    }

    public function destinationBranch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'destination_branch_id');
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}