<?php
/*************************************
 * DB CONNECTION
 *************************************/
$host = '127.0.0.1';
$db   = 'e7_alarms';
$user = 'c2kc';
$pass = 'P@ssw0rd3211';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("DB connection failed: " . $e->getMessage() . PHP_EOL);
}

/*************************************
 * CREATE TABLE IF NOT EXISTS
 *************************************/
$pdo->exec("CREATE TABLE IF NOT EXISTS anomaly_alerts_sent (
    id INT AUTO_INCREMENT PRIMARY KEY,
    anomaly_epoch BIGINT NOT NULL,
    network VARCHAR(64),
    date_sent TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(anomaly_epoch, network)
)");

/*************************************
 * FETCH ALARMS
 *************************************/
$stmt = $pdo->query('SELECT id, subscriber_id, network, alarm_timestamp FROM test1_standing_alarms_view');
// $stmt = $pdo->query('SELECT id, subscriber_id, network, alarm_timestamp FROM standing_alarms_view');
$rows = $stmt->fetchAll();

$networkTimestamps = [];

/*************************************
 * BUILD NETWORK+TIMESTAMP PAIRS
 *************************************/
foreach ($rows as $row) {
    $networkKey = substr($row['network'], 0, 9);
    // Normalize timestamp to Y-m-d H:i (minute-level)
    $timestamp = date('Y-m-d H:i', strtotime($row['alarm_timestamp']));
    $pairKey = $networkKey . '||' . $timestamp;

    if (!isset($networkTimestamps[$pairKey])) {
        $networkTimestamps[$pairKey] = [];
    }
    $networkTimestamps[$pairKey][] = $row;
}

/*************************************
 * FIND NEW ANOMALIES AND SEND EMAILS
 *************************************/
