<?php
/*
Simple Menu Import for CSV Import Plugin
Handles menu items with options and choices in a single CSV file
*/

// Security check - only allow access through admin
if (!defined('IS_CMS_ADMIN') && !function_exists('isAdmin')) {
    die("Direct access not allowed.");
}

function csvImp_simpleMenuImport() {
    // Handle form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submitForm'])) {
        csvImp_processSimpleMenuImport();
    } else {
        // Show upload form
        csvImp_showSimpleUploadForm();
    }
}

function csvImp_showSimpleUploadForm() {
    // Get all restaurants for dropdown
    $restaurants = mysql_query_fetch_all_assoc("SELECT num, name FROM {$GLOBALS['TABLE_PREFIX']}listings ORDER BY name ASC");
    
    // Start output buffering to capture content
    ob_start();
    ?>
    <div class="alert alert-info">
        <h4>Simple Menu Import</h4>
        <p>Import menu items with their options and choices from a single CSV file.</p>
    </div>

    <form method="POST" enctype="multipart/form-data" action="admin.php?_pluginAction=csvImport_simpleMenuImport" accept-charset="UTF-8">
        <input type="hidden" name="_pluginAction" value="csvImport_simpleMenuImport">
        <input type="hidden" name="submitForm" value="1">
        <input type="hidden" name="menu" value="<?php echo htmlspecialchars(@$_REQUEST['menu']); ?>">
        <input type="hidden" name="debug" value="1">
        
        <div class="form-horizontal">
            <div class="form-group">
                <div class="col-sm-2 control-label">
                    <strong>CSV File</strong>
                </div>
                <div class="col-sm-10" style="padding-top: 4px">
                    <input type="file" name="csv_file" id="csv_file" accept=".csv" required class="form-control" onchange="updatePreview()">
                    <p class="help-block">Select your CSV file containing menu data</p>
                </div>
            </div>
            
            <div class="form-group">
                <div class="col-sm-2 control-label">
                    <strong>Restaurant</strong>
                </div>
                <div class="col-sm-10">
                    <select name="listingsNum" id="listingsNum" required class="form-control">
                        <option value="">Select Restaurant</option>
                        <?php foreach ($restaurants as $restaurant): ?>
                        <option value="<?php echo htmlspecialchars($restaurant['num']); ?>">
                            <?php echo htmlspecialchars($restaurant['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="help-block">Select the restaurant for menu import</p>
                </div>
            </div>
            
            <div class="form-group">
                <div class="col-sm-2 control-label">
                </div>
                <div class="col-sm-10">
                    <button type="submit" class="btn btn-primary">Import Menu &gt;&gt;</button>
                </div>
            </div>
        </div>

        <br>
        <hr>
        
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">CSV Format Instructions</h4>
            </div>
            <div class="panel-body">
                <p><strong>Your CSV should have these columns:</strong></p>
                <div class="row">
                    <div class="col-md-6">
                        <h5>Menu Item Columns (Required):</h5>
                        <ul>
                            <li><code>name</code> - Menu item name</li>
                            <li><code>category</code> - Category ID (number)</li>
                            <li><code>price</code> - Base price</li>
                            <li><code>ingredients</code> - Ingredients description (optional)</li>
                            <li><code>enable_order</code> - 1 for enabled, 0 for disabled</li>
                            <li><code>delivery_type</code> - delivery,pickup (optional)</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h5>Options & Choices Columns (Optional):</h5>
                        <ul>
                            <li><code>option_name</code> - Option name (e.g., "Size", "Toppings")</li>
                            <li><code>option_type</code> - required, optional, sides, desserts</li>
                            <li><code>option_price</code> - Additional price for option</li>
                            <li><code>is_required</code> - 1 for required, 0 for optional</li>
                            <li><code>min_selection</code> - Minimum selections allowed</li>
                            <li><code>max_selection</code> - Maximum selections allowed</li>
                            <li><code>choice_name</code> - Choice name (e.g., "Small", "Large")</li>
                            <li><code>choice_description</code> - Choice description</li>
                            <li><code>choice_price</code> - Price for this choice</li>
                        </ul>
                    </div>
                </div>
                
                <div class="alert alert-warning">
                    <h5>Important Notes:</h5>
                    <ul>
                        <li>Each menu item can have multiple options</li>
                        <li>Each option can have multiple choices</li>
                        <li>Leave option/choice columns empty if not needed</li>
                        <li>Use the same menu item name to group options together</li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">CSV Preview</h4>
            </div>
            <div class="panel-body">
                <div style="height: 300px; overflow: auto; border: 1px solid #ddd; padding: 10px;" id="previewContent">
                    <div style="text-align: center; color: #999; padding: 20px;">
                        Upload a CSV file to see preview...
                    </div>
                </div>
            </div>
        </div>
    </form>

    <script type="text/javascript">
    function updatePreview() {
        var fileInput = document.getElementById('csv_file');
        var file = fileInput.files[0];

        if (!file) {
            document.getElementById('previewContent').innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">Upload a CSV file to see preview...</div>';
            return;
        }

        var reader = new FileReader();
        reader.onload = function(e) {
            var csv = e.target.result;
            var lines = csv.split('\n');
            var previewRows = lines.slice(0, 10); // Show first 10 rows

            var table = '<table class="table table-striped table-bordered table-hover">';
            table += '<thead><tr>';

            // Get headers from first line
            var headers = previewRows[0].split(',');
            headers.forEach(function(header) {
                table += '<th><strong>' + header.trim() + '</strong></th>';
            });
            table += '</tr></thead>';

            // Add data rows
            table += '<tbody>';
            for (var i = 1; i < previewRows.length; i++) {
                if (previewRows[i].trim()) {
                    var cells = previewRows[i].split(',');
                    table += '<tr>';
                    cells.forEach(function(cell) {
                        table += '<td>' + cell.trim() + '</td>';
                    });
                    table += '</tr>';
                }
            }
            table += '</tbody></table>';

            document.getElementById('previewContent').innerHTML = table;
        };

        reader.readAsText(file);
    }
    
    // Ensure form has correct enctype
    document.addEventListener('DOMContentLoaded', function() {
        var form = document.querySelector('form');
        form.setAttribute('enctype', 'multipart/form-data');
    });
    </script>
    <?php
    
    $content = ob_get_clean();
    
    // Use adminUI for consistent layout
    $adminUI = csvImp_getSimpleAdminUiDefaults();
    $adminUI['CONTENT'] = $content;
    adminUI($adminUI);
    exit;
}

function csvImp_getSimpleAdminUiDefaults() {
    $adminUI = [];
    
    // page title
    $adminUI['PAGE_TITLE'] = [
        t("Plugins") => '?menu=admin&action=plugins',
        t("CSV Import") => '?_pluginAction=csvImport_uploadForm',
        t("Simple Menu Import") => "?_pluginAction=csvImport_simpleMenuImport",
    ];
    
    // button
    $adminUI['BUTTONS'] = [
        ['name' => 'back_to_csv_import', 'label' => 'Back to CSV Import &gt;&gt;', 'onclick' => 'window.location="?_pluginAction=csvImport_uploadForm";', 'type' => 'button'],
        ['name' => 'back_to_plugins', 'label' => 'Back to Plugins &gt;&gt;', 'onclick' => 'window.location="?menu=admin&action=plugins";', 'type' => 'button'],
    ];
    
    return $adminUI;
}

function csvImp_processSimpleMenuImport() {
    // Check if file was uploaded
    if (!isset($_FILES['csv_file'])) {
        csvImp_showSimpleError("No file uploaded. Please select a CSV file.");
        return;
    }
    
    if (empty($_FILES['csv_file']['name'])) {
        csvImp_showSimpleError("No file selected. Please select a CSV file.");
        return;
    }
    
    $file = $_FILES['csv_file'];
    $listingsNum = intval($_POST['listingsNum']);
    
    // Validate file
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorMessage = "File upload failed. Error code: " . $file['error'];
        switch ($file['error']) {
            case UPLOAD_ERR_INI_SIZE:
                $errorMessage .= " (File too large - exceeds upload_max_filesize)";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $errorMessage .= " (File too large - exceeds MAX_FILE_SIZE)";
                break;
            case UPLOAD_ERR_PARTIAL:
                $errorMessage .= " (File upload was incomplete)";
                break;
            case UPLOAD_ERR_NO_FILE:
                $errorMessage .= " (No file was uploaded)";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $errorMessage .= " (Missing temporary folder)";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $errorMessage .= " (Failed to write file to disk)";
                break;
            case UPLOAD_ERR_EXTENSION:
                $errorMessage .= " (File upload stopped by extension)";
                break;
        }
        csvImp_showSimpleError($errorMessage);
        return;
    }
    
    // Check file extension
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if ($ext !== 'csv') {
        csvImp_showSimpleError("Please upload a valid CSV file (.csv).");
        return;
    }
    
    // Validate listingsNum
    if (!$listingsNum) {
        csvImp_showSimpleError("Please select a restaurant.");
        return;
    }
    
    // Check if restaurant exists
    $restaurant = mysql_get('listings', $listingsNum);
    if (!$restaurant) {
        csvImp_showSimpleError("Restaurant with ID $listingsNum not found.");
        return;
    }
    
    try {
        // Read CSV file
        $csvData = csvImp_readSimpleCSVFile($file['tmp_name']);
        if (empty($csvData)) {
            csvImp_showSimpleError("CSV file is empty or could not be read.");
            return;
        }
        
        // Process import
        $results = csvImp_importSimpleMenuData($csvData, $listingsNum);
        
        // Show results
        csvImp_showSimpleImportResults($results, $restaurant);
        
    } catch (Exception $e) {
        csvImp_showSimpleError("Import failed: " . $e->getMessage());
    }
}

function csvImp_readSimpleCSVFile($filePath) {
    $data = [];
    $handle = fopen($filePath, 'r');
    
    if ($handle === false) {
        throw new Exception("Could not open CSV file");
    }
    
    // Read headers
    $headers = fgetcsv($handle);
    
    if (!$headers) {
        fclose($handle);
        throw new Exception("Could not read CSV headers");
    }
    
    // Read data rows
    while (($row = fgetcsv($handle)) !== false) {
        if (count($row) === count($headers)) {
            $data[] = array_combine($headers, $row);
        }
    }
    
    fclose($handle);
    return $data;
}

function csvImp_importSimpleMenuData($csvData, $listingsNum) {
    $results = [
        'total_rows' => count($csvData),
        'menu_items_created' => 0,
        'menu_items_updated' => 0,
        'options_created' => 0,
        'choices_created' => 0,
        'errors' => []
    ];
    
    // Group data by menu item
    $menuGroups = [];
    foreach ($csvData as $row) {
        $menuKey = $row['name'] . '|' . $row['category'] . '|' . $row['price'];
        if (!isset($menuGroups[$menuKey])) {
            $menuGroups[$menuKey] = [
                'menu_data' => $row,
                'options' => []
            ];
        }
        
        if (!empty($row['option_name'])) {
            $menuGroups[$menuKey]['options'][] = $row;
        }
    }
    
    foreach ($menuGroups as $menuKey => $group) {
        try {
            // Check if menu item already exists
            $existingMenu = mysql_get('menu', null, "listingsNum = $listingsNum AND name = '" . mysql_escape($group['menu_data']['name']) . "' AND category = " . intval($group['menu_data']['category']) . " AND price = " . floatval($group['menu_data']['price']));
            
            if ($existingMenu) {
                // Update existing menu item
                $menuId = $existingMenu['num'];
                $updateData = [
                    'ingredients' => $group['menu_data']['ingredients'] ?? $existingMenu['ingredients'],
                    'enable_order' => intval($group['menu_data']['enable_order'] ?? $existingMenu['enable_order']),
                    'delivery_type' => $group['menu_data']['delivery_type'] ?? $existingMenu['delivery_type'],
                    'updatedDate' => date('Y-m-d H:i:s')
                ];
                mysql_update('menu', $menuId, null, $updateData);
                $results['menu_items_updated']++;
            } else {
                // Create new menu item
                $menuId = csvImp_createSimpleMenuItem($group['menu_data'], $listingsNum);
                if ($menuId) {
                    $results['menu_items_created']++;
                }
            }
            
            // Create options and choices
            if ($menuId && !empty($group['options'])) {
                
                foreach ($group['options'] as $optionRow) {
                    $optionId = csvImp_createSimpleMenuOption($optionRow, $menuId);
                    if ($optionId) {
                        $results['options_created']++;
                        
                        // Create choices if they exist
                        if (!empty($optionRow['choice_name'])) {
                            $choiceId = csvImp_createSimpleMenuChoice($optionRow, $optionId);
                            if ($choiceId) {
                                $results['choices_created']++;
                            } else {
                                $results['errors'][] = "Failed to create choice";
                            }
                        }
                    } else {
                        $results['errors'][] = "Failed to create option";
                    }
                }
            }
        } catch (Exception $e) {
            $errorMsg = "Error processing menu item '{$group['menu_data']['name']}': " . $e->getMessage();
            $results['errors'][] = $errorMsg;
        }
    }
    
    return $results;
}

function csvImp_createSimpleMenuItem($menuData, $listingsNum) {
    $menuData = array_map('trim', $menuData);
    
    $menuInsert = [
        'listingsNum' => $listingsNum,
        'name' => $menuData['name'] ?? '',
        'category' => intval($menuData['category'] ?? 0),
        'price' => floatval($menuData['price'] ?? 0),
        'ingredients' => $menuData['ingredients'] ?? '',
        'enable_order' => intval($menuData['enable_order'] ?? 1),
        'delivery_type' => $menuData['delivery_type'] ?? 'delivery,pickup',
        'is_featured' => 0,
        'is_posItem' => 0,
        'createdByUserNum' => intval(@$_SESSION['adminUserNum'] ?? 0),
        'updatedByUserNum' => intval(@$_SESSION['adminUserNum'] ?? 0),
        'createdDate' => date('Y-m-d H:i:s'),
        'updatedDate' => date('Y-m-d H:i:s')
    ];
    
    $menuId = mysql_insert('menu', $menuInsert);
    return $menuId;
}

function csvImp_createSimpleMenuOption($optionData, $menuId) {
    
    $optionData = array_map('trim', $optionData);
    
    $optionInsert = [
        'menu_id' => $menuId,
        'option_name' => $optionData['option_name'] ?? '',
        'option_type' => $optionData['option_type'] ?? 'required',
        'option_category' => '',
        'price' => floatval($optionData['option_price'] ?? 0),
        'is_required' => intval($optionData['is_required'] ?? 0),
        'min_selection' => intval($optionData['min_selection'] ?? 0),
        'max_selection' => intval($optionData['max_selection'] ?? 1),
        'sort_order' => 1,
        'is_active' => 1,
        'createdByUserNum' => intval(@$_SESSION['adminUserNum'] ?? 0),
        'updatedByUserNum' => intval(@$_SESSION['adminUserNum'] ?? 0),
        'createdDate' => date('Y-m-d H:i:s'),
        'updatedDate' => date('Y-m-d H:i:s')
    ];
    
    $optionId = mysql_insert('menu_options', $optionInsert);
    
    return $optionId;
}

function csvImp_createSimpleMenuChoice($choiceData, $optionId) {
    $choiceData = array_map('trim', $choiceData);
    
    $choiceInsert = [
        'option_id' => $optionId,
        'choice_name' => $choiceData['choice_name'] ?? '',
        'choice_description' => $choiceData['choice_description'] ?? '',
        'price' => floatval($choiceData['choice_price'] ?? 0),
        'sort_order' => 1,
        'is_available' => 1,
        'createdByUserNum' => intval(@$_SESSION['adminUserNum'] ?? 0),
        'updatedByUserNum' => intval(@$_SESSION['adminUserNum'] ?? 0),
        'createdDate' => date('Y-m-d H:i:s'),
        'updatedDate' => date('Y-m-d H:i:s')
    ];
    
    $choiceId = mysql_insert('menu_option_choices', $choiceInsert);
    return $choiceId;
}

function csvImp_showSimpleImportResults($results, $restaurant) {
    // prepare adminUI() placeholders
    $adminUI = csvImp_getSimpleAdminUiDefaults();
    
    // content to display
    $adminUI['CONTENT'] = ob_capture(function() use ($results, $restaurant) {
        ?>
        <div class="alert alert-success">
            <h4>Import Complete!</h4>
            <p>Successfully imported menu data for <strong><?php echo htmlspecialchars($restaurant['name']); ?></strong></p>
        </div>
        
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">Import Summary</h4>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><strong>Total rows processed:</strong> <?php echo htmlspecialchars($results['total_rows']); ?></li>
                            <li><strong>Menu items created:</strong> <?php echo htmlspecialchars($results['menu_items_created']); ?></li>
                            <li><strong>Menu items updated:</strong> <?php echo htmlspecialchars($results['menu_items_updated']); ?></li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><strong>Options created:</strong> <?php echo htmlspecialchars($results['options_created']); ?></li>
                            <li><strong>Choices created:</strong> <?php echo htmlspecialchars($results['choices_created']); ?></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        
        <?php if (!empty($results['errors'])): ?>
        <div class="panel panel-danger">
            <div class="panel-heading">
                <h4 class="panel-title">Errors</h4>
            </div>
            <div class="panel-body">
                <ul class="list-unstyled">
                    <?php foreach ($results['errors'] as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="form-group">
            <div class="col-sm-2 control-label">
            </div>
            <div class="col-sm-10">
                <?php echo adminUI_button(['type' => 'button', 'btn-type' => 'primary', 'label' => 'Import Another Menu', 'onclick' => "location.href='?_pluginAction=csvImport_simpleMenuImport'; return false;"]); ?>
                <?php echo adminUI_button(['type' => 'button', 'btn-type' => 'default', 'label' => 'Back to CSV Import', 'onclick' => "location.href='?_pluginAction=csvImport_uploadForm'; return false;"]); ?>
            </div>
        </div>
        <?php
    });
    
    // display content
    adminUI($adminUI);
    exit;
}

function csvImp_showSimpleError($message) {
    // prepare adminUI() placeholders
    $adminUI = csvImp_getSimpleAdminUiDefaults();
    
    // content to display
    $adminUI['CONTENT'] = ob_capture(function() use ($message) {
        ?>
        <div class="alert alert-danger">
            <h4>Error:</h4>
            <p><?php echo htmlspecialchars($message); ?></p>
        </div>
        
        <div class="form-group">
            <div class="col-sm-2 control-label">
            </div>
            <div class="col-sm-10">
                <?php echo adminUI_button(['type' => 'button', 'btn-type' => 'default', 'label' => 'Try Again', 'onclick' => "location.href='?_pluginAction=csvImport_simpleMenuImport'; return false;"]); ?>
                <?php echo adminUI_button(['type' => 'button', 'btn-type' => 'primary', 'label' => 'Back to CSV Import', 'onclick' => "location.href='?_pluginAction=csvImport_uploadForm'; return false;"]); ?>
            </div>
        </div>
        <?php
    });
    
    // display content
    adminUI($adminUI);
    exit;
}

function csvImp_showSimpleTestResults() {
    // prepare adminUI() placeholders
    $adminUI = csvImp_getSimpleAdminUiDefaults();
    
    // content to display
    $adminUI['CONTENT'] = ob_capture(function() {
        ?>
        <div class="alert alert-info">
            <h4>Upload Test Results</h4>
            <p>Debug information for file upload test:</p>
        </div>
        
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">Server Information</h4>
            </div>
            <div class="panel-body">
                <ul class="list-unstyled">
                    <li><strong>REQUEST_METHOD:</strong> <?php echo htmlspecialchars($_SERVER['REQUEST_METHOD']); ?></li>
                    <li><strong>CONTENT_TYPE:</strong> <?php echo htmlspecialchars($_SERVER['CONTENT_TYPE']); ?></li>
                    <li><strong>CONTENT_LENGTH:</strong> <?php echo htmlspecialchars($_SERVER['CONTENT_LENGTH']); ?></li>
                    <li><strong>upload_max_filesize:</strong> <?php echo htmlspecialchars(ini_get('upload_max_filesize')); ?></li>
                    <li><strong>post_max_size:</strong> <?php echo htmlspecialchars(ini_get('post_max_size')); ?></li>
                    <li><strong>max_file_uploads:</strong> <?php echo htmlspecialchars(ini_get('max_file_uploads')); ?></li>
                    <li><strong>file_uploads:</strong> <?php echo htmlspecialchars(ini_get('file_uploads')); ?></li>
                </ul>
            </div>
        </div>
        
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">POST Data</h4>
            </div>
            <div class="panel-body">
                <pre><?php echo htmlspecialchars(print_r($_POST, true)); ?></pre>
            </div>
        </div>
        
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">FILES Data</h4>
            </div>
            <div class="panel-body">
                <pre><?php echo htmlspecialchars(print_r($_FILES, true)); ?></pre>
            </div>
        </div>
        
        <div class="form-group">
            <div class="col-sm-2 control-label">
            </div>
            <div class="col-sm-10">
                <?php echo adminUI_button(['type' => 'button', 'btn-type' => 'default', 'label' => 'Back to Upload Form', 'onclick' => "location.href='?_pluginAction=csvImport_simpleMenuImport'; return false;"]); ?>
            </div>
        </div>
        <?php
    });
    
    // display content
    adminUI($adminUI);
    exit;
}
    