<?php
// COMPREHENSIVE PRODUCT DISAPPEARANCE INVESTIGATION SYSTEM
// Upload this file to your web server and access it via browser

include 'config.php';
date_default_timezone_set('Asia/Colombo');

echo "<!DOCTYPE html>
<html>
<head>
    <title>🔍 Product Disappearance Detective</title>
    <meta http-equiv='refresh' content='60'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        body { background: #1a1a2e; color: #eee; }
        .detective-card { background: linear-gradient(135deg, #16213e, #0f3460); border: 2px solid #e94560; }
        .alert-critical { background: #e94560; color: white; border: 3px solid #fff; animation: pulse 2s infinite; }
        @keyframes pulse { 0% { opacity: 0.7; } 50% { opacity: 1; } 100% { opacity: 0.7; } }
    </style>
</head>
<body>
<div class='container mt-4'>";

echo "<div class='text-center mb-4'>
    <h1>🔍 PRODUCT DISAPPEARANCE DETECTIVE</h1>
    <p class='lead'>Real-time monitoring • Auto-refresh every 60s</p>
    <p><strong>Mission:</strong> Catch whoever is deleting your products!</p>
</div>";

// STEP 1: Check for deletion attempts
echo "<div class='card detective-card mb-4'>
<div class='card-header'><h4>🚨 DELETION FORENSICS</h4></div>
<div class='card-body'>";

$deletion_log = 'deletion_forensics.log';
if (file_exists($deletion_log) && filesize($deletion_log) > 0) {
    echo "<div class='alert alert-critical'>";
    echo "<h5>⚠️ DELETION ATTEMPTS DETECTED!</h5>";
    echo "<pre style='background:#000; color:#0f0; padding:10px; border-radius:5px; max-height:300px; overflow-y:auto;'>";
    echo htmlspecialchars(file_get_contents($deletion_log));
    echo "</pre>";
    echo "</div>";
} else {
    echo "<div class='alert alert-success'>✅ No deletion attempts detected</div>";
}

echo "</div></div>";

// STEP 2: Live product count comparison
echo "<div class='card detective-card mb-4'>
<div class='card-header'><h4>📊 LIVE PRODUCT COUNT MONITORING</h4></div>
<div class='card-body'>";

$current_count = $conn->query("SELECT COUNT(*) as count FROM products")->fetch_assoc()['count'];
$baseline_file = 'baseline_count.txt';

if (!file_exists($baseline_file)) {
    file_put_contents($baseline_file, $current_count);
    $baseline_count = $current_count;
    echo "<div class='alert alert-info'>📝 Baseline established: $current_count products</div>";
} else {
    $baseline_count = intval(file_get_contents($baseline_file));
}

$difference = $current_count - $baseline_count;

if ($difference < 0) {
    echo "<div class='alert alert-critical'>";
    echo "<h5>🚨 PRODUCTS DISAPPEARED!</h5>";
    echo "<p><strong>Baseline:</strong> $baseline_count products</p>";
    echo "<p><strong>Current:</strong> $current_count products</p>";
    echo "<p><strong>MISSING:</strong> " . abs($difference) . " products have been deleted!</p>";
    
    // Log the disappearance
    $alert_log = date('Y-m-d H:i:s') . " - ALERT: " . abs($difference) . " products disappeared (Baseline: $baseline_count, Current: $current_count)\n";
    file_put_contents('disappearance_alerts.log', $alert_log, FILE_APPEND);
    
    echo "</div>";
} elseif ($difference > 0) {
    echo "<div class='alert alert-success'>";
    echo "<p><strong>✅ Products Added:</strong> $difference new products since baseline</p>";
    echo "<p><strong>Current total:</strong> $current_count products</p>";
    echo "</div>";
} else {
    echo "<div class='alert alert-info'>";
    echo "<p><strong>📊 No changes:</strong> $current_count products (same as baseline)</p>";
    echo "</div>";
}

echo "</div></div>";

// STEP 3: Track today's products
echo "<div class='card detective-card mb-4'>
<div class='card-header'><h4>📅 TODAY'S PRODUCTS TRACKER</h4></div>
<div class='card-body'>";

$todays_products = $conn->query("
    SELECT id, name, barcode, TIME(created_at) as time_created 
    FROM products 
    WHERE DATE(created_at) = CURDATE() 
    ORDER BY created_at DESC
");

if ($todays_products->num_rows > 0) {
    echo "<p><strong>Products added today:</strong> {$todays_products->num_rows}</p>";
    echo "<div class='table-responsive'>";
    echo "<table class='table table-dark table-striped'>";
    echo "<thead><tr><th>ID</th><th>Name</th><th>Barcode</th><th>Time Added</th><th>Status</th></tr></thead><tbody>";
    
    while ($product = $todays_products->fetch_assoc()) {
        // Double-check if product still exists
        $exists_check = $conn->query("SELECT COUNT(*) as exists FROM products WHERE id = {$product['id']}")->fetch_assoc()['exists'];
        $status = $exists_check ? "<span class='badge bg-success'>✅ EXISTS</span>" : "<span class='badge bg-danger'>❌ DELETED</span>";
        
        echo "<tr>";
        echo "<td><strong>{$product['id']}</strong></td>";
        echo "<td>{$product['name']}</td>";
        echo "<td><code>{$product['barcode']}</code></td>";
        echo "<td>{$product['time_created']}</td>";
        echo "<td>$status</td>";
        echo "</tr>";
    }
    echo "</tbody></table></div>";
} else {
    echo "<p>No products added today yet.</p>";
}

echo "</div></div>";

// STEP 4: Instructions and next steps
echo "<div class='card detective-card'>
<div class='card-header'><h4>📋 INVESTIGATION PROTOCOL</h4></div>
<div class='card-body'>";

echo "<h5>🎯 What to do now:</h5>";
echo "<ol>";
echo "<li><strong>Add a test product</strong> through your normal interface</li>";
echo "<li><strong>Note the time</strong> and product details</li>";
echo "<li><strong>Check back tomorrow</strong> - if it's gone, we'll have the forensic data</li>";
echo "<li><strong>Monitor this page</strong> - bookmark: <code>" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "</code></li>";
echo "</ol>";

echo "<h5>🔍 What we're tracking:</h5>";
echo "<ul>";
echo "<li>✅ Every deletion attempt (WHO, WHEN, WHERE)</li>";
echo "<li>✅ Real-time product count changes</li>";
echo "<li>✅ Individual product existence status</li>";
echo "<li>✅ User sessions and IP addresses</li>";
echo "</ul>";

echo "<div class='alert alert-warning mt-3'>";
echo "<strong>🔄 This page auto-refreshes every 60 seconds</strong><br>";
echo "Last refresh: " . date('Y-m-d H:i:s');
echo "</div>";

echo "</div></div>";

echo "</div></body></html>";
?>

<script>
console.log('🔍 Product Detective System Active');
console.log('Monitoring for product disappearances...');
console.log('Next refresh in 60 seconds');
</script>