<?php

namespace App\Models;

use App\Models\BaseModel;
use App\Scopes\CompanyScope;

class WebsiteLegalPage extends BaseModel
{
    protected $table = 'website_legal_pages';

    protected $default = ['xid', 'title', 'meta_title', 'page_url'];

    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $hidden = ['id', 'company_id', 'website_id', 'website_language_id'];

    protected $appends = ['xid', 'x_company_id', 'x_website_id', 'x_website_language_id', 'page_url'];

    protected $filterable = ['title', 'slug', 'status'];

    protected $images = [];

    protected $files = [];

    protected $foreignKeys = ['company_id', 'website_id', 'website_language_id'];

    protected $hashableGetterFunctions = [
        'getXCompanyIdAttribute' => 'company_id',
        'getXWebsiteIdAttribute' => 'website_id',
        'getXWebsiteLanguageIdAttribute' => 'website_language_id',
    ];

    protected $casts = [
        'show_in_footer' => 'boolean',
        'display_order' => 'integer'
    ];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new CompanyScope);
    }

    public function website()
    {
        return $this->belongsTo(Website::class, 'website_id');
    }

    public function websiteLanguage()
    {
        return $this->belongsTo(WebsiteLanguage::class, 'website_language_id');
    }

    /**
     * Get the page URL for this website legal page.
     * Uses the global helper landing_page_url() which handles:
     * - Primary website in non-saas mode: returns root page URL (/page/{pageSlug})
     * - Otherwise: returns website-specific page URL with prefix
     * Includes lang query parameter to ensure correct language is used when opening the page.
     */
    public function getPageUrlAttribute(): ?string
    {
        if (!$this->slug || !$this->website_id) {
            return null;
        }

        // Get website
        $website = Website::withoutGlobalScopes()->find($this->website_id);
        if (!$website || !$website->slug) {
            return null;
        }

        // Get language key for this website legal page
        $langKey = null;
        if ($this->website_language_id) {
            $lang = Lang::find($this->website_language_id);
            $langKey = $lang?->key;
        }

        // Use global helper for consistent URL generation
        $url = landing_page_url($this->slug, $website);

        // Append lang query parameter if language exists
        if ($langKey) {
            $url .= '?lang=' . $langKey;
        }

        return $url;
    }
}
