<?php
require 'info.php';

function simple_build($action, $settings, $board) {
    Simple::build($action, $settings);
}

// Wrap functions in a class so they don't interfere with normal Tinyboard operations
class Simple {
    public static function build($action, $settings) {
        global $config;

        // Only write the static HTML during normal theme build events
        if (!in_array($action, array('all', 'news', 'boards', 'post', 'post-thread', 'post-delete')))
            return;

        // Export the $settings array into PHP code if needed later (kept for compatibility)
        $settings_export = var_export($settings, true);

        // --- NEW BEHAVIOR ---
        // Instead of creating a PHP wrapper that needs to be executed by the webserver,
        // generate a static HTML file at the configured path (e.g. index.html).
        // This avoids depending on .html being parsed as PHP by the webserver.

        // Build the homepage HTML using the homepage() method (which uses Tinyboard internals)
        $html = self::homepage($settings);

        // Write the generated HTML directly to the configured filename (e.g. index.html)
        file_write($config['dir']['home'] . $settings['html'], $html);
    }

    // Build homepage (returns HTML)
    public static function homepage($settings) {
        global $config;

        $stats = array();
        $boards = listBoards();

        //
        // Calculate total posts
        //
        $sql = 'SELECT SUM(top) FROM (';
        foreach ($boards as &$_board) {
            $sql .= sprintf("SELECT MAX(id) AS top FROM `posts_%s` UNION ALL ", $_board['uri']);
        }
        $sql = preg_replace('/UNION ALL $/', ') AS posts_all', $sql);
        $stmt = query($sql) or error(db_error());
        $stats['total_posts'] = number_format($stmt->fetchColumn());

        //
        // Calculate unique posters
        //
        $sql = 'SELECT COUNT(DISTINCT(ip)) FROM (';
        foreach ($boards as &$_board) {
            $sql .= sprintf("SELECT ip FROM `posts_%s` UNION ALL ", $_board['uri']);
        }
        $sql = preg_replace('/UNION ALL $/', ') AS posts_all', $sql);
        $stmt = query($sql) or error(db_error());
        $stats['unique_posters'] = number_format($stmt->fetchColumn());

        //
        // Calculate active content (sum of file sizes)
        //
        $sql = 'SELECT DISTINCT(files) FROM (';
        foreach ($boards as &$_board) {
            $sql .= sprintf("SELECT files FROM `posts_%s` WHERE files IS NOT NULL UNION ALL ", $_board['uri']);
        }
        $sql = preg_replace('/UNION ALL $/', ') AS posts_all', $sql);
        $stmt = query($sql) or error(db_error());
        $files = $stmt->fetchAll();
        $stats['active_content'] = 0;
        foreach ($files as &$file) {
            if ($file[0]) {
                preg_match_all('/"size":([0-9]*)/', $file[0], $matches);
                $stats['active_content'] += array_sum($matches[1]);
            }
        }

        //
        // Board activity tracking with caching (PPD and total posts)
        //
        $tracked_boards = explode(' ', trim($settings['tracked_boards']));
        $stats['board_data'] = array();
        $any_update = false; // tracks if we rebuilt any board cache during this run

        foreach ($tracked_boards as $board_uri) {
            $board_uri = trim($board_uri);
            if (empty($board_uri)) continue;

            $cache_key = "simple_board_data_{$board_uri}";
            $cache_file = $config['dir']['tmp'] . $cache_key;
            $need_update = true;

            if (file_exists($cache_file)) {
                $cache_data = @unserialize(file_get_contents($cache_file));
                if ($cache_data && (time() - $cache_data['timestamp']) < 900) {
                    // ensure older caches have the formatted field
                    if (!isset($cache_data['ppd_fmt']) && isset($cache_data['ppd'])) {
                        $cache_data['ppd_fmt'] = number_format((int)$cache_data['ppd']);
                    }
                    $need_update = false;
                    $stats['board_data'][$board_uri] = $cache_data;
                }
            }

            if ($need_update) {
                try {
                    // Get board info
                    $board_info_query = prepare("SELECT title FROM `boards` WHERE uri = :uri");
                    $board_info_query->bindValue(':uri', $board_uri);
                    $board_info_query->execute();
                    $board_info = $board_info_query->fetch(PDO::FETCH_ASSOC);

                    // PPD (Posts Per Day) - last 24 hours
                    $ppd_query = prepare(sprintf("SELECT COUNT(*) as count FROM `posts_%s` WHERE time > :time", $board_uri));
                    $ppd_query->bindValue(':time', time() - 86400);
                    $ppd_query->execute();
                    $ppd_result = $ppd_query->fetch(PDO::FETCH_ASSOC);
                    $ppd = $ppd_result ? $ppd_result['count'] : 0;

                    // Total posts
                    $total_query = prepare(sprintf("SELECT MAX(id) as total FROM `posts_%s`", $board_uri));
                    $total_query->execute();
                    $total_result = $total_query->fetch(PDO::FETCH_ASSOC);
                    $total = $total_result ? $total_result['total'] : 0;

                    $board_data = array(
                        'title'     => $board_info ? $board_info['title'] : ucfirst($board_uri),
                        // Preserve your original 1.5 multiplier
                        'ppd'       => (int) floor($ppd * 1.5),
                        'ppd_fmt'   => number_format((int) floor($ppd * 1.5)),
                        'total'     => number_format($total),
                        'timestamp' => time()
                    );

                    $stats['board_data'][$board_uri] = $board_data;

                    // Cache the result
                    @file_put_contents($cache_file, serialize($board_data));
                    $any_update = true;
                } catch (Exception $e) {
                    // Board doesn't exist or other error, set defaults
                    $stats['board_data'][$board_uri] = array(
                        'title'     => ucfirst($board_uri),
                        'ppd'       => 0,
                        'ppd_fmt'   => '0',
                        'total'     => 0,
                        'timestamp' => time()
                    );
                }
            }
        }

        // Sort boards by PPD (highest first)
        uasort($stats['board_data'], function($a, $b) {
            return $b['ppd'] - $a['ppd'];
        });

        // Render the template into HTML (Element() returns string)
        $html = Element('themes/simple/index.html', array(
            'settings'  => $settings,
            'config'    => $config,
            'boardlist' => createBoardlist(),
            'stats'     => $stats
        ));

        // IMPORTANT: When generating a static index.html we DO NOT want to append any PHP wrapper.
        // The file written will be pure HTML produced by the template engine.
        // Return the HTML string to the caller (the build() method writes it to disk).
        return $html;
    }
};
?>
