<?php
/**
 * Simple cron-style checker for Keyence barcode timeout alerts.
 *
 * Configure options in:
 *   config/production_alerts.json
 *   config/email_recipients.json
 *
 * This script is designed to be run periodically (e.g. every 5 minutes)
 * by Windows Task Scheduler or a cron job.
 */

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

$alertsFile = __DIR__ . '/../config/production_alerts.json';
$alertsCfg  = sp_email_load_json($alertsFile);
$alertsCfg = array_merge([
    'enabled'         => true,
    'timeout_minutes' => 60,
], is_array($alertsCfg) ? $alertsCfg : []);

if (empty($alertsCfg['enabled'])) {
    // alerts disabled
    exit;
}

$timeoutMinutes = (int)$alertsCfg['timeout_minutes'];
if ($timeoutMinutes <= 0) {
    $timeoutMinutes = 60;
}

// last alert tracker
$lastAlertFile = __DIR__ . '/../config/last_barcode_alert.json';
$lastAlertData = sp_email_load_json($lastAlertFile);

// Get last reading time
$q = $mysqli->query("SELECT MAX(read_time) AS last_time FROM barcode_readings");
if (!$q) {
    sp_email_log('barcode_alert_checker: failed to query last_time: ' . $mysqli->error);
    exit;
}
$row = $q->fetch_assoc();
$lastTime = $row['last_time'] ?? null;

if (!$lastTime) {
    // no scans yet
    exit;
}

$now  = new DateTime('now');
$last = new DateTime($lastTime);
$diffMinutes = (int)floor(($now->getTimestamp() - $last->getTimestamp()) / 60);

if ($diffMinutes < $timeoutMinutes) {
    // still within allowed time
    exit;
}

// avoid spamming: only send if we did not alert for this lastTime
$lastNotifiedTime = $lastAlertData['last_notified_time'] ?? null;
if ($lastNotifiedTime === $lastTime) {
    // already notified for this last scan
    exit;
}

// Build email
$subject = 'ALERT: No barcode scans for more than ' . $timeoutMinutes . ' minutes';
$body    = "Keyence barcode alert from SM Produce.\n\n"
         . "Last scan time: {$lastTime}\n"
         . "Current time: " . $now->format('Y-m-d H:i:s') . "\n"
         . "Gap: {$diffMinutes} minutes without activity.\n";

// Send using centralized Gmail SMTP
$error = null;
if (sp_smtp_send($subject, $body, [], null, $error)) {
    $lastAlertData['last_notified_time'] = $lastTime;
    sp_email_save_json($lastAlertFile, $lastAlertData);
    sp_email_log('barcode_alert_checker: alert email sent.');
} else {
    sp_email_log('barcode_alert_checker: FAILED to send alert: ' . ($error ?: 'unknown error'));
}
