<?php
session_start();
require_once '../db.php'; // Ensure this points to your DB file

// 1. Force Login Check
if (!isset($_SESSION['user_id'])) {
    die("<h3 style='color:red'>Please log in to your dashboard first, then refresh this page.</h3>");
}

$user_id = $_SESSION['user_id'];
echo "<h1>Debug Report: Virtual Account</h1>";
echo "<strong>Checking User ID:</strong> " . $user_id . "<br><hr>";

// 2. CHECK DATABASE FOR ACCOUNT
$sql = "SELECT * FROM virtual_accounts WHERE user_id = '$user_id'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $data = $result->fetch_assoc();
    
    echo "<h3>🔍 Status: Record Found</h3>";
    echo "Raw Database Data:<br>";
    echo "<pre style='background:#f4f4f4; padding:10px;'>"; 
    print_r($data); 
    echo "</pre>";

    // 3. ANALYZE THE DATA
    if (empty($data['account_number'])) {
        echo "<h2 style='color:red'>❌ PROBLEM DETECTED</h2>";
        echo "<p>The database has a record for you, but the <b>Account Number is EMPTY</b>.</p>";
        echo "<p>This is a 'Ghost Record'. Your dashboard sees it exists, but hides it because it's invalid.</p>";
        
        // AUTO-FIX BUTTON
        echo "<br>
              <form method='POST'>
                <button name='delete_bad_record' value='1' style='background:red; color:white; padding:15px; border:none; cursor:pointer; font-size:16px; border-radius:5px;'>
                    🗑️ Fix Now: Delete Bad Record
                </button>
              </form>";
    } else {
        echo "<h2 style='color:green'>✅ DATA LOOKS GOOD</h2>";
        echo "<p>Your account number is: <b>" . $data['account_number'] . "</b></p>";
        echo "<p>If you still don't see this on your dashboard, check <b>user/dashboard.php</b> line 26 (where it fetches \$vacc).</p>";
    }

} else {
    echo "<h3 style='color:orange'>⚠️ No Record Found</h3>";
    echo "<p>The database is clean. You should see the 'Generate Account' button on your dashboard.</p>";
}

// 4. DELETE LOGIC (Runs when you click the red button)
if (isset($_POST['delete_bad_record'])) {
    $conn->query("DELETE FROM virtual_accounts WHERE user_id = '$user_id'");
    echo "<script>
            alert('Bad record deleted successfully! Redirecting...');
            window.location.href='dashboard.php';
          </script>";
}
?>