<?php
require_once __DIR__ . '/config/db.php';

// First, let's check what categories exist
echo "Current categories in database:\n";
$cats = $pdo->query("SELECT id, name FROM categories ORDER BY id")->fetchAll();
foreach ($cats as $c) {
    echo "  ID {$c['id']}: {$c['name']}\n";
}
echo "\n";

// Let the user see categories and decide
$products_data = [];

// Prompt user to map each image to a category
$image_files = ['shirts.png', 'tshirts.png', 'underskirts.png', 'underwear.png', 'mattress.png'];

echo "Mapping images to products...\n";
echo "Enter category ID for each product (comma-separated, same order as above):\n";
echo "Images: " . implode(', ', $image_files) . "\n";
echo "Or press Enter to use category ID 1 for all:\n";

$input = trim(fgets(STDIN));
$category_ids = [];
if (!empty($input)) {
    $category_ids = array_map('intval', explode(',', $input));
}

$product_names = [
    'shirts.png'     => 'Women\'s Shirt',
    'tshirts.png'    => 'Women\'s T-Shirt',
    'underskirts.png'=> 'Women\'s Underskirt',
    'underwear.png'  => 'Women\'s Underwear',
    'mattress.png'   => 'Mattress',
];

$prices = [
    'shirts.png'     => 3500.00,
    'tshirts.png'    => 2500.00,
    'underskirts.png'=> 4500.00,
    'underwear.png'  => 1800.00,
    'mattress.png'   => 15000.00,
];

foreach ($image_files as $i => $img) {
    $cat_id = $category_ids[$i] ?? 1;
    $products_data[] = [
        'name'        => $product_names[$img],
        'description' => 'High-quality product from our collection.',
        'price'       => $prices[$img],
        'category_id' => $cat_id,
        'image'       => $img,
        'stock'       => 25,
    ];
}

try {
    echo "\nStarting product import from images...\n\n";

    $check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE image = ?");
    $stmt = $pdo->prepare("INSERT INTO products (name, description, price, category_id, image, stock, is_featured) VALUES (?, ?, ?, ?, ?, ?, 0)");

    $inserted = 0;
    $skipped = 0;

    foreach ($products_data as $p) {
        $check->execute([$p['image']]);
        if ($check->fetchColumn() > 0) {
            echo "SKIPPED: Product with image '{$p['image']}' already exists.\n";
            $skipped++;
            continue;
        }

        $stmt->execute([
            $p['name'],
            $p['description'],
            $p['price'],
            $p['category_id'],
            $p['image'],
            $p['stock'],
        ]);

        $new_id = $pdo->lastInsertId();
        echo "INSERTED: {$p['name']} (ID: $new_id) - {$p['image']}\n";
        $inserted++;
    }

    echo "\n--- Summary ---\n";
    echo "Inserted: $inserted products\n";
    echo "Skipped: $skipped products (already exist)\n";
    echo "Done!\n";

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
