<?php
// Run manually or via Task Scheduler / cron

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/ensure_traffic_tables.php';
require_once __DIR__ . '/../lib/mikrotik_client.php';
require_once __DIR__ . '/../lib/mikrotik_queue.php';

mysqli_set_charset($conn, 'utf8');
ensure_traffic_tables($conn);

$api = mt_connect($conn);
if (!$api) {
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'message' => 'RouterOS API: اتصال فاشل',
        'ts' => date('c')
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// Fetch queues once
$queues = mt_fetch_simple_queues($api);

$subs = $conn->query("SELECT id, username, full_name, ip_address FROM subscribers ORDER BY id ASC");
$insert = $conn->prepare("INSERT INTO traffic_snapshots (subscriber_id, username, ip_address, rx_bytes, tx_bytes, source, note) VALUES (?,?,?,?,?,'simple_queue',?)");

$ok = 0;
$miss = 0;
$nowDay = date('Y-m-d');

while ($s = $subs->fetch_assoc()) {
    $sid = (int)$s['id'];
    $ip = trim((string)($s['ip_address'] ?? ''));
    if ($ip === '') continue;

    $q = mt_find_queue_by_target($queues, $ip);
    if (!$q) {
        $miss++;
        continue;
    }

    $bytes = mt_parse_queue_bytes($q['bytes'] ?? null);
    $rx = (int)$bytes['rx'];
    $tx = (int)$bytes['tx'];

    $uname = (string)($s['username'] ?? '');
    $note = (string)($q['name'] ?? '');

    $insert->bind_param('issiiis', $sid, $uname, $ip, $rx, $tx, $note);
    $insert->execute();
    $ok++;

    // Daily aggregation: keep max snapshot for the day (simple approximation)
    $conn->query(
        "INSERT INTO traffic_daily (day, subscriber_id, username, ip_address, rx_bytes, tx_bytes)
         VALUES ('$nowDay', $sid, '" . $conn->real_escape_string($uname) . "', '" . $conn->real_escape_string($ip) . "', $rx, $tx)
         ON DUPLICATE KEY UPDATE rx_bytes=GREATEST(rx_bytes,$rx), tx_bytes=GREATEST(tx_bytes,$tx)"
    );
}

mt_disconnect($api);

echo json_encode([
    'ok' => true,
    'saved' => $ok,
    'missing_queue' => $miss,
    'ts' => date('c')
], JSON_UNESCAPED_UNICODE);
