<?php
/**
 * barcode_alert_checker.php
 *
 * Controlla l’inattività del Keyence e, se supera il timeout configurato,
 * invia automaticamente il report parziale usando sp_send_partial_production().
 */

require_once __DIR__ . '/../config/db_remote.php';
require_once __DIR__ . '/../config/emailer.php';

// 1) Legge impostazioni alert (production_alerts.json)
$alerts = sp_email_get_alerts();
$timeoutMinutes = isset($alerts['timeout_minutes']) ? (int)$alerts['timeout_minutes'] : 60;
if ($timeoutMinutes < 1) {
    $timeoutMinutes = 60;
}

// 2) Timestamp ultimo barcode
$timestampFile = __DIR__ . '/../last_barcode_timestamp.txt';

// Se il file non esiste, lo crea adesso e NON invia nulla al primo giro
if (!file_exists($timestampFile)) {
    file_put_contents($timestampFile, time());
    error_log('[KEYENCE] timestamp file created, no report this run.');
    exit;
}

$last = (int)@file_get_contents($timestampFile);
$now  = time();
$idleMinutes = ($now - $last) / 60.0;

// 3) Se inattività minore del timeout, esce
if ($idleMinutes < $timeoutMinutes) {
    error_log('[KEYENCE] Idle ' . $idleMinutes . ' min (< ' . $timeoutMinutes . '), no auto-report.');
    exit;
}

// 4) Invia auto-report (range day)
error_log('[KEYENCE] Idle ' . $idleMinutes . ' min >= ' . $timeoutMinutes . ' → sending AUTO-REPORT');

$ok = sp_send_partial_production($mysqli, 'day', null, null);

// 5) Aggiorna timestamp (per evitare invii ripetuti)
file_put_contents($timestampFile, time());

if ($ok) {
    error_log('[KEYENCE] AUTO-REPORT SENT OK');
} else {
    error_log('[KEYENCE] ERROR sending auto-report');
}
