<?php

namespace App\Models;

use App\Models\Traits\HasAuditFields;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SkuApproval extends Model
{
    use HasFactory, SoftDeletes, HasAuditFields;

    protected $table = 'sku_approvals';

    /**
     * Status constants
     */
    public const STATUS_PENDING = 'pending';
    public const STATUS_APPROVED = 'approved';
    public const STATUS_REJECTED = 'rejected';

    /**
     * Stock status constants
     */
    public const STOCK_STATUS_AVAILABLE = 'available';
    public const STOCK_STATUS_PARTIAL = 'partial';
    public const STOCK_STATUS_UNAVAILABLE = 'unavailable';

    protected $fillable = [
        'customer_id',
        'items',
        'date',
        'approved_date',
        'status',
        'action_date',
        'action_by',
        'created_by',
        'updated_by',
        'stock_status',
    ];

    protected $casts = [
        'items' => 'array',
        'date' => 'date',
        'approved_date' => 'date',
        'action_date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // ──────────────────────────────────────────────────────────────────────────
    // RELATIONSHIPS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get the customer for this approval.
     */
    public function customer()
    {
        return $this->belongsTo(CustomerVendor::class, 'customer_id');
    }

    /**
     * Get the user who performed the action.
     */
    public function actionUser()
    {
        return $this->belongsTo(User::class, 'action_by');
    }

    /**
     * Get the user who created this approval.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // ──────────────────────────────────────────────────────────────────────────
    // SCOPES
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Filter by pending status
     */
    public function scopePending(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    /**
     * Filter by approved status
     */
    public function scopeApproved(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_APPROVED);
    }

    /**
     * Filter by rejected status
     */
    public function scopeRejected(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_REJECTED);
    }

    /**
     * Filter by customer
     */
    public function scopeForCustomer(Builder $query, int $customerId): Builder
    {
        return $query->where('customer_id', $customerId);
    }

    /**
     * Filter by stock status
     */
    public function scopeWithStockStatus(Builder $query, string $status): Builder
    {
        return $query->where('stock_status', $status);
    }

    /**
     * Filter by date range
     */
    public function scopeBetweenDates(Builder $query, $startDate, $endDate): Builder
    {
        return $query->whereBetween('date', [$startDate, $endDate]);
    }

    /**
     * Filter awaiting action
     */
    public function scopeAwaitingAction(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_PENDING)
                     ->orderBy('date', 'asc');
    }

    // ──────────────────────────────────────────────────────────────────────────
    // ACCESSORS & HELPERS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get all valid statuses
     */
    public static function getStatuses(): array
    {
        return [
            self::STATUS_PENDING,
            self::STATUS_APPROVED,
            self::STATUS_REJECTED,
        ];
    }

    /**
     * Get all valid stock statuses
     */
    public static function getStockStatuses(): array
    {
        return [
            self::STOCK_STATUS_AVAILABLE,
            self::STOCK_STATUS_PARTIAL,
            self::STOCK_STATUS_UNAVAILABLE,
        ];
    }

    /**
     * Check if approval is pending
     */
    public function isPending(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    /**
     * Check if approval is approved
     */
    public function isApproved(): bool
    {
        return $this->status === self::STATUS_APPROVED;
    }

    /**
     * Check if approval is rejected
     */
    public function isRejected(): bool
    {
        return $this->status === self::STATUS_REJECTED;
    }

    /**
     * Get item count
     */
    public function getItemCount(): int
    {
        return is_array($this->items) ? count($this->items) : 0;
    }

    /**
     * Get SKU items as models
     */
    public function getSkuItems()
    {
        if (!is_array($this->items) || empty($this->items)) {
            return collect();
        }

        return SkuMaster::whereIn('id', $this->items)->get();
    }

    /**
     * Approve this request
     */
    public function approve(int $userId): bool
    {
        $this->status = self::STATUS_APPROVED;
        $this->approved_date = now();
        $this->action_date = now();
        $this->action_by = $userId;
        return $this->save();
    }

    /**
     * Reject this request
     */
    public function reject(int $userId): bool
    {
        $this->status = self::STATUS_REJECTED;
        $this->action_date = now();
        $this->action_by = $userId;
        return $this->save();
    }
}
