<?php
/**
 * Heritage Voice — health.php
 * Chạy độc lập, không qua router index.php
 * Upload vào: /public_html/api/health.php
 * Test: GET https://yourdomain.com/api/health.php
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

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

try {
    $pdo = db();
    $pdo->query('SELECT 1');

    // Kiểm tra các bảng chính
    $tables = [];
    $stmt = $pdo->query("SHOW TABLES");
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        $tables[] = $row[0];
    }

    $required = ['heritage_sites','voice_tours','audio_points','qr_codes','listen_events','users'];
    $missing  = array_diff($required, $tables);

    echo json_encode([
        'success' => true,
        'message' => 'OK',
        'data'    => [
            'status'        => 'ok',
            'version'       => '1.0.0',
            'timestamp'     => date('c'),
            'db'            => 'connected',
            'db_name'       => DB_NAME,
            'tables_found'  => count($tables),
            'tables_missing'=> array_values($missing),
            'php_version'   => PHP_VERSION,
        ],
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error'   => 'Database connection failed',
        'detail'  => $e->getMessage(), // bỏ dòng này sau khi debug xong
    ], JSON_UNESCAPED_UNICODE);
}
