<?php

$cms["modules"]["sitemap.mod.php"] = array(
    "name"        => "sitemap_module_name",
    "description" => "sitemap_module_description",
    "files" => array(
        ".cms/mod/sitemap.mod.php",
        ".cms/css/sitemap.less",
        ".cms/css/sitemap.css",
        ".cms/js/sitemap.js",
        ".cms/lang/ru_RU.UTF-8/sitemap.mod.php",
        ".cms/lang/en_US.UTF-8/sitemap.mod.php",
        ".cms/lang/uk_UA.UTF-8/sitemap.mod.php",
    ),
);

// Return if module disabled
if ( ! empty( $cms["config"]["sitemap.mod.php"]["disabled"] ) ) {
    return;
}

if ( empty( $cms["config"]["sitemap.mod.php"]["update_interval"] ) ) {
    $cms["config"]["sitemap.mod.php"]["update_interval"] = 60;
}

if ( ! isset( $cms["config"]["sitemap.mod.php"]["exclude"] ) ) {
    $cms["config"]["sitemap.mod.php"]["exclude"] = "";
}

if ( ! isset( $cms["config"]["sitemap.mod.php"]["domain"] ) ) {
    $cms["config"]["sitemap.mod.php"]["domain"] = "";
}

if ( ! isset( $cms["config"]["sitemap.mod.php"]["include"] ) ) {
    $cms["config"]["sitemap.mod.php"]["include"] = "";
}

if ( empty( $cms["config"]["sitemap.mod.php"]["gen"] ) ) {
    $cms["config"]["sitemap.mod.php"]["gen"] = "dynamic";
}

if ( ! isset( $cms["config"]["sitemap.mod.php"]["lastrun"] ) ) {
    $cms["config"]["sitemap.mod.php"]["lastrun"] = "";
}

if ( is_admin() ) {
    hook_add_fn( "admin",         "cms_sitemap_admin" );
    hook_add_fn( "admin_header",  "cms_sitemap_admin_header" );
    hook_add_fn( "api",           "cms_sitemap_api", 20 );
}

if ( $cms["config"]["sitemap.mod.php"]["gen"] === "static" ) {
    hook_add_fn( "cron", "cms_sitemap_cron" );
}
    
$cms["urls"]["^{$cms["base_path"]}sitemap.xml$"] = "sitemap.xml";
hook_add_fn( "sitemap.xml", "cms_sitemap_xml" );


function cms_sitemap_admin_header() {
    global $cms;
    if ( is_admin_header_on( "sitemap.mod.php" ) ) {
        echo "        <link rel=stylesheet href='{$cms["base_path"]}css/sitemap.css'>\n";
        echo "        <script src='{$cms["base_path"]}js/sitemap.js'></script>\n";
    }
}

function cms_sitemap_cron() {
    global $cms;
    if ( $cms["config"]["sitemap.mod.php"]["lastrun"] < date( "Y-m-d H:i:s", time() - $cms["config"]["sitemap.mod.php"]["update_interval"] * 60) ) {
        unlink( "{$cms['site_dir']}/sitemap.xml" );
        $cms["config"]["sitemap.mod.php"]["lastrun"] = date( "Y-m-d H:i:s");
        cms_save_config();
    }
}

function cms_sitemap_xml() {
    global $cms;
    header( "Content-Type: text/xml" );
    $sitemap = cms_sitemap_generate();
    echo $sitemap;
    if ( $cms["config"]["sitemap.mod.php"]["gen"] === "static" ) {
        file_put_contents( "{$cms['site_dir']}/sitemap.xml", $sitemap );
    }
}

function cms_sitemap_update() {
    global $cms;
    // disable remove file
    if ( ! empty( $cms["config"]["sitemap.mod.php"]["disabled"] ) ) {
        return;
    }

    $file = "{$cms['site_dir']}/sitemap.xml";
    if ( file_exists( $file ) ) unlink( $file );
}

