<?php

namespace App\Models;

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

class StockOpname extends Model
{
    use HasFactory;

    protected $table = 't_stock_opnames';

    protected $fillable = [
        'so_number',
        'store_id',
        'so_date',
        'status',
        'notes',
        'editing_by',
        'editing_at',
        'delete_flag',
        'created_by',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'so_date' => 'date',
        'editing_at' => 'datetime',
    ];

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

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

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

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

    public function details()
    {
        return $this->hasMany(StockOpnameDetail::class, 'so_id');
    }

    public function itemRequests()
    {
        return $this->hasMany(ItemRequest::class, 'stock_opname_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $today = date('Ymd');
            $lastNumber = static::selectRaw("so_number")
                ->where('delete_flag', '0')
                ->where('so_number', 'like', "SO{$today}%")
                ->orderByRaw("CAST(SUBSTRING(so_number FROM 11) AS INTEGER) DESC")
                ->value('so_number');

            $lastSeq = $lastNumber ? intval(substr($lastNumber, 10)) : 0;
            $newSeq = $lastSeq + 1;

            $model->so_number = 'SO' . $today . str_pad($newSeq, 4, '0', STR_PAD_LEFT);
        });
    }

    /**
     * Check if SO is currently being edited by any user
     */
    public function isBeingEdited()
    {
        return $this->editing_by !== null;
    }

    /**
     * Check if SO is being edited by current user
     */
    public function isBeingEditedByCurrentUser()
    {
        return $this->editing_by === auth()->id();
    }

    /**
     * Check if SO is being edited by another user
     */
    public function isBeingEditedByAnotherUser()
    {
        return $this->isBeingEdited() && !$this->isBeingEditedByCurrentUser();
    }

    /**
     * Lock SO for editing by current user
     */
    public function lockForEditing()
    {
        $this->update([
            'editing_by' => auth()->id(),
            'editing_at' => now()
        ]);
    }

    /**
     * Unlock SO from editing
     */
    public function unlockFromEditing()
    {
        $this->update([
            'editing_by' => null,
            'editing_at' => null
        ]);
    }

    /**
     * Get editing information
     */
    public function getEditingInfo()
    {
        if (!$this->isBeingEdited()) {
            return null;
        }

        return [
            'user' => $this->editor ? $this->editor->fullname : 'Unknown User',
            'since' => $this->editing_at ? $this->editing_at->diffForHumans() : 'Unknown',
            'timestamp' => $this->editing_at ? $this->editing_at->format('d M Y H:i:s') : 'Unknown'
        ];
    }

    /**
     * Update heartbeat timestamp (keep lock alive)
     */
    public function updateHeartbeat()
    {
        if ($this->isBeingEditedByCurrentUser()) {
            $this->update(['editing_at' => now()]);
            return true;
        }
        return false;
    }
}