<?php
/**
 * Import menu items from CSV
 */

require_once __DIR__ . '/bootstrap/db.php';

$csvFile = 'c:\Users\ChenopeUser\Downloads\menu-lokale-2025-12-11.csv';

if (!file_exists($csvFile)) {
    die("CSV file not found: $csvFile\n");
}

echo "Importing menu items from CSV...\n\n";

try {
    $pdo->beginTransaction();
    
    // Get categories mapping
    $categoriesStmt = $pdo->query("SELECT id, name FROM menu_categories");
    $categories = [];
    while ($row = $categoriesStmt->fetch(PDO::FETCH_ASSOC)) {
        $categories[$row['name']] = $row['id'];
    }
    
    // Get locations mapping
    $locationsStmt = $pdo->query("SELECT id, name FROM locations");
    $locations = [];
    while ($row = $locationsStmt->fetch(PDO::FETCH_ASSOC)) {
        $locations[$row['name']] = $row['id'];
    }
    
    echo "Found " . count($categories) . " categories\n";
    echo "Found " . count($locations) . " locations\n\n";
    
    // Location field names from CSV
    $locationFields = [
        'Słoneczna 1',
        'Witkiewicza 2',
        'Krupówki 4a',
        'Kościelisko',
        'Kasprusie 34',
        'Chramcówki 4',
        'Pardałówka'
    ];
    
    // Open CSV
    $handle = fopen($csvFile, 'r');
    $headers = fgetcsv($handle, 0, ',');
    
    echo "CSV Headers:\n";
    foreach ($headers as $idx => $header) {
        echo "  [$idx] $header\n";
    }
    echo "\n";
    
    $imported = 0;
    $skipped = 0;
    
    while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
        if (count($data) < 10) {
            $skipped++;
            continue;
        }
        
        // Extract data based on CSV structure
        $code = $data[0] ?? null;
        $categoryName = $data[1] ?? '';
        $namePL = $data[2] ?? '';
        $nameEN = $data[3] ?? '';
        $afterNamePL = $data[4] ?? '';
        $afterNameEN = $data[5] ?? '';
        $descriptionPL = $data[6] ?? '';
        $descriptionEN = $data[7] ?? '';
        $imageUrl = $data[8] ?? null;
        
        // Price tier 1
        $price1PrefixPL = $data[9] ?? null;
        $price1 = $data[10] ?? null;
        $price1PrefixEN = $data[11] ?? null;
        
        // Price tier 2
        $price2PrefixPL = $data[12] ?? null;
        $price2 = $data[13] ?? null;
        $price2PrefixEN = $data[14] ?? null;
        
        // Price tier 3
        $price3PrefixPL = $data[15] ?? null;
        $price3 = $data[16] ?? null;
        $price3PrefixEN = $data[17] ?? null;
        
        // Display settings
        $displayOrder = $data[18] ?? 0;
        $fontSize = $data[19] ?? null;
        $customCSS = $data[20] ?? null;
        $borderStyle = $data[21] ?? null;
        
        // Location flags start at index 22
        $locationData = [];
        for ($i = 0; $i < count($locationFields); $i++) {
            $locationData[$locationFields[$i]] = isset($data[22 + $i]) && $data[22 + $i] == '1';
        }
        
        if (empty($namePL)) {
            $skipped++;
            continue;
        }
        
        // Get category ID
        $categoryId = null;
        if (!empty($categoryName) && isset($categories[$categoryName])) {
            $categoryId = $categories[$categoryName];
        }
        
        // Insert menu item
        $sql = "INSERT INTO menu_items (
            code, menu_category_id, name_pl, name_en, after_name_pl, after_name_en,
            description_pl, description_en, image_url,
            price_1_prefix_pl, price_1, price_1_prefix_en,
            price_2_prefix_pl, price_2, price_2_prefix_en,
            price_3_prefix_pl, price_3, price_3_prefix_en,
            display_order, font_size, custom_css, border_style, is_active
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $code,
            $categoryId,
            $namePL,
            $nameEN,
            $afterNamePL,
            $afterNameEN,
            $descriptionPL,
            $descriptionEN,
            $imageUrl,
            $price1PrefixPL,
            $price1,
            $price1PrefixEN,
            $price2PrefixPL,
            $price2,
            $price2PrefixEN,
            $price3PrefixPL,
            $price3,
            $price3PrefixEN,
            $displayOrder,
            $fontSize,
            $customCSS,
            $borderStyle
        ]);
        
        $itemId = $pdo->lastInsertId();
        
        // Insert location associations
        $locationStmt = $pdo->prepare("INSERT INTO menu_item_locations (menu_item_id, location_id) VALUES (?, ?)");
        foreach ($locationData as $locationName => $isActive) {
            if ($isActive && isset($locations[$locationName])) {
                $locationStmt->execute([$itemId, $locations[$locationName]]);
            }
        }
        
        $imported++;
        echo "✓ Imported: $namePL (Category: $categoryName)\n";
    }
    
    fclose($handle);
    
    $pdo->commit();
    
    echo "\n✅ Import completed!\n";
    echo "  Imported: $imported items\n";
    echo "  Skipped: $skipped items\n";
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo "❌ Error: " . $e->getMessage() . "\n";
    exit(1);
}