function cms_sitemap_generate() {
    global $cms;
    if ( empty( $cms["pdo"] ) ) {
        cms_base_connect();
    }
    if ( empty( $cms["pdo"] ) ) {
        return;
    }

    if ( $cms["config"]["sitemap.mod.php"]["gen"] === "static" && ! empty( $cms["config"]["sitemap.mod.php"]["domain"] ) ) {
        $domain = $cms["config"]["sitemap.mod.php"]["domain"];
    } else {
        $domain = "{$cms['url']['scheme']}://{$cms['url']['host']}{$cms['url']['port']}";
    }

    // Формат массива
    // $cms["sitemap"]["https://site.com/link"] = array(
    //      "lastmod" => "2022-08-27T21:25:17+03:00" || "",
    //      "changefreq" => "weekly",
    //      "priority"   => "0.8"
    // );
    $cms["sitemap"] = array();

    $exclude = explode( "\n", $cms["config"]["sitemap.mod.php"]["exclude"] );
    foreach( $exclude as $n => $link ) {
        if ( empty( $link ) ) {
            unset( $exclude[$n] );
        }
    }

    $date = date( "Y-m-d H:i:s" );
    $q = "SELECT title, url, created, modified, published FROM pages WHERE created<=? ORDER BY created DESC";
    
    try {
        $stmt = $cms["pdo"]->prepare( $q );
        $stmt->execute( array( $date ) );

        while ( $page = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
            if ( $page["published"] && ! in_array( $page["url"], $exclude ) ) {
                if ( $modified = max( strtotime( $page["created"] ), (int) $page["modified"] ) ) {
                    $modified = date( "c", $modified );
                } else {
                    $modified = "";
                }
                $link = $domain . $cms["base_path"] . $page["url"];
                if ( ! isset( $cms["sitemap"][$link] ) ) {
                    $cms["sitemap"][$link] = array( "lastmod" => $modified );
                }
            }
        }
    } catch ( PDOException $e ) {
        error_log( "Sitemap generation failed: " . $e->getMessage() );
        return "";
    }

    // Обязательные для включения ссылки
    foreach( explode( "\n", $cms["config"]["sitemap.mod.php"]["include"] ) as $link ) {
        $link = trim( $link );
        if ( ! empty( $link ) ) {
            $cms["sitemap"][$link] = array( "lastmod" => "" );
        }
    }

    do_hook( "sitemap" );

    // Генерация файла
    $content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
    foreach( $cms["sitemap"] as $url => $attr ) {
        if ( empty( $attr["lastmod"] ) ) {
            $lastmod = "";
        } else {
            $lastmod = "<lastmod>{$attr['lastmod']}</lastmod>";
        }
        if ( empty( $attr["changefreq"] ) ) {
            $changefreq = "";
        } else {
            $changefreq = "<changefreq>{$attr['changefreq']}</changefreq>";
        }
        if ( empty( $attr["priority"] ) ) {
            $priority = "";
        } else {
            $priority = "<priority>{$attr['priority']}</priority>";
        }
        $content .= "<url><loc>{$url}</loc>{$lastmod}{$changefreq}{$priority}</url>\n";
    }
    $content .= "</urlset>";
    return $content;
}


