<?php
// Fiction Ignition — Diagnostic endpoint
// Visit: https://yourdomain.com/api/ping.php
// DELETE this file once everything is working.

header('Content-Type: application/json; charset=utf-8');
$out = ['time' => date('Y-m-d H:i:s T'), 'checks' => [], 'fixes' => []];

// ── 1. PHP version ─────────────────────────────────────────
$out['checks']['php'] = PHP_VERSION;
$out['checks']['php_ok'] = version_compare(PHP_VERSION, '8.1', '>=');

// ── 2. Find & load .env ────────────────────────────────────
$envPaths = [
    dirname(__DIR__) . '/api/.env',
    dirname(__DIR__) . '/.env',
    __DIR__  . '/.env',
    dirname(__DIR__, 2) . '/api/.env',
];
$envFile = null;
foreach ($envPaths as $p) { if (file_exists($p)) { $envFile = $p; break; } }
$out['checks']['env_file'] = $envFile ?? 'NOT FOUND — copy api/.env.example to api/.env';
$out['checks']['env_ok']   = $envFile !== null;

if ($envFile) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if (!$line || $line[0] === '#' || !str_contains($line, '=')) continue;
        [$k, $v] = explode('=', $line, 2);
        $k = trim($k); $v = trim($v);
        if (!array_key_exists($k, $_ENV)) { $_ENV[$k] = $v; putenv("$k=$v"); }
    }
}

// ── 3. Required .env keys ──────────────────────────────────
$required = ['APP_URL','DB_HOST','DB_PORT','DB_NAME','DB_USER','DB_PASS',
             'SESSION_COOKIE_SECURE','ANTHROPIC_API_KEY','MAIL_HOST','MAIL_USERNAME'];
$out['checks']['env_keys'] = [];
foreach ($required as $k) {
    $v = $_ENV[$k] ?? getenv($k) ?: null;
    $out['checks']['env_keys'][$k] = $v
        ? (in_array($k, ['DB_PASS','ANTHROPIC_API_KEY','MAIL_PASSWORD'])
            ? substr($v,0,4).'****'
            : $v)
        : '⚠ NOT SET';
}

// ── 4. HTTPS / cookie warning ──────────────────────────────
$isHttps  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? 80) == 443);
$secureCfg = $_ENV['SESSION_COOKIE_SECURE'] ?? getenv('SESSION_COOKIE_SECURE') ?: 'true';
$out['checks']['https']  = $isHttps ? 'yes' : 'no (HTTP)';
$out['checks']['cookie_secure_setting'] = $secureCfg;
if ($secureCfg === 'true' && !$isHttps) {
    $out['checks']['cookie_warning'] = '⚠ SESSION_COOKIE_SECURE=true but you are on HTTP. Login will silently fail. Set SESSION_COOKIE_SECURE=false in .env for HTTP testing.';
    $out['fixes'][] = 'In api/.env set: SESSION_COOKIE_SECURE=false';
}

// ── 5. PHP extensions ──────────────────────────────────────
$exts = ['pdo','pdo_mysql','openssl','curl','mbstring','json'];
$out['checks']['extensions'] = [];
foreach ($exts as $e) {
    $out['checks']['extensions'][$e] = extension_loaded($e) ? 'ok' : '⚠ MISSING';
    if (!extension_loaded($e)) $out['fixes'][] = "Enable PHP extension: $e";
}

// ── 6. Database + schema ───────────────────────────────────
try {
    $h = $_ENV['DB_HOST'] ?? 'localhost';
    $p = $_ENV['DB_PORT'] ?? '3306';
    $n = $_ENV['DB_NAME'] ?? '';
    $u = $_ENV['DB_USER'] ?? '';
    $pw= $_ENV['DB_PASS'] ?? '';
    if (!$n || !$u) throw new Exception('DB_NAME or DB_USER missing from .env');

    $pdo = new PDO("mysql:host=$h;port=$p;dbname=$n;charset=utf8mb4", $u, $pw, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 3,
    ]);
    $out['checks']['db_connection'] = "OK — connected to `$n` on $h:$p";

    // Check each expected table
    $expectedTables = ['users','sessions','email_tokens','reset_tokens',
                       'subscriptions','prompt_usage','webhook_events'];
    $existingTables = array_column($pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_NUM), 0);
    $out['checks']['tables'] = [];
    foreach ($expectedTables as $t) {
        $exists = in_array($t, $existingTables);
        $out['checks']['tables'][$t] = $exists ? 'ok' : '⚠ MISSING';
        if (!$exists) $out['fixes'][] = "Run api/schema.sql — table `$t` is missing";
    }

    // Check isAdmin column
    if (in_array('users', $existingTables)) {
        $cols = array_column($pdo->query("SHOW COLUMNS FROM users")->fetchAll(), 'Field');
        $out['checks']['isAdmin_column'] = in_array('isAdmin', $cols) ? 'ok' : '⚠ MISSING';
        if (!in_array('isAdmin', $cols)) {
            $out['fixes'][] = "Run SQL: ALTER TABLE users ADD COLUMN isAdmin TINYINT(1) NOT NULL DEFAULT 0 AFTER email_verified;";
        }

        // List users
        $users = $pdo->query("SELECT id, name, email, tier, email_verified, isAdmin FROM users ORDER BY created_at DESC LIMIT 10")->fetchAll();
        $out['checks']['users'] = array_map(fn($r) => [
            'email'    => $r['email'],
            'tier'     => $r['tier'],
            'verified' => (bool)$r['email_verified'],
            'isAdmin'  => (bool)$r['isAdmin'],
        ], $users);
    }

} catch (Exception $e) {
    $out['checks']['db_connection'] = '⚠ FAILED: ' . $e->getMessage();
    $out['fixes'][] = 'Fix DB credentials in api/.env — ' . $e->getMessage();
}

// ── 7. Composer vendor ─────────────────────────────────────
$vendor = dirname(__DIR__) . '/vendor/autoload.php';
$out['checks']['composer'] = file_exists($vendor) ? 'ok' : '⚠ NOT FOUND — run: cd api && composer install';
if (!file_exists($vendor)) $out['fixes'][] = 'Run: cd api && composer install  (needed for email sending)';

// ── 8. .htaccess ──────────────────────────────────────────
$htaccess = dirname(__DIR__) . '/.htaccess';
$out['checks']['htaccess'] = file_exists($htaccess) ? 'ok' : '⚠ MISSING';

// ── Summary ────────────────────────────────────────────────
$out['status']  = empty($out['fixes']) ? '✅ All checks passed' : '⚠ Issues found — see fixes[]';
$out['reminder'] = 'DELETE api/ping.php before going live — it exposes server info';

echo json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
