<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');

$status = ['ok'=>true, 'checks'=>[]];

try {
  require_once __DIR__ . '/../config/config.php';
  $status['checks']['php'] = ['pdo'=>extension_loaded('pdo'), 'pdo_mysql'=>extension_loaded('pdo_mysql')];

  // DB-Ping
  $dsn = "mysql:host={$db_host};port={$db_port};dbname={$db_name};charset=utf8mb4";
  $pdo = new PDO($dsn, $db_user, $db_pass, [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
  $pdo->query('SELECT 1');
  $status['checks']['db'] = 'ok';

  // Schreibtest PDF-Pfad (ohne Datei anzulegen)
  $dir = rtrim($pdf_storage_dir ?? (__DIR__.'/../storage/reports'), '/');
  $status['checks']['pdf_dir'] = ['path'=>$dir, 'exists'=>is_dir($dir), 'writable'=>is_writable($dir)];
  $probe = @file_put_contents($dir.'/.__probe__.tmp', 'x');
  if ($probe !== false) { @unlink($dir.'/.__probe__.tmp'); }
  $status['checks']['pdf_dir']['probe_write'] = ($probe !== false);

} catch (Throwable $e) {
  $status['ok'] = false;
  $status['error'] = $e->getMessage();
}

echo json_encode($status);
