<main>
    <?php
    $html = "";
    $n = 12;
    try {
        $stmt = $cms["pdo"]->prepare( "SELECT * FROM pages WHERE t = \"post\" AND created < ? AND published ORDER BY created DESC" );
        $stmt->execute( array( date( "Y-m-d H:i:s" ) ) );


        while ( $n-- > 0 && $page = $stmt->fetch( PDO::FETCH_ASSOC ) ) {

            if ( preg_match( '/<img[^>]+data-preview[^>]*>/us', $page['text'], $m ) ) {
                $preview_img = $m[0];
            } else {
                $preview_img = '';
            }

            if ( preg_match( '/^(.*)(<!--[\s]*preview-start[\s]*-->)(.*)(<!--[\s]*preview-end[\s]*-->)(.*)$/us', $page['text'], $m ) ) {
                $preview = $m[3];
            } else {
                $preview = preg_replace( "/<h1>(.*?)<\/h1>/su", "", $page['text'] );
                $preview = preg_replace( "/<style>(.*?)<\/style>/su", "", $preview );
                $preview = trim( $preview );
                $preview = mb_substr( strip_tags( $preview ), 0, 500 );
                $preview = preg_replace( '/\s\S*$/u', ' ...', $preview );
                $preview = "<p>{$preview}</p>";
            }

            $html .= "
            <article data-date='{$page['created']}'>
                {$preview_img}
                <h2><a href='{$page['url']}' target=_blank>{$page['title']}</a></h2>
                {$preview}
            </article>
            ";

        }

        echo $html;
        // Показать кнопку "Загрузить еще" если есть посты
        if ( $page = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
            $t = $cms["config"]["template.mod.php"]["template"];
            echo "<button class=load-more>" . __( "load_more", $t ) . "</button>";
        }

    } catch ( PDOException $e ) {
        error_log( "blog.php: error: " . $e->getMessage() );
    }
?>
<script>
    document.addEventListener( "DOMContentLoaded", function( event ) {
        let main = document.querySelector( "body > main" );
        function load_more() {
            let more = document.querySelector( `button[class="load-more"]` );
            if ( more ) more.addEventListener( "click", function( el ) {
                let last_el = this.previousElementSibling;
                let last = last_el.getAttribute( "data-date" );
                api( { last: last }, function( html ) {
                    more.remove();
                    main.insertAdjacentHTML( "beforeend", html );
                    load_more();
                } );
            } );
        }
        load_more();

        function api( data, rfn ) {
            const formData = new FormData();
            buildFormData( formData, data );
            let ajax = new XMLHttpRequest();
            ajax.addEventListener( "load", function( event ) {
                rfn( event.target.responseText );
            } );
            ajax.addEventListener( "error", function( event ) {
                console.log( event );
            } );
            ajax.open( "POST", "<?php echo $cms["base_path"]; ?>get_posts" );
            ajax.send( formData );
        }
        function buildFormData( formData, data, parentKey ) {
            if ( data && typeof data === 'object' && ! ( data instanceof Date ) && ! ( data instanceof File ) ) {
                Object.keys( data ).forEach( key => {
                    buildFormData( formData, data[key], parentKey ? `${parentKey}[${key}]` : key );
                } );
            } else {
                const value = data == null ? '' : data;
                formData.append( parentKey, value );
            }
        }
    } );
</script>
</main>
