<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'bio',
        'city',
        'state',
        'country',
        'avatar',
        'payment_methods',
        'is_on_vacation',
        'vacation_message',
        'vacation_start_date',
        'vacation_end_date',
        'ip_address',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'last_seen_at' => 'datetime',
            'rating' => 'decimal:2',
            'is_active' => 'boolean',
            'is_admin' => 'boolean',
            'payment_methods' => 'array',
            'is_on_vacation' => 'boolean',
            'vacation_start_date' => 'datetime',
            'vacation_end_date' => 'datetime',
            'reviewed_at' => 'datetime',
        ];
    }

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

    public function loginHistory()
    {
        return $this->hasMany(LoginHistory::class)->orderByDesc('logged_in_at');
    }

    public function items()
    {
        return $this->hasMany(Item::class);
    }

    public function sentMessages()
    {
        return $this->hasMany(Message::class, 'sender_id');
    }

    public function receivedMessages()
    {
        return $this->hasMany(Message::class, 'recipient_id');
    }

    public function buyQueue()
    {
        return $this->hasMany(BuyQueue::class);
    }

    public function soldTransactions()
    {
        return $this->hasMany(Transaction::class, 'seller_id');
    }

    public function boughtTransactions()
    {
        return $this->hasMany(Transaction::class, 'buyer_id');
    }

    public function givenFeedback()
    {
        return $this->hasMany(Feedback::class, 'reviewer_id');
    }

    public function receivedFeedback()
    {
        return $this->hasMany(Feedback::class, 'reviewee_id');
    }

    public function watchlist()
    {
        return $this->hasMany(Watchlist::class);
    }

    public function watchedItems()
    {
        return $this->belongsToMany(Item::class, 'watchlists')->withTimestamps();
    }

    public function offersAsBuyer()
    {
        return $this->hasMany(Offer::class, 'buyer_id');
    }

    public function offersAsSeller()
    {
        return $this->hasMany(Offer::class, 'seller_id');
    }

    public function preferences()
    {
        return $this->hasOne(UserPreference::class);
    }

    public function interactions()
    {
        return $this->hasMany(UserInteraction::class);
    }

    public function conversations()
    {
        return $this->belongsToMany(Conversation::class, 'conversation_participants')
            ->withPivot('last_read_at')
            ->withTimestamps()
            ->orderBy('last_message_at', 'desc');
    }

    public function messages()
    {
        return $this->hasMany(Message::class);
    }

    public function trustLinks()
    {
        return $this->hasMany(UserTrustLink::class);
    }

    public function verifiedTrustLinks()
    {
        return $this->hasMany(UserTrustLink::class)
            ->where('status', 'verified')
            ->with('service');
    }

    public function getPaymentMethodsDisplayAttribute()
    {
        if (!$this->payment_methods) {
            return [];
        }

        $display = [];
        foreach ($this->payment_methods as $method => $details) {
            if ($details['enabled'] ?? false) {
                $display[] = $method;
            }
        }
        return $display;
    }

    public function getPaymentMethodAddress($method)
    {
        return $this->payment_methods[$method]['address'] ?? null;
    }

    public function isOnVacation()
    {
        if (!$this->is_on_vacation) {
            return false;
        }

        $now = now();
        
        // If start date is set and hasn't been reached yet
        if ($this->vacation_start_date && $now->lt($this->vacation_start_date)) {
            return false;
        }
        
        // If end date is set and has passed
        if ($this->vacation_end_date && $now->gt($this->vacation_end_date)) {
            return false;
        }
        
        return true;
    }

    public function getVacationStatusAttribute()
    {
        if (!$this->is_on_vacation) {
            return null;
        }
        
        $now = now();
        
        if ($this->vacation_start_date && $now->lt($this->vacation_start_date)) {
            return 'scheduled';
        }
        
        if ($this->vacation_end_date && $now->gt($this->vacation_end_date)) {
            return 'expired';
        }
        
        return 'active';
    }
}
