<?php
// ulf_thumbgen.php
// pre-generates JPG thumbnails for all PDF files in data_plot/<stationcode>/
// stores thumbnails in data_plot/thumbcache/<stationcode>/
// processes one station at a time to avoid browser timeouts on large datasets
// skips thumbnails that are up to date, regenerates if PDF is newer than thumbnail
// note: JPG and PNG files are served directly and do not need thumbnails generated

set_time_limit(0);

$datapath_plot = "/var/www/html/ULF/data_plot/";
$thumbcache    = "/var/www/html/ULF/data_plot/thumbcache/";

// stations to process - must match station list in ulf_dbstatus
$stations = array("NAL", "LYR", "ISR", "HOR", "NAQ", "UNH", "SNK", "IQA", "MCM", "SPA", "VNA", "KSS", "JBS", "HAL", "RTH", "ZK1", "ZK2", "ZK3", "SDY", "PG2", "PG3", "PG4", "PG5");

// get requested station from URL parameter
$active_station = isset($_GET['station']) ? strtoupper($_GET['station']) : null;

// validate requested station is in our list
if ($active_station !== null && !in_array($active_station, $stations)) {
        $active_station = null;
}

// helper function to format bytes nicely
function format_bytes($bytes) {
    if ($bytes >= 1073741824) return round($bytes / 1073741824, 2) . " GB";
    if ($bytes >= 1048576)    return round($bytes / 1048576, 2)    . " MB";
    if ($bytes >= 1024)       return round($bytes / 1024, 2)       . " KB";
    return $bytes . " B";
}

// get cache size and thumbnail count for a station
function get_station_cache_info($cache_dir) {
    $total_bytes = 0;
    $count       = 0;
    if (is_dir($cache_dir)) {
        $files = scandir($cache_dir);
        foreach ($files as $f) {
            $fp = $cache_dir . $f;
            if (is_file($fp)) {
                $total_bytes += filesize($fp);
                $count++;
            }
        }
    }
    return array('bytes' => $total_bytes, 'count' => $count);
}

// count PDFs in a station directory
function count_pdfs($dirpath) {
    if (!is_dir($dirpath)) return 0;
    $count = 0;
    $files = scandir($dirpath);
    foreach ($files as $f) {
        if (strtolower(pathinfo($f, PATHINFO_EXTENSION)) === 'pdf') $count++;
    }
    return $count;
}

