<?php

namespace App\Models\Warehouse;

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

class Supplier extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'suppliers';

    protected $fillable = [
        'supplier_code',
        'name',
        'contact_person',
        'email',
        'phone',
        'mobile',
        'address',
        'city',
        'state',
        'country',
        'postal_code',
        'tax_number',
        'website',
        'bank_name',
        'bank_account',
        'payment_terms',
        'credit_limit',
        'currency',
        'status',
        'is_active',
        'notes',
        'rating',
        'created_by',
    ];

    protected $casts = [
        'credit_limit' => 'decimal:2',
        'rating' => 'decimal:1',
        'is_active' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    protected $attributes = [
        'status' => 'active',
        'is_active' => true,
        'currency' => 'USD',
        'payment_terms' => 'Net 30',
        'rating' => 0.0,
    ];

    // Relationships

    /**
     * Get the user who created this supplier.
     */
    public function createdBy()
    {
        return $this->belongsTo(\App\Models\User::class, 'created_by');
    }

    /**
     * Get incoming transactions from this supplier.
     */
    public function incomingTransactions()
    {
        return $this->hasMany(IncomingTransaction::class);
    }

    /**
     * Get purchase orders for this supplier.
     */
    public function purchaseOrders()
    {
        return $this->hasMany(PurchaseOrder::class);
    }

    /**
     * Get supplier items/products.
     */
    public function items()
    {
        return $this->belongsToMany(Item::class, 'supplier_items')
                    ->withPivot('supplier_item_code', 'unit_cost', 'lead_time_days', 'minimum_order_quantity')
                    ->withTimestamps();
    }

    /**
     * Get incoming operations from this supplier.
     */
    public function incomingOperations()
    {
        return $this->hasMany(IncomingOperation::class);
    }

    // Scopes

    /**
     * Scope for active suppliers.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope for inactive suppliers.
     */
    public function scopeInactive($query)
    {
        return $query->where('status', 'inactive');
    }

    /**
     * Scope for suppliers with good rating.
     */
    public function scopeHighRated($query, $minRating = 4.0)
    {
        return $query->where('rating', '>=', $minRating);
    }

    /**
     * Search scope.
     */
    public function scopeSearch($query, $search)
    {
        if (empty($search)) {
            return $query;
        }

        return $query->where(function ($q) use ($search) {
            $q->where('name', 'LIKE', "%{$search}%")
              ->orWhere('supplier_code', 'LIKE', "%{$search}%")
              ->orWhere('contact_person', 'LIKE', "%{$search}%")
              ->orWhere('email', 'LIKE', "%{$search}%")
              ->orWhere('phone', 'LIKE', "%{$search}%");
        });
    }

    // Accessors & Mutators

    /**
     * Get the supplier's full address.
     */
    public function getFullAddressAttribute()
    {
        $parts = array_filter([
            $this->address,
            $this->city,
            $this->state,
            $this->postal_code,
            $this->country,
        ]);

        return implode(', ', $parts);
    }

    /**
     * Get the supplier's performance score.
     */
    public function getPerformanceScoreAttribute()
    {
        return $this->calculatePerformanceScore();
    }

    /**
     * Get the supplier's status badge color.
     */
    public function getStatusColorAttribute()
    {
        return match ($this->status) {
            'active' => 'green',
            'inactive' => 'red',
            'suspended' => 'yellow',
            default => 'gray',
        };
    }

    /**
     * Get formatted rating.
     */
    public function getFormattedRatingAttribute()
    {
        return number_format($this->rating, 1);
    }

    // Helper Methods

    /**
     * Generate supplier code based on ID (for backward compatibility).
     * Note: New approach generates code after creation using ID.
     */
    public static function generateSupplierCode($id = null)
    {
        if ($id) {
            return 'SUP' . str_pad($id, 4, '0', STR_PAD_LEFT);
        }

        // Fallback for backward compatibility - predict next ID
        $nextId = self::max('id') + 1;
        return 'SUP' . str_pad($nextId, 4, '0', STR_PAD_LEFT);
    }

    /**
     * Calculate performance score based on various metrics.
     */
    public function calculatePerformanceScore()
    {
        $scores = [];

        // Rating score (40%)
        $scores['rating'] = ($this->rating / 5) * 40;

        // On-time delivery score (30%)
        $onTimeScore = $this->calculateOnTimeDeliveryScore();
        $scores['delivery'] = $onTimeScore * 30;

        // Quality score (20%)
        $qualityScore = $this->calculateQualityScore();
        $scores['quality'] = $qualityScore * 20;

        // Responsiveness score (10%)
        $responsivenessScore = $this->calculateResponsivenessScore();
        $scores['responsiveness'] = $responsivenessScore * 10;

        return array_sum($scores);
    }

    /**
     * Calculate on-time delivery score.
     */
    protected function calculateOnTimeDeliveryScore()
    {
        $recentTransactions = $this->incomingTransactions()
            ->where('created_at', '>=', Carbon::now()->subMonths(6))
            ->get();

        if ($recentTransactions->isEmpty()) {
            return 0.8; // Default score
        }

        $onTimeCount = $recentTransactions->where('delivery_status', 'on_time')->count();
        return $onTimeCount / $recentTransactions->count();
    }

    /**
     * Calculate quality score.
     */
    protected function calculateQualityScore()
    {
        // This would be based on return rates, defect rates, etc.
        // For now, return a default score
        return 0.85;
    }

    /**
     * Calculate responsiveness score.
     */
    protected function calculateResponsivenessScore()
    {
        // This would be based on response times to inquiries, etc.
        // For now, return a default score
        return 0.9;
    }

    /**
     * Get total orders count.
     */
    public function getTotalOrdersCount()
    {
        return $this->incomingTransactions()->count();
    }

    /**
     * Get total order value.
     */
    public function getTotalOrderValue()
    {
        return $this->incomingTransactions()
                    ->where('status', 'completed')
                    ->sum('total_amount') ?? 0;
    }

    /**
     * Get average order value.
     */
    public function getAverageOrderValue()
    {
        $totalValue = $this->getTotalOrderValue();
        $totalOrders = $this->getTotalOrdersCount();

        return $totalOrders > 0 ? $totalValue / $totalOrders : 0;
    }

    /**
     * Get recent activity.
     */
    public function getRecentActivity($limit = 5)
    {
        return $this->incomingTransactions()
                    ->with('items')
                    ->orderBy('created_at', 'desc')
                    ->limit($limit)
                    ->get();
    }

    /**
     * Check if supplier is overdue on payments.
     */
    public function hasOverduePayments()
    {
        // This would check for overdue invoices
        // Implementation depends on your payment tracking system
        return false;
    }

    /**
     * Get supplier's top purchased items.
     */
    public function getTopPurchasedItems($limit = 5)
    {
        return $this->items()
                    ->withPivot('unit_cost', 'lead_time_days')
                    ->orderBy('supplier_items.created_at', 'desc')
                    ->limit($limit)
                    ->get();
    }
}