<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

header('Content-Type: text/plain; charset=utf-8');

echo "Locative cPanel check\n";
echo "=====================\n\n";

echo "PHP version: " . PHP_VERSION . "\n";
echo "PDO extension: " . (extension_loaded('pdo') ? 'OK' : 'MISSING') . "\n";
echo "PDO MySQL extension: " . (extension_loaded('pdo_mysql') ? 'OK' : 'MISSING') . "\n";
echo "JSON extension: " . (extension_loaded('json') ? 'OK' : 'MISSING') . "\n";
echo "MBString extension: " . (extension_loaded('mbstring') ? 'OK' : 'MISSING') . "\n\n";

$configPath = dirname(__DIR__) . '/config/database.php';
echo "Config path: " . $configPath . "\n";
echo "Config exists: " . (is_file($configPath) ? 'YES' : 'NO') . "\n\n";

if (!is_file($configPath)) {
    exit("ERROR: config/database.php not found.\n");
}

$config = require $configPath;

echo "Database host: " . ($config['host'] ?? 'missing') . "\n";
echo "Database name: " . ($config['database'] ?? 'missing') . "\n";
echo "Database user: " . ($config['username'] ?? 'missing') . "\n\n";

try {
    $dsn = sprintf(
        'mysql:host=%s;port=%d;dbname=%s;charset=%s',
        $config['host'],
        $config['port'],
        $config['database'],
        $config['charset']
    );

    $pdo = new PDO($dsn, $config['username'], $config['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    echo "Database connection: OK\n\n";

    $tables = [
        'users',
        'properties',
        'property_photos',
        'clients',
        'reservations',
        'payments',
        'notifications',
        'app_settings',
        'activity_logs',
        'monthly_targets',
    ];

    foreach ($tables as $table) {
        $stmt = $pdo->query("SHOW TABLES LIKE " . $pdo->quote($table));
        echo "Table " . $table . ": " . ($stmt->fetch() ? 'OK' : 'MISSING') . "\n";
    }

    $stmt = $pdo->query("SELECT COUNT(*) AS total FROM users");
    $row = $stmt->fetch();
    echo "\nUsers count: " . ($row['total'] ?? 0) . "\n";
    echo "\nCheck finished.\n";
} catch (Throwable $e) {
    echo "Database/app error: FAILED\n";
    echo get_class($e) . ": " . $e->getMessage() . "\n";
}
