<?php

namespace EstatebudConnect\Core;

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

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

class RewriteRules
{
    use Singleton;

    protected $rules = [
        [
            'regex' => '(?:[^\/]{2,}\/)?({{ slugs }})\/([^\/]+)\/?([^\/]+)?\/?$',
            'query' =>
                'index.php?estatebud_listing_type_slug=$matches[1]&estatebud_listing_id=$matches[2]&estatebud_listing_slug=$matches[3]',
            'after' => 'top',
            'variables' => ['estatebud_listing_type_slug', 'estatebud_listing_id', 'estatebud_listing_slug'],
        ],
    ];

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

    public function register_rules()
    {
        $rules = get_option('rewrite_rules', []);
        $flush = false;

        foreach ($this->rules as $rule) {
            $languages = Locale::instance()->get_enabled_languages();
            $url_slugs = [];

            foreach($languages as $language) {
                $url_slugs[] = Helper::slugify(Helper::term('property', 1, $language['code']));
                $url_slugs[] = Helper::slugify(Helper::term('project', 1, $language['code']));
            }

            $regex = str_replace('{{ slugs }}', implode("|", array_unique($url_slugs)), $rule['regex']);
            add_rewrite_rule($regex, $rule['query'], $rule['after']);

            if (!isset($rules[$regex])) {
                $flush = true;
            }
        }

        if ($flush) {
            flush_rewrite_rules();
        }
    }

    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)
    {
        $eligible_type_slugs = [
            'property' => Helper::slugify(Helper::term('property')),
            'project' => Helper::slugify(Helper::term('project')),
        ];

        $listing_type_slug = get_query_var('estatebud_listing_type_slug');
        $listing_type = array_first(array_keys($eligible_type_slugs, $listing_type_slug));
        $listing_slug = trim(get_query_var('estatebud_listing_slug'), '-');
        $listing_id = get_query_var('estatebud_listing_id');

        if (isset($eligible_type_slugs[$listing_type]) && !empty($listing_id)) {
            return Listing::instance()->render_listing($listing_id, $listing_type, $listing_slug);
        }
        
        return $template;
    }
}
