<?php
$delay = 15; // time in seconds
header("Refresh: $delay; URL=" . $_SERVER['PHP_SELF']);

/**
 * Refresh truck dump stats cache.
 * 
 * Run via cron every 60 seconds:
 *   * * * * * php /path/to/refresh_truckdump_cache.php
 * 
 * Or call from truckdump.php with stale-check.
 */

// Ensure PHP uses the same timezone as MySQL/local server
date_default_timezone_set('America/Chicago');

$con = mysqli_connect('192.168.0.10', 'corey', '41945549', 'controls');

if (!$con) {
    error_log('refresh_truckdump_cache: DB connection failed');
    exit(1);
}

/**
 * Format seconds as HH:MM:SS
 */
function formatDuration($seconds)
{
    if ($seconds <= 0) {
        return '00:00:00';
    }
    $hours = floor($seconds / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    $secs = $seconds % 60;
    return sprintf('%02d:%02d:%02d', $hours, $minutes, $secs);
}

/**
 * Get dump timestamps for a given counter column.
 * Finds when the counter value changed (i.e., when a dump occurred).
 * Returns array of up to 10 timestamps (most recent first).
 */
function getDumpTimestamps($con, $counterColumn)
{
    // Find the first occurrence of each counter value (when it incremented)
    // by getting the MIN(DATE) for each distinct counter value
    $query = "
        SELECT MIN(DATE) AS dump_time
        FROM plc
        GROUP BY {$counterColumn}
        ORDER BY {$counterColumn} DESC
        LIMIT 10
    ";
    $result = mysqli_query($con, $query);
    
    if (!$result) {
        return [];
    }
    
    $timestamps = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $ts = strtotime($row['dump_time']);
        if ($ts) {
            $timestamps[] = $ts;
        }
    }
    return $timestamps;
}

/**
 * Calculate stats for a dump location.
 */
function calculateDumpStats($con, $counterColumn)
{
    $timestamps = getDumpTimestamps($con, $counterColumn);
    $now = time();
    
    $sinceLast = '00:00:00';
    $betweenDumps = '00:00:00';
    $avg10 = '00:00:00';
    
    if (count($timestamps) >= 1) {
        // Time since the most recent dump
        $sinceLast = formatDuration($now - $timestamps[0]);
    }
    
    if (count($timestamps) >= 2) {
        // Time between the last two dumps
        $betweenDumps = formatDuration($timestamps[0] - $timestamps[1]);
    }
    
    if (count($timestamps) >= 10) {
        // Average time between 10 dumps = (first - tenth) / 9 intervals
        $avgSeconds = ($timestamps[0] - $timestamps[9]) / 9;
        $avg10 = formatDuration((int) $avgSeconds);
    }
    
    return [
        'since_last'    => $sinceLast,
        'between_dumps' => $betweenDumps,
        'avg_10'        => $avg10,
    ];
}

// Calculate all stats
$east = calculateDumpStats($con, 'totnorth');
$west1 = calculateDumpStats($con, 'totsouth');
$west2 = calculateDumpStats($con, 'totwest2');

// Update cache table
$sql = "
    UPDATE truckdump_stats_cache SET
        east_since_last     = ?,
        east_between_dumps  = ?,
        east_avg_10         = ?,
        west1_since_last    = ?,
        west1_between_dumps = ?,
        west1_avg_10        = ?,
        west2_since_last    = ?,
        west2_between_dumps = ?,
        west2_avg_10        = ?,
        updated_at          = NOW()
    WHERE id = 1
";

$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param(
    $stmt,
    'sssssssss',
    $east['since_last'],
    $east['between_dumps'],
    $east['avg_10'],
    $west1['since_last'],
    $west1['between_dumps'],
    $west1['avg_10'],
    $west2['since_last'],
    $west2['between_dumps'],
    $west2['avg_10']
);

$success = mysqli_stmt_execute($stmt);

mysqli_stmt_close($stmt);
mysqli_close($con);

if ($success) {
    echo "Cache refreshed at " . date('Y-m-d H:i:s') . "\n";
    exit(0);
} else {
    error_log('refresh_truckdump_cache: Update failed');
    exit(1);
}
