<?php
// This script is intended to be run by a cron job or a scheduled task.
// It checks server traffic usage and expiration dates and sends Telegram notifications.

// Increase execution time, as SSH connections can be slow.
set_time_limit(600); // 10 minutes

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../autoloader.php';

use phpseclib3\Net\SSH2;

echo "Cron job started at " . date('Y-m-d H:i:s') . "\n";

// Fetch servers that have a traffic limit or an expiration date set, and for which notification has not been sent yet.
$stmt = $pdo->prepare("SELECT * FROM servers WHERE (traffic_limit_gb IS NOT NULL OR expiration_date IS NOT NULL) AND notification_sent = 0");
$stmt->execute();
$servers = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($servers)) {
    echo "No servers to check or all notifications have been sent.\n";
    exit;
}

foreach ($servers as $server) {
    $server_name = $server['name'];
    $notification_message = '';
    $send_notification = false;

    // --- Check 1: Expiration Date ---
    if (!empty($server['expiration_date'])) {
        $expiration_timestamp = strtotime($server['expiration_date']);
        if (time() > $expiration_timestamp) {
            $notification_message = "<b>⚠️ هشدار انقضای سرور ⚠️</b>\n\n";
            $notification_message .= "سرور <b>{$server_name}</b> ({$server['ip_address']}) در تاریخ " . to_jalali($server['expiration_date']) . " منقضی شده است.";
            $send_notification = true;
        }
    }

    // --- Check 2: Traffic Limit (only if not already expired) ---
    if (!$send_notification && !empty($server['traffic_limit_gb'])) {
        $limit_bytes = $server['traffic_limit_gb'] * 1024 * 1024 * 1024;
        $total_usage_bytes = 0;

        try {
            $ssh = new SSH2($server['ip_address'], $server['ssh_port']);
            $password = decrypt_data($server['ssh_password']);
            if (!$ssh->login($server['ssh_user'], $password)) {
                echo "Login failed for server: {$server_name}\n";
                continue; // Skip to next server
            }

            // Command to get total RX + TX bytes from all interfaces
            $command = "cat /proc/net/dev | tail -n +3 | awk '{print $2, $10}' | awk '{rx+=$1; tx+=$2} END {print rx+tx}'";
            $output = $ssh->exec($command);
            $total_usage_bytes = (float)trim($output);

            if ($total_usage_bytes >= $limit_bytes) {
                $used_gb = round($total_usage_bytes / (1024*1024*1024), 2);
                $notification_message = "<b>🚨 هشدار حد مصرف ترافیک 🚨</b>\n\n";
                $notification_message .= "سرور <b>{$server_name}</b> ({$server['ip_address']}) از حد مصرف ترافیک خود عبور کرده است.\n\n";
                $notification_message .= "- حد مجاز: <b>{$server['traffic_limit_gb']} GB</b>\n";
                $notification_message .= "- مصرف فعلی: <b>{$used_gb} GB</b>";
                $send_notification = true;
            }

        } catch (Exception $e) {
            echo "Could not connect or execute command on server: {$server_name}. Error: " . $e->getMessage() . "\n";
            continue; // Skip to next server
        }
    }

    // --- Send Notification and Update DB ---
    if ($send_notification) {
        echo "Sending notification for server: {$server_name}...\n";
        send_telegram_message($notification_message);

        // Mark as notified to prevent spam
        $update_stmt = $pdo->prepare("UPDATE servers SET notification_sent = 1 WHERE id = ?");
        $update_stmt->execute([$server['id']]);
        
        echo "Notification sent and DB updated for server: {$server_name}.\n";
    } else {
        echo "No alert condition met for server: {$server_name}.\n";
    }
}

echo "Cron job finished at " . date('Y-m-d H:i:s') . "\n";
?>