<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class StockLedger extends Model
{
    use LogsActivity;

    protected $table = 'stock_ledgers';

    protected $fillable = [
        'igp_id',
        'qc_id',
        'po_id',
        'item_id',
        'account_id',
        'txn_type',
        'txn_id',
        'reference',
        'qty_in',
        'qty_out',
        'quantity',
        'warehouse_id',
        'bin_id',
        'lot_no',
        'remarks',
        'timestamp',
        'occurred_at',
        'length',
        'piece_quantity',
        'manufacturing_run_id',
        'unit',
        'piece_type',
        'notes',
        'created_by',
        'factory_invoice_id',
    ];

    protected $casts = [
        'igp_id' => 'integer',
        'qc_id' => 'integer',
        'po_id' => 'integer',
        'item_id' => 'integer',
        'account_id' => 'integer',
        'txn_id' => 'integer',
        'qty_in' => 'decimal:4',
        'qty_out' => 'decimal:4',
        'quantity' => 'decimal:2',
        'warehouse_id' => 'integer',
        'bin_id' => 'integer',
        'timestamp' => 'datetime',
        'occurred_at' => 'datetime',
        'length' => 'decimal:4',
        'piece_quantity' => 'integer',
        'manufacturing_run_id' => 'integer',
        'factory_invoice_id' => 'integer',
        'created_by' => 'integer',
    ];

    // Relationships
    public function igp(): BelongsTo
    {
        return $this->belongsTo(GatePass::class, 'igp_id');
    }

    public function qc(): BelongsTo
    {
        return $this->belongsTo(Qc::class, 'qc_id');
    }

    public function purchaseOrder(): BelongsTo
    {
        return $this->belongsTo(PurchaseOrder::class, 'po_id');
    }

    public function factoryInvoice(): BelongsTo
    {
        return $this->belongsTo(FactoryInvoice::class, 'factory_invoice_id');
    }

    public function purchaseOrderItem()
    {
        return $this->hasOne(PurchaseOrderItem::class, 'purchase_order_id', 'po_id')
                    ->where('item_id', $this->account_id);
    }
    public function item(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'account_id', 'id');
    }
    public function account(): BelongsTo
    {
        return $this->belongsTo(Account::class);
    }
    public function warehouse(): BelongsTo
    {
        return $this->belongsTo(Warehouse::class);
    }

    public function manufacturingRun(): BelongsTo
    {
        return $this->belongsTo(ManufacturingRun::class, 'manufacturing_run_id');
    }

    public function bin(): BelongsTo
    {
        return $this->belongsTo(WarehouseBin::class, 'bin_id');
    }

    // Scopes
    public function scopeByIgp($query, $igpId)
    {
        return $query->where('igp_id', $igpId);
    }

    public function scopeByQc($query, $qcId)
    {
        return $query->where('qc_id', $qcId);
    }

    public function scopeByPo($query, $poId)
    {
        return $query->where('po_id', $poId);
    }

    public function scopeByItem($query, $itemId)
    {
        return $query->where('item_id', $itemId);
    }

    public function scopeByWarehouse($query, $warehouseId)
    {
        return $query->where('warehouse_id', $warehouseId);
    }

    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('timestamp', [$startDate, $endDate]);
    }

    // Helper methods
    public function getFormattedQuantityAttribute()
    {
        return number_format($this->quantity, 2);
    }

    public function getFormattedTimestampAttribute()
    {
        return $this->timestamp ? $this->timestamp->format('Y-m-d H:i:s') : '-';
    }

    public function getItemNameAttribute()
    {
        return $this->item ? $this->item->name : 'Unknown Item';
    }

    public function getWarehouseNameAttribute()
    {
        return $this->warehouse ? $this->warehouse->name : 'Unknown Warehouse';
    }

    public function getBinNameAttribute()
    {
        return $this->bin ? $this->bin->name : 'Unknown Bin';
    }

    public function getIgpNumberAttribute()
    {
        return $this->igp ? $this->igp->gate_pass_number : '-';
    }

    public function getQcNumberAttribute()
    {
        return $this->qc ? $this->qc->qc_number : '-';
    }

    public function getPoNumberAttribute()
    {
        return $this->purchaseOrder ? $this->purchaseOrder->po_number : '-';
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('stock_ledger')
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
