<?php

namespace EstatebudConnect\Core;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Controllers\Listing;
use EstatebudConnect\Utilities\Helper;

class RewriteRules
{
    use Singleton;

    protected $rules = [
        [
            'regex' => '(?:[^\/]{2}\/)?{{ property }}\/(.*-+)?([0-9]+)\/?$',
            'query' =>
                'index.php?estatebud_listing_type=property&estatebud_listing_slug=$matches[1]&estatebud_listing_id=$matches[2]',
            'after' => 'top',
            'variables' => ['estatebud_listing_type', 'estatebud_listing_slug', 'estatebud_listing_id'],
        ],
        [
            'regex' => '(?:[^\/]{2}\/)?{{ project }}\/(.*-+)?([0-9]+)\/?$',
            'query' =>
                'index.php?estatebud_listing_type=project&estatebud_listing_slug=$matches[1]&estatebud_listing_id=$matches[2]',
            'after' => 'top',
            'variables' => ['estatebud_listing_type', 'estatebud_listing_slug', 'estatebud_listing_id'],
        ],
    ];

    public function __construct()
    {
        add_action('init', [$this, 'register_rules'], -999999);
        add_filter('query_vars', [$this, 'register_variables'], -999999, 1);
        add_filter('template_include', [$this, 'handle_listing_request'], 10);
    }

    public function register_rules()
    {
        $placeholders = [
            '{{ property }}',
            '{{ project }}',
        ];

        $values = [
            Helper::slugify(Helper::term('property')),
            Helper::slugify(Helper::term('project')),
        ];

        foreach ($this->rules as $rule) {
            $regex = str_replace($placeholders, $values, $rule['regex']);
            add_rewrite_rule($regex, $rule['query'], $rule['after']);
        }
    }

    public function register_variables($vars)
    {
        foreach ($this->rules as $rule) {
            if (isset($rule['variables']) && is_array($rule['variables'])) {
                foreach ($rule['variables'] as $variable) {
                    $vars[] = $variable;
                }
            }
        }

        return $vars;
    }

    public function handle_listing_request($template)
    {
        $id = get_query_var('estatebud_listing_id');
        
        if (!empty($id)) {
            return Listing::instance()->render_listing();
        }

        return $template;
    }
}
