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

$current_time = date('Y-m-d H:i:s');
echo "<!DOCTYPE html>
<html>
<head>
    <title>🕵️ Live Product Monitor - Catch the Culprit</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css' rel='stylesheet'>
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .monitor-card { background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.2); }
        .alert-danger { background: rgba(220,53,69,0.9); border-color: #dc3545; }
        .alert-success { background: rgba(25,135,84,0.9); border-color: #198754; }
        .alert-warning { background: rgba(255,193,7,0.9); border-color: #ffc107; color: #000; }
        .table { background: rgba(255,255,255,0.95); color: #000; }
    </style>
</head>
<body>
<div class='container mt-4'>";

echo "<div class='text-center mb-4'>
    <h1><i class='fas fa-search'></i> 🕵️ LIVE PRODUCT DISAPPEARANCE MONITOR</h1>
    <p class='lead'>Catching product deletions in real-time • Last check: $current_time</p>
</div>";

// Check if any products have disappeared
$monitor_file = 'product_monitor.txt';
$disappeared_products = [];
$current_products = [];

if (file_exists($monitor_file)) {
    $monitored = file($monitor_file, FILE_IGNORE_NEW_LINES);
    foreach ($monitored as $line) {
        if (trim($line)) {
            list($id, $name, $barcode) = explode('|', $line);
            
            // Check if product still exists
            $check = $conn->prepare("SELECT id, name, barcode FROM products WHERE id = ?");
            $check->bind_param('i', $id);
            $check->execute();
            $result = $check->get_result();
            
            if ($result->num_rows == 0) {
                $disappeared_products[] = ['id' => $id, 'name' => $name, 'barcode' => $barcode];
                
                // Log the disappearance
                $disappear_log = date('Y-m-d H:i:s') . " - 🚨 PRODUCT DISAPPEARED! ID: $id, Name: $name, Barcode: $barcode\n";
                file_put_contents('product_disappearances.log', $disappear_log, FILE_APPEND);
            } else {
                $current_products[] = $result->fetch_assoc();
            }
        }
    }
}

// Show disappeared products alert
if (!empty($disappeared_products)) {
    echo "<div class='alert alert-danger'>";
    echo "<h4><i class='fas fa-exclamation-triangle'></i> 🚨 PRODUCTS HAVE DISAPPEARED!</h4>";
    echo "<p><strong>Found " . count($disappeared_products) . " missing products:</strong></p>";
    echo "<ul>";
    foreach ($disappeared_products as $product) {
        echo "<li>ID {$product['id']}: <strong>{$product['name']}</strong> (Barcode: {$product['barcode']})</li>";
    }
    echo "</ul>";
    echo "<p><strong>Check the logs below for WHO deleted them!</strong></p>";
    echo "</div>";
} else {
    echo "<div class='alert alert-success'>";
    echo "<h4><i class='fas fa-check-circle'></i> ✅ All Products Safe</h4>";
    echo "<p>All " . count($current_products) . " monitored products are still in the database.</p>";
    echo "</div>";
}

// Show deletion attempts log
echo "<div class='monitor-card card mb-4'>";
echo "<div class='card-header bg-danger text-white'>";
echo "<h5><i class='fas fa-exclamation-triangle'></i> 🚨 DELETION ATTEMPTS LOG</h5>";
echo "</div>";
echo "<div class='card-body'>";

if (file_exists('deletion_forensics.log')) {
    $log_content = file_get_contents('deletion_forensics.log');
    if (trim($log_content)) {
        echo "<div class='alert alert-warning'>";
        echo "<h6>⚠️ DELETION ATTEMPTS DETECTED!</h6>";
        echo "<pre style='background: #000; color: #fff; padding: 15px; border-radius: 5px; max-height: 400px; overflow-y: auto;'>";
        echo htmlspecialchars($log_content);
        echo "</pre>";
        echo "</div>";
    } else {
        echo "<p class='text-success'><i class='fas fa-shield-alt'></i> No deletion attempts detected yet.</p>";
    }
} else {
    echo "<p class='text-success'><i class='fas fa-shield-alt'></i> No deletion attempts detected yet.</p>";
}

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

// Show recent product additions
echo "<div class='monitor-card card mb-4'>";
echo "<div class='card-header bg-primary text-white'>";
echo "<h5><i class='fas fa-plus'></i> Recent Product Additions</h5>";
echo "</div>";
echo "<div class='card-body'>";

$recent = $conn->query("SELECT id, name, barcode, created_at FROM products WHERE DATE(created_at) >= CURDATE() - INTERVAL 2 DAY ORDER BY created_at DESC LIMIT 10");

if ($recent->num_rows > 0) {
    echo "<div class='table-responsive'>";
    echo "<table class='table table-striped table-sm'>";
    echo "<thead><tr><th>ID</th><th>Name</th><th>Barcode</th><th>Added</th><th>Action</th></tr></thead>";
    echo "<tbody>";
    
    while ($row = $recent->fetch_assoc()) {
        $is_today = date('Y-m-d', strtotime($row['created_at'])) == date('Y-m-d');
        $row_class = $is_today ? 'table-success' : '';
        
        echo "<tr class='$row_class'>";
        echo "<td><strong>{$row['id']}</strong></td>";
        echo "<td>{$row['name']}</td>";
        echo "<td><code>{$row['barcode']}</code></td>";
        echo "<td>" . date('M d, H:i', strtotime($row['created_at'])) . "</td>";
        echo "<td><button onclick='addToMonitor({$row['id']}, \"{$row['name']}\", \"{$row['barcode']}\")' class='btn btn-sm btn-warning'>Monitor This</button></td>";
        echo "</tr>";
    }
    echo "</tbody></table></div>";
} else {
    echo "<p class='text-muted'>No recent products found.</p>";
}

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

// Show current monitoring status
echo "<div class='monitor-card card mb-4'>";
echo "<div class='card-header bg-info text-white'>";
echo "<h5><i class='fas fa-eye'></i> Currently Monitoring (" . count($current_products) . " products)</h5>";
echo "</div>";
echo "<div class='card-body'>";

if (!empty($current_products)) {
    echo "<div class='row'>";
    foreach (array_slice($current_products, 0, 20) as $product) {
        echo "<div class='col-md-6 col-lg-4 mb-2'>";
        echo "<div class='card'>";
        echo "<div class='card-body p-2'>";
        echo "<small><strong>ID {$product['id']}</strong>: {$product['name']}</small><br>";
        echo "<small class='text-muted'>Barcode: {$product['barcode']}</small>";
        echo "</div></div></div>";
    }
    echo "</div>";
    
    if (count($current_products) > 20) {
        echo "<p class='text-muted mt-3'>... and " . (count($current_products) - 20) . " more products being monitored.</p>";
    }
} else {
    echo "<p class='text-warning'>No products are being monitored yet. Add some products and click 'Monitor This'.</p>";
}

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

// Instructions
echo "<div class='monitor-card card'>";
echo "<div class='card-header bg-success text-white'>";
echo "<h5><i class='fas fa-lightbulb'></i> How This Works</h5>";
echo "</div>";
echo "<div class='card-body'>";
echo "<ol>";
echo "<li><strong>Add products normally</strong> through your products interface</li>";
echo "<li><strong>Click 'Monitor This'</strong> next to new products above</li>";
echo "<li><strong>Check this page daily</strong> - it will show if any products disappeared</li>";
echo "<li><strong>If products disappear</strong>, the deletion log will show WHO did it</li>";
echo "<li><strong>Bookmark this page</strong>: <code>" . $_SERVER['HTTP_HOST'] . "/live_monitor.php</code></li>";
echo "</ol>";
echo "</div></div>";

echo "</div>"; // container

// JavaScript for adding products to monitor
echo "<script>
function addToMonitor(id, name, barcode) {
    fetch('add_to_monitor.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'id=' + id + '&name=' + encodeURIComponent(name) + '&barcode=' + encodeURIComponent(barcode)
    })
    .then(response => response.text())
    .then(data => {
        alert('Product ID ' + id + ' added to monitoring!');
        location.reload();
    });
}

// Auto-refresh every 60 seconds
setTimeout(function() {
    location.reload();
}, 60000);

console.log('🕵️ Product Disappearance Monitor Active - Auto-refresh in 60 seconds');
</script>";

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