<?php
/**
 * ═══════════════════════════════════════════════════════════════════════════
 * Health Check - بررسی سلامت سیستم
 * ═══════════════════════════════════════════════════════════════════════════
 */
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache');

define('BASE_PATH', dirname(__DIR__));

// Load environment
$envFile = BASE_PATH . '/.env';
$hasEnv = file_exists($envFile);

if ($hasEnv) {
    require_once BASE_PATH . '/src/Env.php';
    require_once BASE_PATH . '/src/DB.php';
    App\Env::load($envFile);
}

// Check debug mode
$debugMode = $hasEnv && App\Env::get('DEBUG_MODE', '0') === '1';

// Build health status
$health = [
    'status' => 'ok',
    'timestamp' => date('c'),
    'checks' => []
];

// 1. PHP Version
$phpVersion = phpversion();
$phpOk = version_compare($phpVersion, '7.4.0', '>=');
$health['checks']['php'] = [
    'ok' => $phpOk,
    'version' => $phpVersion,
    'required' => '7.4+'
];

// 2. Extensions
$requiredExtensions = ['pdo', 'pdo_mysql', 'curl', 'json', 'mbstring'];
$extensionsOk = true;
$missing = [];
foreach ($requiredExtensions as $ext) {
    if (!extension_loaded($ext)) {
        $extensionsOk = false;
        $missing[] = $ext;
    }
}
$health['checks']['extensions'] = [
    'ok' => $extensionsOk,
    'missing' => $missing
];

// 3. Environment file
$health['checks']['env_file'] = [
    'ok' => $hasEnv,
    'path' => $debugMode ? $envFile : '[hidden]'
];

// 4. Database connection
$dbOk = false;
$dbError = null;
if ($hasEnv) {
    try {
        $pdo = App\DB::pdo();
        $pdo->query('SELECT 1');
        $dbOk = true;
    } catch (Throwable $e) {
        $dbError = $debugMode ? $e->getMessage() : 'Connection failed';
    }
}
$health['checks']['database'] = [
    'ok' => $dbOk,
    'error' => $dbError
];

// 5. Required tables
$tablesOk = false;
$missingTables = [];
if ($dbOk) {
    $requiredTables = ['users', 'settings', 'plans', 'orders', 'credentials'];
    try {
        $stmt = $pdo->query("SHOW TABLES");
        $existingTables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        foreach ($requiredTables as $table) {
            if (!in_array($table, $existingTables)) {
                $missingTables[] = $table;
            }
        }
        $tablesOk = empty($missingTables);
    } catch (Throwable $e) {
        $tablesOk = false;
    }
}
$health['checks']['tables'] = [
    'ok' => $tablesOk,
    'missing' => $missingTables
];

// 6. Writable directories
$writableOk = true;
$notWritable = [];
$checkDirs = [
    BASE_PATH . '/storage',
    BASE_PATH . '/storage/logs',
    BASE_PATH . '/public/mini_app/uploads'
];
foreach ($checkDirs as $dir) {
    if (!is_writable($dir)) {
        $writableOk = false;
        $notWritable[] = basename($dir);
    }
}
$health['checks']['writable'] = [
    'ok' => $writableOk,
    'not_writable' => $notWritable
];

// 7. Bot token configured
$hasToken = $hasEnv && !empty(App\Env::get('BOT_TOKEN'));
$health['checks']['bot_token'] = [
    'ok' => $hasToken,
    'configured' => $hasToken
];

// Overall status
$allOk = $phpOk && $extensionsOk && $hasEnv && $dbOk && $tablesOk && $writableOk && $hasToken;
$health['status'] = $allOk ? 'ok' : 'error';

// Response code
http_response_code($allOk ? 200 : 500);

// Pretty print if debug
$jsonFlags = JSON_UNESCAPED_UNICODE;
if ($debugMode) {
    $jsonFlags |= JSON_PRETTY_PRINT;
}

echo json_encode($health, $jsonFlags);
