<?php

namespace ZenoChatbot\Model;

use ZenoChatbot\Framework\Database\Model;

if (!defined('ABSPATH')) {
    exit;
}

// Ensure relation class is loadable when using optimized/composed autoloader or older classmap
if (!class_exists('ZenoChatbot\Model\ConversationSentiment', false)) {
    require_once __DIR__ . '/ConversationSentiment.php';
}

/**
 * Conversation Model
 *
 * Represents chat conversations between customers and the AI/support
 */
class Conversation extends Model
{
    /**
     * Table name
     */
    protected $table = 'zenochatbot_conversations';

    /**
     * Primary key
     */
    protected $primaryKey = 'id';

    /**
     * Fillable attributes
     */
    protected $fillable = [
        'customer_id',
        'department',
        'started_at',
        'ended_at',
        'total_tokens'
    ];

    /**
     * Disable timestamps since table doesn't have created_at/updated_at
     */
    public $timestamps = false;

    /**
     * Attributes that should be cast
     */
    protected $casts = [
        'id' => 'int',
        'customer_id' => 'int',
        'total_tokens' => 'int',
        'started_at' => 'datetime',
        'ended_at' => 'datetime'
    ];

    /**
     * Get the customer associated with this conversation
     */
    public function customer()
    {
       return $this->belongsTo(Customer::class);
    }

    /**
     * Get messages for this conversation
     */
    public function messages()
    {
        return $this->hasMany(Message::class, 'conversation_id');
    }

    /**
     * Get page source (one meta row per conversation, meta_key = page_source).
     * Eager load with ->with('source') to avoid N+1.
     *
     * @return \ZenoChatbot\Framework\Database\Relations\HasOne
     */
    public function source()
    {
        return $this->hasOne(PageSource::class, 'entity_id', 'id')
            ->where('entity_type', self::class)
            ->where('meta_key', PageSource::META_KEY);
    }

    /**
     * Get conversation notes (one meta row per conversation, meta_key = conversation_notes).
     * Value is serialized array of note objects; use ->getItems() on the related model.
     * Eager load with ->with('conversationNotes') to avoid N+1.
     *
     * @return \ZenoChatbot\Framework\Database\Relations\HasOne
     */
    public function conversationNotes()
    {
        return $this->hasOne(ConversationNotes::class, 'entity_id', 'id')
            ->where('entity_type', self::class)
            ->where('meta_key', ConversationNotes::META_KEY);
    }

    /**
     * Get sentiment (one meta row per conversation, meta_key = conversation_sentiment).
     * Eager load with ->with('sentiment') to avoid N+1.
     *
     * @return \ZenoChatbot\Framework\Database\Relations\HasOne
     */
    public function sentiment()
    {
        return $this->hasOne(ConversationSentiment::class, 'entity_id', 'id')
            ->where('entity_type', self::class)
            ->where('meta_key', ConversationSentiment::META_KEY);
    }

    /**
     * Scope to filter by search term
     *
     * @param \ZenoChatbot\Framework\Database\ORM\QueryBuilder $query
     * @param string $search
     * @return \ZenoChatbot\Framework\Database\ORM\QueryBuilder
     */
    public function scopeSearch($query, $search)
    {
        if (!empty($search)) {
            return $query->whereHas('customer', function($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                  ->orWhere('email', 'like', '%' . $search . '%');
            });
        }

        return $query;
    }

    /**
     * Scope to filter by status
     *
     * @param \ZenoChatbot\Framework\Database\ORM\QueryBuilder $query
     * @param string $status
     * @return \ZenoChatbot\Framework\Database\ORM\QueryBuilder
     */
    public function scopeStatus($query, $status)
    {
        if (!empty($status)) {
            if ($status === 'active') {
                return $query->whereNull('ended_at');
            } elseif ($status === 'ended') {
                return $query->whereNotNull('ended_at');
            }
        }

        return $query;
    }

    /**
     * Scope to filter by multiple filters
     *
     * @param \ZenoChatbot\Framework\Database\ORM\QueryBuilder $query
     * @param array $filters
     * @return \ZenoChatbot\Framework\Database\ORM\QueryBuilder
     */
    public function scopeFilterBy($query, array $filters = [])
    {
        return $query->search($filters['search'] ?? '')
                    ->status($filters['status'] ?? '');
    }
}
