<?php

namespace App\Models;

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

use App\Utilities\PageLink;

class PageRedirect extends Model
{
    use HasFactory;

    protected $appends = ['url'];

    protected $casts = [
        //'sort_order' => 'integer',
    ];

    public function savePageRedirect($input, $id = null)
    {
        if ($id) {
            $page_redirect = PageRedirect::findOrFail($id);
        } else {
            $page_redirect = new PageRedirect();
        }

        $page_redirect->url_regex = Arr::get($input, 'url_regex');
        $page_redirect->redirect = Arr::get($input, 'redirect');
        $page_redirect->sort_order = Arr::get($input, 'sort_order');
        $page_redirect->save();

        PageRedirect::sortAll();

        return $page_redirect;
    }

    public static function sortAll()
    {
        $page_redirects = PageRedirect::orderBy('sort_order')->get();

        foreach ($page_redirects as $count => $page_redirect) {
            $page_redirect->sort_order = $count + 1;
            $page_redirect->save();
        }
    }

    public function getUrlAttribute()
    {
        return PageLink::getSlugFromIdAndHash([
            'item_id' => $this->redirect,
            'item_type' => 'page',
        ]);
    }

    public function checkRedirect($path)
    {
        preg_match('/'.Str::replace('/', '\/', $this->url_regex).'/i', $path, $match);
        return count($match) ? $match : null;
    }

    public function processRedirect($path)
    {
        $match = collect($this->checkRedirect($path));

        if (!$match->count()) {
            // we shouldnt get here as the above check method
            // should have already been called
            abort(404);
        }

        $full_match = $match->shift();
        $redirect = $this->redirect;

        // if there is only one match we arent doing any replacement
        // so just use the redirect string
        if ($match->count()) {
            // we need to use the matched groups and replace
            // the corresponding $# areas on the redirect string
            foreach ($match as $count => $replace) {
                $redirect = preg_replace('/\$'.($count + 1).'/i', $replace, $redirect);
            }
        }

        return PageLink::convertLink($redirect);
    }
}
