<?php

namespace App\Models;

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

class Inquiry extends Model
{
    use HasFactory;

    const STATUS_NEW = 'new';
    const STATUS_VIEWED = 'viewed';
    const STATUS_RESPONDED = 'responded';
    const STATUS_CLOSED = 'closed';

    // Admin management statuses
    const ADMIN_STATUS_PENDING = 'pending';
    const ADMIN_STATUS_ASSIGNED = 'assigned';
    const ADMIN_STATUS_REJECTED = 'rejected';

    protected $fillable = [
        'seller_id',
        'buyer_id',
        'name',
        'email',
        'phone',
        'message',
        'product_id',
        'status',
        'seller_viewed_at',
        'seller_response',
        'responded_at',
        'assigned_by_admin_id',
        'assigned_at',
        'admin_status',
        'admin_notes',
    ];

    protected $casts = [
        'seller_viewed_at' => 'datetime',
        'responded_at' => 'datetime',
        'assigned_at' => 'datetime',
    ];

    public function seller()
    {
        return $this->belongsTo(Seller::class);
    }

    public function buyer()
    {
        return $this->belongsTo(Buyer::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

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

    public function markAsViewed()
    {
        if ($this->status === self::STATUS_NEW) {
            $this->update([
                'status' => self::STATUS_VIEWED,
                'seller_viewed_at' => now(),
            ]);
        }
    }

    public function getStatusBadgeAttribute()
    {
        $badges = [
            self::STATUS_NEW => '<span class="badge bg-primary">New</span>',
            self::STATUS_VIEWED => '<span class="badge bg-info">Viewed</span>',
            self::STATUS_RESPONDED => '<span class="badge bg-success">Responded</span>',
            self::STATUS_CLOSED => '<span class="badge bg-secondary">Closed</span>',
        ];
        return $badges[$this->status] ?? $badges[self::STATUS_NEW];
    }

    public static function getStatuses()
    {
        return [
            self::STATUS_NEW => 'New',
            self::STATUS_VIEWED => 'Viewed',
            self::STATUS_RESPONDED => 'Responded',
            self::STATUS_CLOSED => 'Closed',
        ];
    }

    public function scopeNew($query)
    {
        return $query->where('status', self::STATUS_NEW);
    }

    public function scopeResponded($query)
    {
        return $query->where('status', self::STATUS_RESPONDED);
    }

    public function scopePendingAdmin($query)
    {
        return $query->where('admin_status', self::ADMIN_STATUS_PENDING);
    }

    public function scopeAssignedByAdmin($query)
    {
        return $query->where('admin_status', self::ADMIN_STATUS_ASSIGNED);
    }
}

