<?php
// TEMPORARY DIAGNOSTIC - DELETE AFTER USE.
// URL: https://your-domain/live_binding_check.php?key=mavela_debug_2026

if (($_GET['key'] ?? '') !== 'mavela_debug_2026') {
    http_response_code(404);
    exit('Not found');
}

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
header('Content-Type: text/plain');

require __DIR__ . '/Config.php';

echo "=== LIVE BINDING CHECK ===\n\n";
echo "Server time: " . date('Y-m-d H:i:s') . "\n";
echo "Host: " . ($_SERVER['HTTP_HOST'] ?? 'n/a') . "\n";
echo "Script path: " . __FILE__ . "\n";
echo "Admin.php mtime: " . date('Y-m-d H:i:s', @filemtime(__DIR__ . '/admin.php')) . "\n\n";

try {
    $dbName = (string)$pdo->query("SELECT DATABASE() AS dbname")->fetchColumn();
    $dbUser = (string)$pdo->query("SELECT CURRENT_USER() AS dbuser")->fetchColumn();

    $learnersCount = (int)$pdo->query("SELECT COUNT(*) FROM learners")->fetchColumn();
    $activeLearnersCount = (int)$pdo->query("SELECT COUNT(*) FROM learners WHERE COALESCE(is_frozen,0)=0")->fetchColumn();
    $attendanceCount = (int)$pdo->query("SELECT COUNT(*) FROM daily_attendance_register")->fetchColumn();

    echo "Connected DB: " . $dbName . "\n";
    echo "DB user context: " . $dbUser . "\n";
    echo "Learners total: " . $learnersCount . "\n";
    echo "Learners active (not frozen): " . $activeLearnersCount . "\n";
    echo "Attendance rows: " . $attendanceCount . "\n\n";

    $byClass = $pdo->query("SELECT c.name, COUNT(l.id) AS cnt
      FROM classes c
      LEFT JOIN learners l ON l.class_id = c.id AND COALESCE(l.is_frozen,0)=0
      GROUP BY c.id, c.name
      ORDER BY c.id")->fetchAll(PDO::FETCH_ASSOC);

    echo "Active learners by class:\n";
    foreach ($byClass as $row) {
      echo "- " . $row['name'] . ": " . (int)$row['cnt'] . "\n";
    }
} catch (Throwable $e) {
    echo "ERROR: " . get_class($e) . ": " . $e->getMessage() . "\n";
}

echo "\n=== END ===\n";
echo "Delete this file after debugging.\n";
