<?php
/**
 * TrackPro v5 Debug — Find intelligence engine errors
 * DELETE AFTER USE
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: text/html; charset=utf-8');
echo "<pre style='background:#0a0e17;color:#10b981;padding:2rem;min-height:100vh;font-family:monospace'>\n";
echo "TrackPro v5 Intelligence Debug\n" . str_repeat('=', 50) . "\n\n";

// 1. Check DB connection
echo "1. DB Connection... ";
try {
    require_once __DIR__ . '/includes/db.php';
    $pdo = getDB();
    echo "OK\n";
} catch (Exception $e) {
    echo "FAIL: " . $e->getMessage() . "\n";
    exit;
}

// 2. Check visitor_profiles table exists
echo "2. visitor_profiles table... ";
try {
    $pdo->query("SELECT 1 FROM `visitor_profiles` LIMIT 1");
    echo "OK\n";
} catch (Exception $e) {
    echo "MISSING — run migrate_v5.php first!\n";
    echo "   Error: " . $e->getMessage() . "\n";
    exit;
}

// 3. Check identity_graph table
echo "3. identity_graph table... ";
try {
    $pdo->query("SELECT 1 FROM `identity_graph` LIMIT 1");
    echo "OK\n";
} catch (Exception $e) {
    echo "MISSING — run migrate_v5.php first!\n";
    echo "   Error: " . $e->getMessage() . "\n";
}

// 4. Check visitor_identities
echo "4. visitor_identities... ";
$visitors = $pdo->query("SELECT * FROM `visitor_identities` ORDER BY `id` DESC LIMIT 5")->fetchAll();
echo count($visitors) . " visitors found\n";
if (empty($visitors)) {
    echo "   No visitors to profile! Need tracking data first.\n";
    exit;
}

// 5. Check visitor_sessions
echo "5. visitor_sessions... ";
$vid = $visitors[0]['id'];
echo "Testing visitor ID: {$vid}\n";
$sessions = $pdo->prepare("SELECT vs.*, s.id as sid, s.started_at, s.duration_seconds FROM `visitor_sessions` vs JOIN `sessions` s ON vs.session_id = s.id WHERE vs.visitor_id = ?");
$sessions->execute([$vid]);
$sess = $sessions->fetchAll();
echo "   Sessions for this visitor: " . count($sess) . "\n";
if (empty($sess)) {
    echo "   No sessions linked to this visitor!\n";
    exit;
}

// 6. Test each table join individually
$sid = $sess[0]['sid'];
echo "\n6. Testing table data for session {$sid}:\n";
$tables = ['device_data', 'browser_data', 'network_data', 'location_data', 'risk_data', 'fingerprint_data', 'behavioral_data'];
foreach ($tables as $t) {
    try {
        $r = $pdo->prepare("SELECT * FROM `{$t}` WHERE `session_id` = ?");
        $r->execute([$sid]);
        $row = $r->fetch();
        $count = $row ? count($row) : 0;
        echo "   {$t}: " . ($row ? "{$count} columns OK" : "no data") . "\n";
    } catch (Exception $e) {
        echo "   {$t}: ERROR — " . $e->getMessage() . "\n";
    }
}

// 7. Check visitor_profiles columns match what we're trying to insert
echo "\n7. visitor_profiles columns:\n";
$cols = $pdo->query("SHOW COLUMNS FROM `visitor_profiles`")->fetchAll();
foreach ($cols as $c) {
    echo "   {$c['Field']} ({$c['Type']})" . ($c['Key'] ? " [{$c['Key']}]" : "") . "\n";
}

// 8. Try to load and run the profiler
echo "\n8. Loading intelligence_engine.php... ";
try {
    require_once __DIR__ . '/includes/intelligence_engine.php';
    echo "OK\n";
} catch (Exception $e) {
    echo "FAIL: " . $e->getMessage() . "\n";
    exit;
}

echo "9. Running profiler on visitor {$vid}... ";
try {
    $profiler = new VisitorProfiler($pdo);
    $profile = $profiler->profileVisitor($vid);
    echo "OK!\n\n";
    echo "Profile result:\n";
    foreach ($profile as $k => $v) {
        if (is_array($v)) $v = json_encode($v);
        if (strlen($v) > 100) $v = substr($v, 0, 100) . '...';
        echo "   {$k}: {$v}\n";
    }
} catch (Exception $e) {
    echo "FAIL!\n";
    echo "   Error: " . $e->getMessage() . "\n";
    echo "   File: " . $e->getFile() . "\n";
    echo "   Line: " . $e->getLine() . "\n";
    echo "\n   Stack trace:\n" . $e->getTraceAsString() . "\n";
}

echo "\n10. Running correlator... ";
try {
    $correlator = new IdentityCorrelator($pdo);
    $result = $correlator->correlateAll();
    echo "OK!\n";
    echo "   Clusters: {$result['clusters_found']}, Linked: {$result['visitors_linked']}\n";
} catch (Exception $e) {
    echo "FAIL!\n";
    echo "   Error: " . $e->getMessage() . "\n";
    echo "   File: " . $e->getFile() . "\n";
    echo "   Line: " . $e->getLine() . "\n";
}

echo "\n" . str_repeat('=', 50) . "\nDELETE THIS FILE\n</pre>";
