<?php

$cms["urls"]["^{$cms['base_path']}search_by_tag$"] = "hook_search_by_tag";

hook_add_fn( "hook_search_by_tag", "mini_search_by_tag_fn" );
hook_add_fn( "clear_cache", "template_mini_clear_cache" );

function mini_search_by_tag_fn() {
    global $cms;
    if ( ! empty( $_GET['tag'] ) ) {
        $cms["page"]["title"] = "Поиск по тегу";
        $cms["status"] = "200";
        $cms["hooks"]["write"]["disabled"] = true;
        $cms["hooks"]["hook_search_by_tag"]["next"] = "template";
        $cms["page"]["text"] = "<h1>Статьи с тегом \"{$_GET['tag']}\"</h1>";
        $cms["page"]["tpl"] = "page";
        $cms["page"]["id"] = "search";

        if ( cms_base_connect() ) {
            $etag = mysqli_real_escape_string( $cms["base"], $_GET["tag"] );
            $query = "SELECT * FROM pages WHERE tags LIKE '%{$etag}%' ORDER BY id DESC";

            if ( $cms["search_by_tag_result"] = mysqli_query( $cms["base"], $query ) ) {
                while ( $page = mysqli_fetch_assoc( $cms["search_by_tag_result"] ) ) {
                    $cms["page"]["text"] .= "<a target=_blank href='{$cms['base_path']}{$page['url']}'>{$page['title']}</a>";
                }
            } else {
                $cms["page"]["text"] .= "<p class=error>Ошибка выполнения запроса к базе данных.</p>";
            }
        } else {
            $cms["page"]["text"] .= "<p class=error>Ошибка подключения к базе данных.</p>";
        }
    }
}

// Clear Blog pages
function template_mini_clear_cache() {
    global $cms;

    if ( empty( $cms["base"] ) ) { return ""; } // fix php 8.0
    
    $q = "SELECT * FROM pages WHERE tpl = 'blog'";
    if ( $res1 = mysqli_query( $cms["base"], $q ) ) {
        
        while ( $blog = mysqli_fetch_assoc( $res1 ) ) {

            $q = "SELECT url FROM pages WHERE tpl != 'blog'";
            if ( $res2 = mysqli_query( $cms["base"], $q ) ) {

                $pager = 0;
                $pcount = 0;

                while ( $page = mysqli_fetch_assoc( $res2 ) ) {

                    if ( $pcount < 12 ) {

                        $pcount++;
    
                    } elseif ( $pager == 0 ) {
    
                        $pager++;
                        $pcount = 1;
    
                    } else {
    
                        $file = "{$cms['site_dir']}/{$blog['url']}{$pager}";
                        if ( is_file( $file ) ) {
                            unlink( $file );
                        }
                        $pager++;
                        $pcount = 1;
    
                    }

                }

                if ( $pager == 0 ) {

                } else {
        
                    $file = "{$cms['site_dir']}/{$blog['url']}{$pager}";
                    if ( is_file( $file ) ) {
                        unlink( $file );
                    }
        
                }
            }

        }

    }

}