<?php

use WoWPress\Models\Raid;

add_filter('generate_rewrite_rules', function ($wp_rewrite) {
    $wp_rewrite->rules = array_merge(
        ['roster/?$' => 'index.php?wowpress_page=roster'],
        ['raids/?$' => 'index.php?wowpress_page=raids&year='.date('Y')."&month=".date('m')],
        ['raids/(\d+)/(\d+)?$' => 'index.php?wowpress_page=raids&year=$matches[1]&month=$matches[2]'],
        ['raid/(\d+)/?$' => 'index.php?wowpress_page=raid&raid_id=$matches[1]'],
        ['request/?$' => 'index.php?wowpress_page=form_request'],
        $wp_rewrite->rules
    );
});

add_filter('query_vars', function ($query_vars) {
    $query_vars[] = 'wowpress_page';
    $query_vars[] = 'year';
    $query_vars[] = 'month';
    $query_vars[] = 'raid_id';

    return $query_vars;
});

add_action('template_redirect', function () {
    $page = get_query_var('wowpress_page');
    switch ($page) {
        case 'roster':
            $GLOBALS['wowpress']['widget_area'] = [
                'left' => false,
                'right' => false,
                'top' => false,
                'bottom' => true,
            ];
            $GLOBALS['wowpress']['page_title'] = "Gildenverzeichnis";
            include plugin_dir_path(__FILE__) . '../pages/roster.php';
            die;
            break;
        case 'raids':
            $GLOBALS['wowpress']['widget_area'] = [
                'left' => true,
                'right' => true,
                'top' => false,
                'bottom' => true,
            ];
            $GLOBALS['wowpress']['page_title'] = "Raids";
            $GLOBALS['wowpress']['raids']['year'] = get_query_var('year');
            $GLOBALS['wowpress']['raids']['month'] = get_query_var('month');

            include plugin_dir_path(__FILE__) . '../pages/raids.php';
            die;
            break;
        case 'raid':
            $GLOBALS['wowpress']['widget_area'] = [
                'left' => true,
                'right' => true,
                'top' => false,
                'bottom' => true,
            ];

            $raid = Raid::find(get_query_var('raid_id'));
            $GLOBALS['wowpress']['raid'] = $raid;
            $GLOBALS['wowpress']['page_title'] = $raid->title;

            include plugin_dir_path(__FILE__) . '../pages/single_raid.php';
            die;
            break;
        case 'form_request':
            include plugin_dir_path(__FILE__) . '../request.php';
            die;
        default:
            // DO NOTHING
            break;
    }
});
