<?php

namespace ZenoChatbot\Model;

use ZenoChatbot\Framework\Database\QueryBuilder;

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

/**
 * Page source meta for a conversation.
 *
 * One row per conversation in zenochatbot_meta (meta_key = 'page_source').
 * Exposes source_url, source_title, source_referrer via accessors.
 */
class PageSource extends Meta
{
    public const META_KEY = 'page_source';

    /**
     * Scope all queries to conversation page_source rows (e.g. for eager load).
     *
     * @return QueryBuilder
     */
    public function newQuery()
    {
        return parent::newQuery()
            ->where('entity_type', Conversation::class)
            ->where('meta_key', self::META_KEY);
    }

    /**
     * Get source_url from meta_value.
     *
     * @return string|null
     */
    public function getSourceUrlAttribute(): ?string
    {
        $data = $this->getDecodedValue();
        $v = $data['source_url'] ?? null;
        return $v !== null && $v !== '' ? (string) $v : null;
    }

    /**
     * Get source_title from meta_value.
     *
     * @return string|null
     */
    public function getSourceTitleAttribute(): ?string
    {
        $data = $this->getDecodedValue();
        $v = $data['source_title'] ?? null;
        return $v !== null && $v !== '' ? (string) $v : null;
    }

    /**
     * Get source_referrer from meta_value.
     *
     * @return string|null
     */
    public function getSourceReferrerAttribute(): ?string
    {
        $data = $this->getDecodedValue();
        $v = $data['source_referrer'] ?? null;
        return $v !== null && $v !== '' ? (string) $v : null;
    }

    /**
     * Decode meta_value to array.
     *
     * @return array<string,mixed>
     */
    protected function getDecodedValue(): array
    {
        if (!isset($this->attributes['meta_value']) && !isset($this->original['meta_value'])) {
            return [];
        }
        $raw = $this->attributes['meta_value'] ?? $this->original['meta_value'] ?? null;
        if ($raw === null) {
            return [];
        }
        $decoded = maybe_unserialize($raw);
        return is_array($decoded) ? $decoded : [];
    }
}
