<?php

namespace Workdo\MobileServiceManagement\Entities;

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

class MobileServiceCustomPage extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'title',
        'slug',
        'contents',
        'show_in_footer',
        'workspace',
        'created_by',
    ];

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

        static::created(function ($pageoption) {
            $pageoption->slug = $pageoption->createSlug($pageoption->name);
            $pageoption->save();
        });
    }

    private function createSlug($name)
    {
        $slug = Str::slug($name);

        if (static::where('slug', $slug)->exists()) {
            $latestSlug = static::where('name', $name)
                ->latest('id')
                ->skip(1)
                ->value('slug');

            if ($latestSlug && preg_match('/(\d+)$/', $latestSlug, $matches)) {
                return preg_replace_callback('/(\d+)$/', function ($matches) {
                    return $matches[1] + 1;
                }, $latestSlug);
            }

            return "{$slug}-2";
        }

        return $slug;
    }

    public static function getTermsPage($workspaceId)
    {
        return static::where('workspace', $workspaceId)
            ->where('slug', 'LIKE', 'terms-and-condition%')
            ->first();
    }

    public static function getPrivacyPage($workspaceId)
    {
        return static::where('workspace', $workspaceId)
            ->where('slug', 'LIKE', 'privacy-policy%')
            ->first();
    }
}