foreach ($networkTimestamps as $pairKey => $alarms) {
    // Extract unique subscriber_ids
    $uniqueSubs = [];
    foreach ($alarms as $alarm) {
        $uniqueSubs[$alarm['subscriber_id']] = true;
    }
    if (count($uniqueSubs) > 1) {
        list($networkKey, $timestamp) = explode('||', $pairKey);
        $epoch = strtotime($timestamp);

        // Check if this anomaly event was already alerted
        $checkStmt = $pdo->prepare("SELECT 1 FROM anomaly_alerts_sent WHERE anomaly_epoch = ? AND network = ?");
        $checkStmt->execute([$epoch, $networkKey]);
        if (!$checkStmt->fetch()) {
            // Not sent, so send the email
            $to = "kchamberlain@rtccom.com";
            $subject = "New Anomaly Detected | $networkKey $timestamp";

            $body = '
            <html>
            <head>
                <style>
                    body { background-color: #23272e; color: #222; font-family: Arial, sans-serif; }
                    .card {
                        background: #fff6e5;
                        border-radius: 8px;
                        box-shadow: 0 2px 8px #e2c27860;
                        border: 2px solid #ff8800;
                        max-width: 600px;
                        margin: 24px auto;
                        padding: 20px 30px 24px 30px;
                    }
                    h2 { color: #bf2600; }
                    .important { color: #bf2600; font-weight: bold; }
                    .epoch { color: #3573ff; font-size: 16px; }
                    .timestamp { color: #152c0b; font-size: 18px; }
                    .sublist { background: #fffbe6; border-radius: 6px; padding: 10px 16px; margin-top: 10px; }
                    .network { font-size: 18px; color: #353858; }
                    .footer { font-size: 12px; color: #a0a0a0; margin-top: 32px; text-align: center; }
                </style>
            </head>
            <body>
                <div class="card">
                    <h2>New Anomaly Detected</h2>
                    <h4>TYPE</h4>
                    <div class="network"><b>Network:</b> '.$networkKey.'</div>
                    <div class="timestamp"><b>Timestamp:</b> '.$timestamp.'</div>
                    <div class="sublist">
                        <b><span class="important">Subscribers Affected</span>:</b>
                        <ul>';
            foreach ($alarms as $alarm) {
                $body .= '<li><b>' . htmlspecialchars($alarm['subscriber_id']) . '</b></li>';
            }
            $body .= '</ul>
                    </div>
                    <div style="margin-top:24px;">
                        <span class="important">Action may be required!</span>  
                        <br><br>
                    </div>
                   
                </div>
            </body>
            </html>
            ';

            $headers  = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=UTF-8\r\n";
            $headers .= "From: anomaly@rtccom.com\r\n";

            // Send the email
            mail($to, $subject, $body, $headers);

            // Record as sent
            $insertStmt = $pdo->prepare("INSERT INTO anomaly_alerts_sent (anomaly_epoch, network) VALUES (?, ?)");
            $insertStmt->execute([$epoch, $networkKey]);

            echo "Email sent for anomaly at $networkKey $timestamp (epoch: $epoch)\n";
        }
    }
}






// CHECK FOR CLEARED ANOMS ------------------------------------------------------------
$currentAnomalies = [];
foreach ($networkTimestamps as $pairKey => $alarms) {
    $uniqueSubs = [];
    foreach ($alarms as $alarm) {
        $uniqueSubs[$alarm['subscriber_id']] = true;
    }
    if (count($uniqueSubs) > 1) {
        list($networkKey, $timestamp) = explode('||', $pairKey);
        $epoch = strtotime($timestamp);
        $currentAnomalies[$networkKey . '||' . $epoch] = [
            'network' => $networkKey,
            'epoch'   => $epoch,
            'timestamp' => $timestamp
        ];
    }
}

// Get all previous anomaly alerts
$alerted = $pdo->query("SELECT anomaly_epoch, network FROM anomaly_alerts_sent")->fetchAll(PDO::FETCH_ASSOC);
foreach ($alerted as $alert) {
    // Does ANY alarm remain in the DB for this anomaly's network/epoch?
    $stillActive = false;
    foreach ($rows as $row) {
        $networkKey = substr($row['network'], 0, 9);
        $timestamp = date('Y-m-d H:i', strtotime($row['alarm_timestamp']));
        $epoch = strtotime($timestamp);

        if ($networkKey == $alert['network'] && $epoch == $alert['anomaly_epoch']) {
            $stillActive = true;
            break; // Found a matching alarm, so it's not truly cleared yet
        }
    }

    // Only proceed if this anomaly is truly cleared (no alarms left for that network/epoch)
    if (!$stillActive) {
        // Check if already sent cleared
        $checkCleared = $pdo->prepare("SELECT 1 FROM anomaly_cleared_sent WHERE anomaly_epoch = ? AND network = ?");
        $checkCleared->execute([$alert['anomaly_epoch'], $alert['network']]);
        if (!$checkCleared->fetch()) {
            // Compose the cleared email
            $to = "kchamberlain@rtccom.com";
            $subject = "Anomaly Cleared | {$alert['network']} {$alert['anomaly_epoch']}";
            $body = '
            <html>
            <head>
                <style>
                    body { background-color: #f5fff5; color: #222; font-family: Arial, sans-serif; }
                    .card {
                        background: #e6ffec;
                        border-radius: 8px;
                        box-shadow: 0 2px 8px #a4e7b860;
                        border: 2px solid #22bb33;
                        max-width: 600px;
                        margin: 24px auto;
                        padding: 20px 30px 24px 30px;
                    }
                    h2 { color: #22bb33; }
                    .network { font-size: 18px; color: #353858; }
                    .epoch { color: #3573ff; font-size: 16px; }
                    .footer { font-size: 12px; color: #a0a0a0; margin-top: 32px; text-align: center; }
                </style>
            </head>
            <body>
                <div class="card">
                    <h2>✅ Network Anomaly Cleared</h2>
                    <div class="network"><b>Network:</b> '.$alert['network'].'</div>
                    <div class="epoch"><b>Epoch:</b> '.$alert['anomaly_epoch'].'</div>
                    <div style="margin-top:20px;">
                        This anomaly has cleared and is no longer present in your active alarms.<br>
                    </div>
                    <div class="footer">
                        Cleared by your e7-alarms monitoring system.<br>
                        <span style="color:#3573ff;">RTC Network Operations</span>
                    </div>
                </div>
            </body>
            </html>
            ';
            $headers  = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=UTF-8\r\n";
            $headers .= "From: anomaly@rtccom.com\r\n";
            mail($to, $subject, $body, $headers);

            // Mark as cleared
            $ins = $pdo->prepare("INSERT INTO anomaly_cleared_sent (anomaly_epoch, network) VALUES (?, ?)");
            $ins->execute([$alert['anomaly_epoch'], $alert['network']]);

            echo "Cleared email sent for anomaly at {$alert['network']} epoch: {$alert['anomaly_epoch']}\n";
        }
    }
}









?>