function cms_sitemap_admin() {
    global $cms;
    if ( is_admin_header_on( "sitemap.mod.php" ) ) {

    // Save settings
    if ( ! empty( $_POST["save_settings_sitemap"] ) ) {
        $list = preg_split( "/\r\n|\n\r|\r|\n/u", $_POST["exclude"] );
        $base_url = "{$cms['url']['scheme']}://{$cms['url']['host']}{$cms['url']['port']}{$cms['base_path']}";
        foreach ( $list as $key => $value ) {
            // remove domain
            $list[$key] = trim( str_replace( $base_url, "", $value ) );
            if ( substr( $list[$key], 0, 1 ) === "/" ) $list[$key] = substr( $list[$key], 1 );
        }
        $list = implode( "\n", $list );
        $cms["config"]["sitemap.mod.php"]["gen"]             = $_POST["gen"];
        $cms["config"]["sitemap.mod.php"]["exclude"]         = $list;
        $cms["config"]["sitemap.mod.php"]["include"]         = $_POST["include"];
        $cms["config"]["sitemap.mod.php"]["domain"]          = rtrim( $_POST["domain"], "/" );
        $cms["config"]["sitemap.mod.php"]["update_interval"] =  trim( $_POST["update_interval"] );
        cms_save_config();
        if ( $cms["config"]["sitemap.mod.php"]["gen"] === "dynamic" ) {
            unlink( "{$cms['site_dir']}/sitemap.xml" );
        }
        cms_sitemap_update();
        $cms["status"] = "302";
        $cms["status_302_location"] = $cms["base_path"] . $cms["config"]["admin.mod.php"]["admin_url"];
        return;
    }

    // Create menu item if not exists
    if ( empty( $cms["config"]["sitemap.mod.php"]["menu"]["sitemap"] ) ) {
        $cms["config"]["sitemap.mod.php"]["menu"]["sitemap"] = array(
            "title"    => "sitemap_module_name",
            "sort"     => 60,
            "section"  => "settings",
        );
        cms_save_config();
    }

    $ch["static"] = "";
    $ch["dynamic"] = "";
    $ch[ $cms["config"]["sitemap.mod.php"]["gen"] ] = "checked";

    $sitemap = "{$cms['url']['scheme']}://{$cms['url']['host']}{$cms['url']['port']}{$cms['base_path']}sitemap.xml";

    $page = "
<div class='panel url'>
    <span>" . __( "view_sitemap" ) . "</span>
    <a href='{$sitemap}' target=_blank>{$sitemap}</a>
</div>

<form method=post>

    <div class='panel links rm'>
        <div class=title>" . __( "excluded_links" ) . "</div>
        <textarea name=exclude rows=12 autocomplete=off>{$cms['config']['sitemap.mod.php']['exclude']}</textarea>
        <div class=controls>
            <div class=autoinput>
                <div class=field-search>
                    <input type=search name=search class=search autocomplete=off placeholder='" . __( "placeholder" ) . "'>
                </div>
                <div class=options>
                    
                </div>
            </div>
            <button class=button name=save_settings_sitemap value=save>
                <span>" . __( "save" ) . "</span>
            </button>
        </div>
    </div>

    <div class='panel links add'>
        <div class=title>" . __( "included_links" ) . "</div>
        <textarea name=include rows=12 autocomplete=off>{$cms['config']['sitemap.mod.php']['include']}</textarea>
        <button class=button name=save_settings_sitemap value=save>
            <span>" . __( "save" ) . "</span>
        </button>
    </div>

    <div class='panel mode'>
        <div class=title>" . __( "sitemap_gen" ) . "</div>
        <label>
            <input name=gen type=radio value=dynamic {$ch['dynamic']}>
            <span>" . __( "dynamic" ) . "</span>
        </label>
        <label>
            <input name=gen type=radio value=static {$ch['static']}>
            <span>" . __( "static" ) . "</span>
        </label>
        <div class=title>" . __( "domain" ) . "</div>
        <input type=text name=domain value='{$cms['config']['sitemap.mod.php']['domain']}' placeholder='http://example.com'>
        <button class=button name=save_settings_sitemap value=save>
            <span>" . __( "save" ) . "</span>
        </button>
    </div>

    <div class='panel cron'>
        <div class=title>" . __( "update_freq" ) . "</div>
        <p>
            " . __( "static_freq" ) . " <input type=text name=update_interval value={$cms['config']['sitemap.mod.php']['update_interval']}> " . __( "minutes" ) . "
        </p>
        <p>
            " . __( "url_for_cron" ) . ": {$cms['url']['scheme']}://{$cms['url']['host']}{$cms['url']['port']}{$cms['base_path']}{$cms['config']['admin.mod.php']['cron_url']}
        </p>
        <button class=button name=save_settings_sitemap value=save>
            <span>" . __( "save" ) . "</span>
        </button>
    </div>

</form>

<div class='panel manual'>
    <div class=title>" . __( "help" ) . "</div>
    <p>" . __( "help_p1" ) . "</p>
    <p>" . __( "help_p2" ) . "</p>
</div>
    ";

    $cms["admin_pages"]["sitemap"] = $page;

    }
}

function cms_sitemap_api() {
    global $cms;
    if ( empty( $cms["pdo"] ) ) {
        return;
    }
    
    if ( ! empty( $_POST["fn"] ) ) {
        switch ( $_POST["fn"] ) {
            case "sitemap_pages_list":
                $s = preg_replace( "/\s/u", "", $_POST["search"] );
                $s = preg_split( '//u', $s, -1, PREG_SPLIT_NO_EMPTY );
                $s = implode( "%", $s );
                $search_param = "%{$s}%";

                // Список страниц
                $q = "SELECT id, title, url, pin
                      FROM pages 
                      WHERE ( title LIKE ? OR url LIKE ? )
                            AND url != ''
                      ORDER BY pin DESC, modified DESC
                      LIMIT 100";
                $li_arr = array();
                
                try {
                    $stmt = $cms["pdo"]->prepare( $q );
                    $stmt->execute( array( $search_param, $search_param ) );
                    while ( $page = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
                        $title = htmlspecialchars( $page["title"] );
                        $li_arr[] = "<div class=option data-id={$page['id']} data-url='{$page['url']}'>{$title}</div>";
                    }
                } catch ( PDOException $e ) {
                    error_log( "Sitemap pages list failed: " . $e->getMessage() );
                    // Return empty list on error
                }


                // Хук для других модулей если хотят пополнить список
                // $cms["menu.mod.php"]["s"] = $s;
                // $cms["menu.mod.php"]["pages_list"] = &$html;
                // do_hook( "mod_menu_pages_for_selector" );
                // Передавать через параметры хука

                echo( json_encode( array( "result" => array( "html" => implode( "", $li_arr ), ) ) ) );

            break;
        }
    }
}