<?php
// Add this line at the beginning of the file
ini_set('error_log', '/Volumes/www/forza_m/logs/error.log');
date_default_timezone_set("America/La_Paz");

// First create the logs directory if it doesn't exist
if (!file_exists('/Volumes/www/forza_m/logs')) {
    mkdir('/Volumes/www/forza_m/logs', 0755, true);
}

require 'lib/phpmailer/PHPMailer.php';
require 'lib/phpmailer/SMTP.php';
require 'lib/phpmailer/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$host = "192.168.0.13";
$dbname = "forza_mqtt2";
$user = "bot";
$password = "Tykun.2026";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Get the settings for each person
    $stmt = $pdo->query("SELECT * FROM ups_settings");
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Modificar la consulta para incluir el device_id
    // Fix the JOIN query to match the correct column names
    $stmt = $pdo->query("SELECT d.*, s.* 
        FROM ups_devices d 
        JOIN ups_settings s ON d.id = s.ups_device_id 
        WHERE d.person_id = s.person_id");
    $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($devices as $device) {
        // Verificar último registro para este dispositivo
        $stmt = $pdo->prepare("SELECT * FROM ups_data WHERE device_id = ? ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$device['id']]);
        $last_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
        if ($last_data) {
            $last_time = new DateTime($last_data['created_at']);
            $current_time = new DateTime();
            $diff = $current_time->diff($last_time);
            $minutes_diff = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
    
            // Check for data interruption (2 minutes without data)
            // Update the time check condition
            if ($minutes_diff >= 2) {
                $check_notification = $pdo->query("SELECT * FROM error_logs WHERE error_type = 'no_data' AND notification_sent = 1 ORDER BY last_error_time DESC LIMIT 1");
                $last_notification = $check_notification->fetch(PDO::FETCH_ASSOC);
            
                // Changed from 15 to 30 minutes and added proper time difference check
                // En la sección de no_data
                if (!$last_notification || (new DateTime($last_notification['last_error_time']))->diff($current_time)->i >= 30) {
                    // Enviar notificación a cada persona configurada
                    foreach ($settings as $setting) {
                        $message = "
                        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px;'>
                            <h2 style='color: #d9534f; text-align: center; border-bottom: 2px solid #d9534f; padding-bottom: 10px;'>⚠️ ALERTA DE SISTEMA UPS</h2>
                            
                            <div style='background-color: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; padding: 15px; margin: 15px 0;'>
                                <strong>Estado:</strong> Sin comunicación<br>
                                <strong>Tiempo sin datos:</strong> {$minutes_diff} minutos<br>
                                <strong>Último registro:</strong> " . date('d/m/Y H:i:s', strtotime($last_data['created_at'])) . "
                            </div>
                        
                            <div style='background-color: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; padding: 15px; margin: 15px 0;'>
                                <h3 style='color: #495057; margin-top: 0;'>Últimos valores registrados:</h3>
                                <table style='width: 100%; border-collapse: collapse;'>
                                    <tr>
                                        <td style='padding: 8px; border-bottom: 1px solid #ddd;'><strong>Voltaje de entrada:</strong></td>
                                        <td style='padding: 8px; border-bottom: 1px solid #ddd;'>{$last_data['input_voltage']}V</td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 8px; border-bottom: 1px solid #ddd;'><strong>Voltaje de salida:</strong></td>
                                        <td style='padding: 8px; border-bottom: 1px solid #ddd;'>{$last_data['out_voltage']}V</td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 8px; border-bottom: 1px solid #ddd;'><strong>Voltaje de batería:</strong></td>
                                        <td style='padding: 8px; border-bottom: 1px solid #ddd;'>{$last_data['battery_voltage']}V</td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 8px;'><strong>Temperatura de batería:</strong></td>
                                        <td style='padding: 8px;'>{$last_data['battery_temperature']}°C</td>
                                    </tr>
                                </table>
                            </div>
                        </div>";
                        
                        sendNotification($pdo, 'no_data', $message, $current_time, $setting);
                    }
                }
            } else {
                // Check if we were previously in error state
                $last_error = $pdo->query("SELECT * FROM error_logs WHERE error_type = 'no_data' ORDER BY last_error_time DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
                // Fix the sendNotification call in the restored section
                if ($last_error) {
                    $message = "Sistema UPS restaurado: Se han restablecido las comunicaciones.<br><br>
                               Último dato recibido: " . $last_data['created_at'];
                    // Get the current setting from the loop
                    foreach ($settings as $current_setting) {
                        if ($current_setting['person_id'] == $device['person_id']) {
                            sendNotification($pdo, 'restored', $message, $current_time, $current_setting);
                        }
                    }
                    $pdo->exec("DELETE FROM error_logs WHERE error_type = 'no_data'");
                }
    
                // Check for out-of-range values
                $alerts = [];
                if ($last_data['input_voltage'] < 210 || $last_data['input_voltage'] > 230) {
                    $alerts[] = "Voltaje de entrada: " . $last_data['input_voltage'] . "V (normal: 210-230V)";
                }
                if ($last_data['out_voltage'] < 218 || $last_data['out_voltage'] > 240) {
                    $alerts[] = "Voltaje de salida: " . $last_data['out_voltage'] . "V (normal: 220-240V)";
                }
                if ($last_data['battery_voltage'] < 11.5) {
                    $alerts[] = "Voltaje de batería bajo: " . $last_data['battery_voltage'] . "V (mínimo: 11.5V)";
                }
    
                if (!empty($alerts)) {
                    $check_range_alert = $pdo->query("SELECT * FROM error_logs WHERE error_type = 'range' AND notification_sent = 1 ORDER BY last_error_time DESC LIMIT 1");
                    $last_range_alert = $check_range_alert->fetch(PDO::FETCH_ASSOC);
    
                    // Send range alerts every 30 minutes
                    if (!$last_range_alert || (new DateTime($last_range_alert['last_error_time']))->diff($current_time)->i >= 15) {
                        $message = "
                        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px;'>
                            <h2 style='color: #ffc107; text-align: center; border-bottom: 2px solid #ffc107; padding-bottom: 10px;'>⚠️ ALERTA DE SISTEMA UPS</h2>
                            
                            <div style='background-color: #fff3cd; border: 1px solid #ffeeba; border-radius: 4px; padding: 15px; margin: 15px 0;'>
                                <strong>Estado:</strong> Valores fuera de rango<br>
                                <strong>Tiempo:</strong> " . $current_time->format('d/m/Y H:i:s') . "
                            </div>
                        
                            <div style='background-color: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; padding: 15px; margin: 15px 0;'>
                                <h3 style='color: #495057; margin-top: 0;'>Valores críticos detectados:</h3>
                                <ul style='list-style-type: none; padding-left: 0;'>";
                        
                        foreach ($alerts as $alert) {
                            $message .= "<li style='padding: 8px; margin: 5px 0; background-color: #ffe5e5; border-radius: 3px;'>❗ {$alert}</li>";
                        }
                        
                        $message .= "
                                </ul>
                            </div>
                            
                            <div style='font-size: 12px; color: #6c757d; text-align: center; margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd;'>
                                Este es un mensaje automático del sistema de monitoreo UPS. Por favor, no responda a este correo.
                            </div>
                        </div>";
                        
                        // Get the current setting for this device
                        foreach ($settings as $current_setting) {
                            if ($current_setting['person_id'] == $device['person_id']) {
                                sendNotification($pdo, 'range', $message, $current_time, $current_setting);
                            }
                        }
                    }
                }
            }
        }
    }
} catch (PDOException $e) {
    error_log("Error de base de datos: " . $e->getMessage());
} catch (Exception $e) {
    error_log("Error general: " . $e->getMessage());
}

// Update the sendNotification function parameters to match the new calls
// Add debug logging in sendNotification function
function sendNotification($pdo, $type, $message, $current_time, $setting = null) {
    try {
        error_log("Starting email notification process for type: " . $type);
        
        $mail = new PHPMailer(true);
        $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Add debug output
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'ale2co@gmail.com';
        $mail->Password   = 'bxqt nsoy lyjs spah';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';

        $mail->setFrom('ale2co@gmail.com', 'Vanaeph UPS');
        
        // Add error checking for email address
        $recipient_email = $setting ? $setting['notification_email'] : 'soporte@vanaeph.com';
        error_log("Sending to email: " . $recipient_email);
        
        if (!filter_var($recipient_email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception("Invalid email address: " . $recipient_email);
        }
        
        $mail->addAddress($recipient_email);
        $mail->isHTML(true);
        $mail->Subject = 'Alerta de Sistema UPS - ' . ucfirst($type);
        $mail->Body    = $message;
    
        if (!$mail->send()) {
            throw new Exception("Email sending failed: " . $mail->ErrorInfo);
        }
        
        error_log("Email sent successfully for type: " . $type . " to " . $recipient_email);

        // Add error checking for database insert
        $stmt = $pdo->prepare("INSERT INTO error_logs (error_type, last_error_time, notification_sent, person_id) 
                              VALUES (:type, :time, 1, :person_id)");
        if (!$stmt->execute([
            ':type' => $type,
            ':time' => $current_time->format('Y-m-d H:i:s'),
            ':person_id' => $setting ? $setting['person_id'] : null
        ])) {
            throw new Exception("Failed to insert error log");
        }
    } catch (Exception $e) {
        error_log("Error in sendNotification: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
    }
}
// ...
// En la sección de no_data


// ...
// En la sección de range alerts
