<?php
// sse-stats.php
// فتح اتصال SSE وبث التحديثات فقط عند تغيّر البيانات

require_once __DIR__ . '/db.php';
$conn->set_charset('utf8mb4');

ignore_user_abort(true);
set_time_limit(0);

// تعطيل أي بافرينج
while (ob_get_level() > 0) { ob_end_flush(); }
ob_implicit_flush(true);

// هيدرز SSE
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Connection: keep-alive');

// دالة لجلب القيم الحالية
function get_stats(mysqli $conn): array {
    $stats = [
        'capital' => 0.0,
        'balance' => 0.0,
        'revenues' => 0.0,
        'expenses' => 0.0,
        'profits' => 0.0,
        'profitPercentage' => 0.0,
        'custody' => 0.0,
        'projects' => [],
        'projectsCount' => 0
    ];

    // رأس المال
    $q = "SELECT COALESCE(SUM(value),0) AS s FROM `financialMH`";
    if ($r = $conn->query($q)) { $stats['capital'] = (float)$r->fetch_assoc()['s']; $r->free(); }

    // الرصيد الحالي
    $q = "SELECT COALESCE(SUM(value),0) AS s FROM `TransactionsMH`";
    if ($r = $conn->query($q)) { $stats['balance'] = (float)$r->fetch_assoc()['s']; $r->free(); }

    // الإيرادات
    $q = "SELECT COALESCE(SUM(value),0) AS s FROM `revenuesMH`";
    if ($r = $conn->query($q)) { $stats['revenues'] = (float)$r->fetch_assoc()['s']; $r->free(); }

    // المصروفات
    $q = "SELECT COALESCE(SUM(total_price),0) AS s FROM `expensesMH`";
    if ($r = $conn->query($q)) { $stats['expenses'] = (float)$r->fetch_assoc()['s']; $r->free(); }

    // الأرباح ونسبتها
    $stats['profits'] = $stats['revenues'] - $stats['expenses'];
    $stats['profitPercentage'] = ($stats['revenues'] > 0)
        ? round(($stats['profits'] / $stats['revenues']) * 100, 2)
        : 0.0;

    // العهدة
    $q = "SELECT COALESCE(SUM(CAmount),0) AS s FROM `custodyMH`";
    if ($r = $conn->query($q)) { $stats['custody'] = (float)$r->fetch_assoc()['s']; $r->free(); }

    // المشاريع وحالاتها
    $q = "SELECT project_name, project_status 
          FROM `PrjectsMH` 
          WHERE project_status IS NOT NULL 
          ORDER BY project_name ASC";
    if ($r = $conn->query($q)) {
        while ($row = $r->fetch_assoc()) {
            $stats['projects'][] = [
                'name'   => $row['project_name'],
                'status' => $row['project_status']
            ];
        }
        $stats['projectsCount'] = count($stats['projects']);
        $r->free();
    }

    return $stats;
}

// مقارنة القيم
function stats_changed(array $a, array $b): bool {
    $keys = ['capital','balance','revenues','expenses','profits','profitPercentage','custody','projectsCount'];
    foreach ($keys as $k) {
        if ($a[$k] !== $b[$k]) return true;
    }
    // مقارنة المشاريع بالاسم والحالة
    if (count($a['projects']) !== count($b['projects'])) return true;
    foreach ($a['projects'] as $i => $proj) {
        if ($proj['name'] !== $b['projects'][$i]['name'] || $proj['status'] !== $b['projects'][$i]['status']) {
            return true;
        }
    }
    return false;
}

// إرسال أول لقطة
$last = get_stats($conn);
echo "event: stats\n";
echo "data: " . json_encode($last, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
flush();

// التحقق كل ثانيتين
$maxSeconds = 3600;
$start = time();

while (!connection_aborted() && (time() - $start) < $maxSeconds) {
    usleep(2000000);

    $current = get_stats($conn);

    if (stats_changed($current, $last)) {
        $last = $current;
        echo "event: stats\n";
        echo "data: " . json_encode($current, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
        flush();
    } else {
        echo ": keep-alive\n\n";
        flush();
    }
}

echo "event: end\n";
echo "data: \"closed\"\n\n";
flush();
