<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Service extends Model
{
protected $fillable = [
    'service_category_id',
    'title',
    'hero_video',
    'slug',
    'description',
    'work_section_header',
    'h1',
    'h2',
    'position',
    'status',

    // SEO
    'meta_title',
    'meta_description',
    'meta_keywords',
    'canonical_url',
    'og_title',
    'og_description',
    'og_image',

    'noindex',
    'nofollow',

    // Schema (Single + Multiple)
    'schema_type',
    'schema_markup',

    'service_schema',
    'faq_schema',
    'org_schema',
    'webpage_schema',
    'article_schema',
    'breadcrumb_schema',
    'localbusiness_schema',
];



    // ================= CASTS =================
    protected $casts = [
        'status' => 'boolean',
        'position' => 'integer',
    ];

    // ================= RELATIONS =================
    public function category()
    {
        return $this->belongsTo(ServiceCategory::class, 'service_category_id');
    }

    public function works()
    {
        return $this->belongsToMany(Work::class, 'service_work')
            ->withPivot('position')
            ->orderBy('service_work.position');
    }

    public function menu()
    {
        return $this->belongsTo(Menu::class);
    }

    // ================= ROUTE MODEL BINDING =================
    public function getRouteKeyName()
    {
        return 'slug';
    }

    // ================= SCOPES =================
    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    // ================= BOOT =================
    protected static function booted()
    {
        static::saving(function ($service) {

            // Auto generate slug if title changes
            if ($service->isDirty('title')) {
                $service->slug = Str::slug($service->title);
            }

            // Auto set SEO title if empty
            if (empty($service->meta_title)) {
                $service->meta_title = $service->title;
            }

            // Auto set OG title if empty
            if (empty($service->og_title)) {
                $service->og_title = $service->title;
            }
        });
    }

    // ================= ACCESSORS =================
    public function getHeroVideoAttribute($value)
    {
        if (! $value) {
            return null;
        }

        // External URL
        if (Str::startsWith($value, ['http://', 'https://'])) {
            return $value;
        }

        // Stored path
        return asset($value);
    }

    public function getOgImageAttribute($value)
    {
        if (! $value) {
            return null;
        }

        if (Str::startsWith($value, ['http://', 'https://'])) {
            return $value;
        }

        return asset($value);
    }
}