<?php
/**
 * سودانا — Diagnostics API (ADMIN ONLY)
 * SECURED: Requires active admin session
 * Returns safe system status without exposing secrets
 * FIX: session_start BEFORE any header() output
 */
require_once '../config.php';
require_once __DIR__ . '/../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__.'/../engine/Logger.php';

// ── SECURITY: Session FIRST (before any header output) ───────────
start_secure_session();
if (empty($_SESSION['admin'])) {
    http_response_code(403);
        echo json_encode(['error' => 'forbidden', 'message' => 'Admin access required'], JSON_UNESCAPED_UNICODE);
    exit;
}

header('Cache-Control: no-cache, no-store');

$results = [];
$request_id = uniqid('diag_', true);

// DB Status
try {
    $cnt = (int)db()->query('SELECT COUNT(*) FROM users')->fetchColumn();
    $results['db'] = ['status' => 'ok', 'users' => $cnt];
} catch(Throwable $e) {
    $results['db'] = ['status' => 'error', 'msg' => 'Connection failed — check credentials and that database_complete.sql was imported'];
}

// Tables check
$required_tables = [
    'users','bookings','subscription_plans','flow_sessions',
    'tele_sessions','medical_records','rate_limits','feature_flags',
    'provider_services','kpi_daily','ai_cache','audit_logs',
    'user_subscriptions','payments','neighborhood_services','inquiries'
];
$missing = [];
$present = [];
foreach ($required_tables as $t) {
    try {
        db()->query("SELECT 1 FROM `".preg_replace("/[^a-z_]/","",strtolower($t))."` LIMIT 1");
        $present[] = $t;
    } catch(Throwable $e) {
        $missing[] = $t;
    }
}
$results['tables'] = [
    'status'  => empty($missing) ? 'ok' : 'missing',
    'checked' => count($required_tables),
    'present' => count($present),
    'missing' => $missing,
];

// Engine files check
$engine_files = [
    'Gateway','InferenceEngine','AIClient','OutputBuilder',
    'StepController','ProviderDecisionEngine','CacheLayer','KPILogger'
];
$missing_files = [];
foreach ($engine_files as $f) {
    if (!file_exists(__DIR__ . "/../engine/{$f}.php")) $missing_files[] = $f;
}
$results['engine'] = [
    'status' => empty($missing_files) ? 'ok' : 'missing',
    'files'  => (count($engine_files) - count($missing_files)) . '/' . count($engine_files),
    'missing'=> $missing_files,
];

// IE rules count
try {
    $ie = file_get_contents(__DIR__ . '/../engine/InferenceEngine.php');
    $results['inference_engine'] = [
        'status' => 'ok',
        'rules'  => substr_count($ie, "'id'=>'"),
    ];
} catch(Throwable $e) {
    $results['inference_engine'] = ['status' => 'error'];
}

// Feature flags
try {
    $flags = db()->query("SELECT flag_name, is_enabled FROM feature_flags")->fetchAll();
    $results['feature_flags'] = $flags;
} catch(Throwable $e) {
    $results['feature_flags'] = 'table_missing';
}

// KPI today
try {
    $today = db()->query(
        "SELECT total_requests, ai_calls, ie_hits, cache_hits, bookings_created
         FROM kpi_daily WHERE kpi_date = CURDATE() LIMIT 1"
    )->fetch();
    $results['kpi_today'] = $today ?: ['total_requests'=>0,'ai_calls'=>0,'note'=>'no data yet today'];
} catch(Throwable $e) {
    $results['kpi_today'] = null;
}

// AI models (bool only — no key values)
$results['ai_models'] = [
    'gemini' => defined('GEMINI_KEY') && GEMINI_KEY && GEMINI_KEY !== 'YOUR_GEMINI_KEY_HERE',
    'claude' => defined('CLAUDE_API_KEY') && CLAUDE_API_KEY && CLAUDE_API_KEY !== 'YOUR_NEW_CLAUDE_KEY_HERE',
    'openai' => defined('OPENAI_API_KEY') && OPENAI_API_KEY && OPENAI_API_KEY !== 'YOUR_OPENAI_KEY_HERE',
];

$results['request_id'] = $request_id;
$results['timestamp']  = date('c');
$results['version']    = 'v21';
$results['site_url']   = SITE_URL;
$results['db_name']    = DB_NAME; // name only, not credentials

echo json_encode(['success' => true, 'diag' => $results], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