?>
<html>
<head>
<title>ULF Thumbnail Pre-Generator</title>
<style>
body { font-family: arial; font-size: 14px; margin: 20px; }
h2 { color: #004E9B; }
h3 { color: #333333; margin-top: 20px; margin-bottom: 4px; }

table.station-list { border-collapse: collapse; margin-top: 10px; width: 700px; }
table.station-list td, table.station-list th {
    padding: 5px 12px;
    text-align: left;
    border: 1px solid #cccccc;
    font-size: 13px;
}
table.station-list th { background-color: #004E9B; color: #ffffff; }
table.station-list tr.active-row td { background-color: #ffffcc; font-weight: bold; }
table.station-list tr:hover td { background-color: #f0f0f0; }

table.results { border-collapse: collapse; margin-top: 10px; width: 600px; }
table.results td, table.results th {
    padding: 4px 12px;
    text-align: left;
    border: 1px solid #cccccc;
    font-size: 13px;
}
table.results th { background-color: #004E9B; color: #ffffff; }
tr.summary-row td { font-weight: bold; background-color: #e8e8e8; }

.ok    { color: #007700; }
.skip  { color: #888888; }
.error { color: #ff0000; }
.warn  { color: #cc6600; }

a.process-btn {
    display: inline-block;
    padding: 3px 10px;
    background-color: #004E9B;
    color: #ffffff;
    text-decoration: none;
    font-size: 12px;
    border-radius: 3px;
}
a.process-btn:hover { background-color: #0066cc; }
a.process-btn.active { background-color: #cc6600; }
</style>
</head>
<body>

<!-- Banner Start -->
<table border="0" cellpadding="0" cellspacing="0" height="80" width="100%" bgcolor="#004E9B" style="width:100%">
    <tr>
        <td><img src="mirl_logo.jpg" width="94" height="100%"></td>
        <td align="left">
            <font style="font-family:arial; font-size:20px; color:#FFFFFF"><b>ULF Magnetometer System<br>
            <font style="font-family:arial; font-size:18px; color:#FFFFAA">Thumbnail Pre-Generator
        </td>
    </tr>
</table>
<!-- Banner End -->

<h2>Thumbnail Generator</h2>
<p>
Click <b>Process</b> next to a station to generate thumbnails for all its PDF files.<br>
Thumbnails are cached in <code><?php echo($thumbcache); ?></code><br>
JPG and PNG files are served directly and are not processed here.<br>
Existing thumbnails are skipped unless the source PDF is newer.
</p>

<?php

// make sure thumbcache root exists
if (!is_dir($thumbcache)) {
    if (!mkdir($thumbcache, 0755, true)) {
        echo("<p class='error'>ERROR: Could not create thumbcache directory at $thumbcache — check apache write permissions.</p>");
        echo("</body></html>");
        exit;
    }
}

// calculate overall cache size
$overall_bytes = 0;
$overall_thumbs = 0;
foreach ($stations as $code) {
    $info = get_station_cache_info($thumbcache . $code . "/");
    $overall_bytes  += $info['bytes'];
    $overall_thumbs += $info['count'];
}

echo("<p>Overall cache: <b>" . format_bytes($overall_bytes) . "</b> across <b>" . $overall_thumbs . "</b> thumbnails</p>");

// station overview table
echo("<table class='station-list'>");
echo("<tr><th>Station</th><th>PDFs</th><th>Cached Thumbs</th><th>Cache Size</th><th>Action</th></tr>");

foreach ($stations as $code) {
    $dirpath   = $datapath_plot . $code . "/";
    $cache_dir = $thumbcache . $code . "/";
    $pdf_count = count_pdfs($dirpath);
    $info      = get_station_cache_info($cache_dir);
    $is_active = ($active_station === $code);

    $row_class = $is_active ? "class='active-row'" : "";
    echo("<tr $row_class>");
    echo("<td>" . $code . "</td>");
    echo("<td>" . $pdf_count . "</td>");
    echo("<td>" . $info['count'] . "</td>");
    echo("<td>" . format_bytes($info['bytes']) . "</td>");

    if ($is_active) {
        echo("<td><a class='process-btn active' href='ulf_thumbgen.php?station=" . $code . "'>Processing...</a></td>");
    } else {
        echo("<td><a class='process-btn' href='ulf_thumbgen.php?station=" . $code . "'>Process</a></td>");
    }
    echo("</tr>");
}

echo("</table>");

// process the selected station if one was requested
if ($active_station !== null) {
    $code      = $active_station;
    $dirpath   = $datapath_plot . $code . "/";
    $cache_dir = $thumbcache . $code . "/";

    echo("<h2>Processing: " . $code . "</h2>");
    flush();

    if (!is_dir($dirpath)) {
        echo("<p class='warn'>No data directory found at $dirpath</p>");
    } else {

        // create station cache dir if needed
        if (!is_dir($cache_dir)) {
            mkdir($cache_dir, 0755, true);
        }

        // scan for PDFs only
        $all_files = scandir($dirpath); 
// debug - remove after testing 
echo("<p>scandir returned: " . ($all_files === false ? "FALSE - permission denied" : count($all_files) . " entries") . "</p>"); $pdf_files = array(); 
echo("<p>PDF files found: " . count($pdf_files) . "</p>"); foreach ($all_files as $f) {
flush();
            if (strtolower(pathinfo($f, PATHINFO_EXTENSION)) === 'pdf') {
                $pdf_files[] = $f;
            }
        }

        // sort descending so newest files are processed first
        rsort($pdf_files);

        $generated = 0;
        $skipped   = 0;
        $errors    = 0;
        $results   = array();

        echo("<p>" . count($pdf_files) . " PDF files found.</p>");
        flush();

        foreach ($pdf_files as $pdf_file) {
            $source_path = $dirpath . $pdf_file;
            $basename    = pathinfo($pdf_file, PATHINFO_FILENAME);
            $thumb_path  = $cache_dir . $basename . ".jpg";

            // skip if thumbnail exists and is up to date
            if (file_exists($thumb_path) && filemtime($thumb_path) >= filemtime($source_path)) {
                $skipped++;
                $results[] = array('file' => $pdf_file, 'status' => 'skipped', 'msg' => 'Up to date');
                continue;
            }

            // generate thumbnail from first page of PDF with white background
            $source_arg = escapeshellarg($source_path . '[0]');
            $dest_arg   = escapeshellarg($thumb_path);
            $cmd        = "convert -density 72 -resize 400x -background white -flatten $source_arg $dest_arg";
            exec($cmd, $output, $returncode);

            if ($returncode !== 0 || !file_exists($thumb_path)) {
                $errors++;
                $results[] = array('file' => $pdf_file, 'status' => 'error', 'msg' => 'ImageMagick failed');
            } else {
                $generated++;
                $results[] = array('file' => $pdf_file, 'status' => 'ok', 'msg' => 'Generated');
            }

            flush();
        }

        // recalculate cache size after processing
        $info = get_station_cache_info($cache_dir);

        // show results table
        echo("<table class='results'>");
        echo("<tr><th>File</th><th>Status</th></tr>");
        foreach ($results as $entry) {
            $css = $entry['status'] === 'ok' ? 'ok' : ($entry['status'] === 'skipped' ? 'skip' : 'error');
            echo("<tr><td>" . htmlspecialchars($entry['file']) . "</td><td class='" . $css . "'>" . $entry['msg'] . "</td></tr>");
        }
        echo("<tr class='summary-row'><td>Station cache size</td><td>" . format_bytes($info['bytes']) . "</td></tr>");
        echo("<tr class='summary-row'><td>Generated / Skipped / Errors</td><td>" . $generated . " / " . $skipped . " / " . $errors . "</td></tr>");
        echo("</table>");

        echo("<p><b>Done.</b> Finished at " . date("Y-m-d H:i:s T") . "</p>");

        // find next station in list for convenience link
        $current_idx = array_search($code, $stations);
        if ($current_idx !== false && $current_idx < count($stations) - 1) {
            $next_station = $stations[$current_idx + 1];
            echo("<p><a class='process-btn' href='ulf_thumbgen.php?station=" . $next_station . "'>Process next station: " . $next_station . " &rarr;</a></p>");
        } else {
            echo("<p class='ok'><b>All stations processed.</b></p>");
        }
    }
}

?>

</body>
</html>
