<?php
/**
 * Check and Restore Products Script
 * This script checks if products exist in the database and restores them if missing
 */

require_once '../config/db_config.php';

echo "<h1>Product Check and Restore</h1>";

// Test database connection
$conn = getDbConnection();
if (!$conn) {
    echo "<p style='color: red;'>✗ Database connection failed</p>";
    exit;
}

echo "<p style='color: green;'>✓ Database connection successful</p>";

// Check if products table exists
try {
    $stmt = $conn->query("SHOW TABLES LIKE 'products'");
    if ($stmt->rowCount() > 0) {
        echo "<p style='color: green;'>✓ Products table exists</p>";
    } else {
        echo "<p style='color: red;'>✗ Products table does not exist</p>";
        echo "<p>You need to run the database setup script first.</p>";
        exit;
    }
} catch (PDOException $e) {
    echo "<p style='color: red;'>✗ Error checking products table: " . $e->getMessage() . "</p>";
    exit;
}

// Check current products
echo "<h2>Current Products in Database</h2>";
try {
    $stmt = $conn->query("SELECT * FROM products WHERE is_active = true ORDER BY product_id");
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($products)) {
        echo "<p style='color: orange;'>⚠ No products found in database</p>";
    } else {
        echo "<p style='color: green;'>✓ Found " . count($products) . " products</p>";
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr><th>ID</th><th>Name</th><th>Price</th><th>Stock</th><th>Image</th><th>Status</th></tr>";
        foreach ($products as $product) {
            echo "<tr>";
            echo "<td>" . $product['product_id'] . "</td>";
            echo "<td>" . htmlspecialchars($product['name']) . "</td>";
            echo "<td>Rp " . number_format($product['price'], 0, ',', '.') . "</td>";
            echo "<td>" . $product['stock'] . "</td>";
            echo "<td>" . htmlspecialchars($product['image']) . "</td>";
            echo "<td>" . ($product['is_active'] ? 'Active' : 'Inactive') . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
} catch (PDOException $e) {
    echo "<p style='color: red;'>✗ Error fetching products: " . $e->getMessage() . "</p>";
}

// Check if sample products exist
echo "<h2>Sample Products Check</h2>";
$sample_products = [
    ['name' => 'Baso BE 50', 'description' => 'Baso BE 50 adalah baso ukuran kecil dengan harga murah, dengan daging sapi murni dan nyaman di mulut', 'price' => 15000, 'stock' => 100, 'image' => 'assets/baso-1.jpeg'],
    ['name' => 'Baso BE 100', 'description' => 'Baso BE 100 adalah baso ukuran sedang dengan rasa yang lezat, dengan daging sapi pilihan berkualitas', 'price' => 20000, 'stock' => 75, 'image' => 'assets/baso-2.jpeg'],
    ['name' => 'Baso BE 200', 'description' => 'Baso BE 200 adalah baso ukuran besar dengan tekstur yang sempurna, dibuat dari daging sapi premium', 'price' => 25000, 'stock' => 50, 'image' => 'assets/baso-3.jpeg']
];

$missing_products = [];
foreach ($sample_products as $sample) {
    try {
        $stmt = $conn->prepare("SELECT COUNT(*) FROM products WHERE name = :name");
        $stmt->bindParam(':name', $sample['name']);
        $stmt->execute();
        $count = $stmt->fetchColumn();
        
        if ($count > 0) {
            echo "<p style='color: green;'>✓ " . htmlspecialchars($sample['name']) . " exists</p>";
        } else {
            echo "<p style='color: red;'>✗ " . htmlspecialchars($sample['name']) . " missing</p>";
            $missing_products[] = $sample;
        }
    } catch (PDOException $e) {
        echo "<p style='color: red;'>✗ Error checking " . htmlspecialchars($sample['name']) . ": " . $e->getMessage() . "</p>";
    }
}

// Restore missing products
if (!empty($missing_products)) {
    echo "<h2>Restoring Missing Products</h2>";
    
    foreach ($missing_products as $product) {
        try {
            $stmt = $conn->prepare("INSERT INTO products (name, description, price, stock, image, is_active) VALUES (:name, :description, :price, :stock, :image, :is_active)");
            $stmt->bindParam(':name', $product['name']);
            $stmt->bindParam(':description', $product['description']);
            $stmt->bindParam(':price', $product['price']);
            $stmt->bindParam(':stock', $product['stock']);
            $stmt->bindParam(':image', $product['image']);
            $is_active = true;
            $stmt->bindParam(':is_active', $is_active);
            
            if ($stmt->execute()) {
                echo "<p style='color: green;'>✓ Restored " . htmlspecialchars($product['name']) . "</p>";
            } else {
                echo "<p style='color: red;'>✗ Failed to restore " . htmlspecialchars($product['name']) . "</p>";
            }
        } catch (PDOException $e) {
            echo "<p style='color: red;'>✗ Error restoring " . htmlspecialchars($product['name']) . ": " . $e->getMessage() . "</p>";
        }
    }
} else {
    echo "<p style='color: green;'>✓ All sample products are present</p>";
}

// Check image files
echo "<h2>Image Files Check</h2>";
$image_files = [
    'assets/baso-1.jpeg',
    'assets/baso-2.jpeg', 
    'assets/baso-3.jpeg'
];

foreach ($image_files as $image) {
    if (file_exists($image)) {
        echo "<p style='color: green;'>✓ " . $image . " exists</p>";
    } else {
        echo "<p style='color: red;'>✗ " . $image . " missing</p>";
    }
}

// Final check
echo "<h2>Final Product Count</h2>";
try {
    $stmt = $conn->query("SELECT COUNT(*) FROM products WHERE is_active = true");
    $count = $stmt->fetchColumn();
    echo "<p style='color: green;'>✓ Total active products: $count</p>";
} catch (PDOException $e) {
    echo "<p style='color: red;'>✗ Error counting products: " . $e->getMessage() . "</p>";
}

echo "<h2>Next Steps</h2>";
echo "<p><a href='dashboard.php'>Go to Dashboard</a></p>";
echo "<p><a href='admin/listProduct.php'>View Products in Admin Panel</a></p>";
echo "<p><a href='setup_database.php'>Run Database Setup (if needed)</a></p>";
?> 