<?php
/**
 * Enhanced Menu Import with Options Support
 * This script handles CSV import for menus with options and choices
 */

// Include CMSB
require_once 'lib/init.php';
require_once 'plugins/menuOptions/menuOptions_functions.php';

try {
    echo "<h2>📋 Enhanced Menu Import with Options</h2>\n";
    
    // Check if CSV file is uploaded
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        
        $uploadedFile = $_FILES['csv_file']['tmp_name'];
        $fileName = $_FILES['csv_file']['name'];
        
        echo "<p style='color: blue;'>🔄 Processing file: <strong>$fileName</strong></p>\n";
        
        // Read CSV data
        $csvData = [];
        $handle = fopen($uploadedFile, 'r');
        
        if ($handle) {
            // Get headers
            $headers = fgetcsv($handle);
            echo "<p>📋 Headers found: <strong>" . implode(', ', $headers) . "</strong></p>\n";
            
            // Read data rows
            while (($data = fgetcsv($handle)) !== false) {
                $row = array_combine($headers, $data);
                $csvData[] = $row;
            }
            fclose($handle);
            
            echo "<p>📊 Total rows to import: <strong>" . count($csvData) . "</strong></p>\n";
            
            // Process import using enhanced function
            $results = enhancedMenuImport($csvData, 'menu');
            
            if ($results['success']) {
                echo "<h3 style='color: green;'>✅ Import Completed Successfully!</h3>\n";
                echo "<ul>\n";
                echo "<li>🍽️ Menus imported: <strong>{$results['menus_imported']}</strong></li>\n";
                echo "<li>⚙️ Options imported: <strong>{$results['options_imported']}</strong></li>\n";
                echo "<li>🔧 Choices imported: <strong>{$results['choices_imported']}</strong></li>\n";
                echo "</ul>\n";
                
                if (!empty($results['errors'])) {
                    echo "<h4 style='color: orange;'>⚠️ Warnings:</h4>\n";
                    echo "<ul>\n";
                    foreach ($results['errors'] as $error) {
                        echo "<li style='color: orange;'>$error</li>\n";
                    }
                    echo "</ul>\n";
                }
                
            } else {
                echo "<h3 style='color: red;'>❌ Import Failed!</h3>\n";
                echo "<p style='color: red;'>Error: {$results['error']}</p>\n";
            }
            
        } else {
            echo "<p style='color: red;'>❌ Could not read uploaded file</p>\n";
        }
        
    } else {
        // Show upload form
        echo "<form method='POST' enctype='multipart/form-data'>\n";
        echo "<div style='margin: 20px 0;'>\n";
        echo "<label for='csv_file'><strong>📁 Select CSV File:</strong></label><br>\n";
        echo "<input type='file' name='csv_file' id='csv_file' accept='.csv' required style='margin: 10px 0;'>\n";
        echo "</div>\n";
        echo "<button type='submit' style='background: #007cba; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer;'>🚀 Import Menu with Options</button>\n";
        echo "</form>\n";
        
        echo "<h3>📋 CSV Format Required:</h3>\n";
        echo "<p>Your CSV file should have the following columns (all optional except 'name'):</p>\n";
        
        echo "<h4>🍽️ Menu Fields:</h4>\n";
        echo "<ul>\n";
        echo "<li><strong>name</strong> - Menu item name (required)</li>\n";
        echo "<li><strong>category</strong> - Menu category</li>\n";
        echo "<li><strong>price</strong> - Menu item price</li>\n";
        echo "<li><strong>ingredients</strong> - Menu ingredients list</li>\n";
        echo "<li><strong>listingsNum</strong> - Restaurant listing ID</li>\n";
        echo "<li><strong>enable_order</strong> - Enable ordering (1 or 0)</li>\n";
        echo "<li><strong>delivery_type</strong> - Delivery options</li>\n";
        echo "</ul>\n";
        
        echo "<h4>⚙️ Option Fields (optional):</h4>\n";
        echo "<ul>\n";
        echo "<li><strong>option_name</strong> - Option name (e.g., 'Select Size')</li>\n";
        echo "<li><strong>option_type</strong> - Type: required, optional, sides, desserts, people_count</li>\n";
        echo "<li><strong>option_category</strong> - Option category</li>\n";
        echo "<li><strong>option_price</strong> - Option base price</li>\n";
        echo "<li><strong>is_required</strong> - Is required (1 or 0)</li>\n";
        echo "<li><strong>min_selection</strong> - Minimum selections</li>\n";
        echo "<li><strong>max_selection</strong> - Maximum selections</li>\n";
        echo "<li><strong>option_sort_order</strong> - Display order</li>\n";
        echo "</ul>\n";
        
        echo "<h4>🔧 Choice Fields (optional):</h4>\n";
        echo "<ul>\n";
        echo "<li><strong>choice_name</strong> - Choice name (e.g., 'Large')</li>\n";
        echo "<li><strong>choice_description</strong> - Choice description</li>\n";
        echo "<li><strong>choice_price</strong> - Additional price for choice</li>\n";
        echo "<li><strong>choice_sort_order</strong> - Display order</li>\n";
        echo "</ul>\n";
        
        echo "<h4>📊 Sample CSV:</h4>\n";
        echo "<pre style='background: #f5f5f5; padding: 15px; overflow-x: auto; font-size: 12px;'>";
        echo "name,category,price,ingredients,listingsNum,option_name,option_type,is_required,choice_name,choice_price\n";
        echo "\"Beef Burrito\",\"Main Course\",12.99,\"Beef, rice, beans, cheese\",3,\"Select Size\",\"required\",1,\"Regular\",0.00\n";
        echo "\"Beef Burrito\",\"Main Course\",12.99,\"Beef, rice, beans, cheese\",3,\"Select Size\",\"required\",1,\"Large\",3.00\n";
        echo "\"Beef Burrito\",\"Main Course\",12.99,\"Beef, rice, beans, cheese\",3,\"Add Sides\",\"optional\",0,\"Chips & Salsa\",2.50\n";
        echo "\"Chicken Tacos\",\"Main Course\",9.99,\"Chicken, corn tortillas, cilantro\",3,\"Select Number\",\"people_count\",1,\"1 Person\",0.00\n";
        echo "\"Chicken Tacos\",\"Main Course\",9.99,\"Chicken, corn tortillas, cilantro\",3,\"Select Number\",\"people_count\",1,\"2 People\",8.00\n";
        echo "</pre>\n";
        
        echo "<div style='background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; margin: 20px 0; border-radius: 5px;'>\n";
        echo "<h4>💡 Import Tips:</h4>\n";
        echo "<ul>\n";
        echo "<li>Each row can create a menu item, option, and choice</li>\n";
        echo "<li>Repeat menu data for multiple options/choices</li>\n";
        echo "<li>Leave option/choice fields empty for menu-only rows</li>\n";
        echo "<li>Test with a small file first</li>\n";
        echo "<li>Check existing menu items after import</li>\n";
        echo "</ul>\n";
        echo "</div>\n";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>\n";
}
?>
