<?php
/*
Menu Options Manager - Functions File
Contains all the backend functions for managing menu options
*/

// Create schema tables for menu options
function _menuOptions_pluginSetup_createSchemas() {
  // Check if tables exist
  $menuOptionsTable = 'cmsb_menu_options';
  $menuOptionChoicesTable = 'cmsb_menu_option_choices';
  
  // Create menu_options table if it doesn't exist
  $createMenuOptionsTable = "
    CREATE TABLE IF NOT EXISTS `$menuOptionsTable` (
      `num` int(11) NOT NULL AUTO_INCREMENT,
      `createdDate` datetime DEFAULT NULL,
      `createdByUserNum` int(11) DEFAULT 0,
      `updatedDate` datetime DEFAULT NULL,
      `updatedByUserNum` int(11) DEFAULT 0,
      `menu_id` int(11) NOT NULL,
      `option_name` varchar(255) NOT NULL DEFAULT '',
      `option_type` varchar(50) NOT NULL DEFAULT 'required',
      `option_category` varchar(100) DEFAULT '',
      `price` decimal(10,2) DEFAULT 0.00,
      `is_required` tinyint(1) DEFAULT 0,
      `min_selection` int(11) DEFAULT 1,
      `max_selection` int(11) DEFAULT 1,
      `sort_order` int(11) DEFAULT 0,
      `is_active` tinyint(1) DEFAULT 1,
      PRIMARY KEY (`num`),
      INDEX `menu_id` (`menu_id`),
      INDEX `is_active` (`is_active`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  ";
  
  // Create menu_option_choices table if it doesn't exist
  $createMenuOptionChoicesTable = "
    CREATE TABLE IF NOT EXISTS `$menuOptionChoicesTable` (
      `num` int(11) NOT NULL AUTO_INCREMENT,
      `createdDate` datetime DEFAULT NULL,
      `createdByUserNum` int(11) DEFAULT 0,
      `updatedDate` datetime DEFAULT NULL,
      `updatedByUserNum` int(11) DEFAULT 0,
      `option_id` int(11) NOT NULL,
      `choice_name` varchar(255) NOT NULL DEFAULT '',
      `choice_description` varchar(500) DEFAULT '',
      `price` decimal(10,2) DEFAULT 0.00,
      `is_available` tinyint(1) DEFAULT 1,
      `sort_order` int(11) DEFAULT 0,
      PRIMARY KEY (`num`),
      INDEX `option_id` (`option_id`),
      INDEX `is_available` (`is_available`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  ";
  
  // Execute table creation using CMSB's mysql functions
  mysql_do($createMenuOptionsTable);
  mysql_do($createMenuOptionChoicesTable);
  
  // Create schema files
  _menuOptions_createSchemaFiles();
}

// Create menu options schema files
function _menuOptions_createSchemaFiles() {
  $schemaDir = __DIR__ . '/pluginSchemas';
  
  // Create pluginSchemas directory if it doesn't exist
  if (!is_dir($schemaDir)) {
    mkdir($schemaDir, 0755, true);
  }
  
  // Create menu_options.ini.php
  $menuOptionsSchema = "<?php /* This is a PHP data file */ if (!@\$LOADSTRUCT) { die(\"This is not a program file.\"); }
return array (
  '_detailPage' => '',
  '_disableAdd' => '0',
  '_disableErase' => '0',
  '_disableModify' => '0',
  '_disablePreview' => '0',
  '_disableView' => '1',
  '_filenameFields' => 'option_name',
  '_hideRecordsFromDisabledAccounts' => '0',
  '_indent' => '0',
  '_listPage' => '',
  '_maxRecords' => '',
  '_maxRecordsPerUser' => '',
  '_perPageDefault' => '25',
  '_previewPage' => '',
  '_requiredPlugins' => '',
  '_tableName' => 'menu_options',
  'listPageFields' => 'option_name, menu_id, option_type, is_required, is_active',
  'listPageOrder' => 'menu_id ASC, sort_order ASC',
  'listPageSearchFields' => '_all_',
  'menuHidden' => '0',
  'menuName' => 'Menu Options',
  'menuOrder' => '0000000029',
  'menuPrefixIcon' => 'fa-list',
  'menuType' => 'multi',
  'num' => array(
    'order' => 1,
    'type' => 'none',
    'label' => 'Record Number',
    'isSystemField' => '1',
  ),
  'createdDate' => array(
    'order' => 2,
    'type' => 'none',
    'label' => 'Created',
    'isSystemField' => '1',
  ),
  'createdByUserNum' => array(
    'order' => 3,
    'type' => 'none',
    'label' => 'Created By',
    'isSystemField' => '1',
  ),
  'updatedDate' => array(
    'order' => 4,
    'type' => 'none',
    'label' => 'Last Updated',
    'isSystemField' => '1',
  ),
  'updatedByUserNum' => array(
    'order' => 5,
    'type' => 'none',
    'label' => 'Last Updated By',
    'isSystemField' => '1',
  ),
  'menu_id' => array(
    'order' => 6,
    'label' => 'Menu Item',
    'type' => 'list',
    'indexed' => '1',
    'defaultValue' => '',
    'fieldPrefix' => '',
    'description' => '',
    'isRequired' => '1',
    'isUnique' => '0',
    'listType' => 'pulldown',
    'optionsType' => 'table',
    'optionsTablename' => 'menu',
    'optionsValueField' => 'num',
    'optionsLabelField' => 'name',
  ),
  'option_name' => array(
    'order' => 7,
    'label' => 'Option Name',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '',
    'fieldPrefix' => '',
    'description' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '1',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'option_type' => array(
    'order' => 8,
    'label' => 'Option Type',
    'type' => 'list',
    'indexed' => '0',
    'defaultValue' => 'required',
    'fieldPrefix' => '',
    'description' => '',
    'isRequired' => '1',
    'isUnique' => '0',
    'listType' => 'pulldown',
    'optionsType' => 'values',
    'optionsValues' => 'required|Required
optional|Optional
sides|Sides
desserts|Desserts
people_count|People Count',
  ),
  'option_category' => array(
    'order' => 9,
    'label' => 'Option Category',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '',
    'fieldPrefix' => '',
    'description' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '0',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'price' => array(
    'order' => 10,
    'label' => 'Option Price',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '0.00',
    'fieldPrefix' => '',
    'description' => '',
    'fieldAddonBefore' => '',
    'fieldAddonAfter' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '0',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'is_required' => array(
    'order' => 11,
    'label' => 'Is Required',
    'type' => 'checkbox',
    'indexed' => '0',
    'fieldPrefix' => '',
    'checkedByDefault' => '0',
    'description' => '',
    'checkedValue' => 'Yes',
    'uncheckedValue' => 'No',
  ),
  'min_selection' => array(
    'order' => 12,
    'label' => 'Minimum Selection',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '1',
    'fieldPrefix' => '',
    'description' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '1',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'max_selection' => array(
    'order' => 13,
    'label' => 'Maximum Selection',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '1',
    'fieldPrefix' => '',
    'description' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '1',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'sort_order' => array(
    'order' => 14,
    'label' => 'Sort Order',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '0',
    'fieldPrefix' => '',
    'description' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '0',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'is_active' => array(
    'order' => 15,
    'label' => 'Is Active',
    'type' => 'checkbox',
    'indexed' => '0',
    'fieldPrefix' => '',
    'checkedByDefault' => '1',
    'description' => '',
    'checkedValue' => 'Yes',
    'uncheckedValue' => 'No',
  ),
);
?>";
  
  // Create menu_option_choices.ini.php
  $menuOptionChoicesSchema = "<?php /* This is a PHP data file */ if (!@\$LOADSTRUCT) { die(\"This is not a program file.\"); }
return array (
  '_detailPage' => '',
  '_disableAdd' => '0',
  '_disableErase' => '0',
  '_disableModify' => '0',
  '_disablePreview' => '0',
  '_disableView' => '1',
  '_filenameFields' => 'choice_name',
  '_hideRecordsFromDisabledAccounts' => '0',
  '_indent' => '0',
  '_listPage' => '',
  '_maxRecords' => '',
  '_maxRecordsPerUser' => '',
  '_perPageDefault' => '25',
  '_previewPage' => '',
  '_requiredPlugins' => '',
  '_tableName' => 'menu_option_choices',
  'listPageFields' => 'choice_name, option_id, price, is_available',
  'listPageOrder' => 'option_id ASC, sort_order ASC',
  'listPageSearchFields' => '_all_',
  'menuHidden' => '0',
  'menuName' => 'Menu Option Choices',
  'menuOrder' => '0000000030',
  'menuPrefixIcon' => 'fa-check-square-o',
  'menuType' => 'multi',
  'num' => array(
    'order' => 1,
    'type' => 'none',
    'label' => 'Record Number',
    'isSystemField' => '1',
  ),
  'createdDate' => array(
    'order' => 2,
    'type' => 'none',
    'label' => 'Created',
    'isSystemField' => '1',
  ),
  'createdByUserNum' => array(
    'order' => 3,
    'type' => 'none',
    'label' => 'Created By',
    'isSystemField' => '1',
  ),
  'updatedDate' => array(
    'order' => 4,
    'type' => 'none',
    'label' => 'Last Updated',
    'isSystemField' => '1',
  ),
  'updatedByUserNum' => array(
    'order' => 5,
    'type' => 'none',
    'label' => 'Last Updated By',
    'isSystemField' => '1',
  ),
  'option_id' => array(
    'order' => 6,
    'label' => 'Option',
    'type' => 'list',
    'indexed' => '1',
    'defaultValue' => '',
    'fieldPrefix' => '',
    'description' => '',
    'isRequired' => '1',
    'isUnique' => '0',
    'listType' => 'pulldown',
    'optionsType' => 'table',
    'optionsTablename' => 'menu_options',
    'optionsValueField' => 'id',
    'optionsLabelField' => 'option_name',
  ),
  'choice_name' => array(
    'order' => 7,
    'label' => 'Choice Name',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '',
    'fieldPrefix' => '',
    'description' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '1',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'choice_description' => array(
    'order' => 8,
    'label' => 'Choice Description',
    'type' => 'textbox',
    'indexed' => '0',
    'defaultContent' => '',
    'fieldPrefix' => '',
    'description' => '',
    'isRequired' => '0',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'fieldHeight' => '',
    'autoFormat' => '1',
  ),
  'price' => array(
    'order' => 9,
    'label' => 'Price',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '0.00',
    'fieldPrefix' => '',
    'description' => '',
    'fieldAddonBefore' => '',
    'fieldAddonAfter' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '0',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
  'is_available' => array(
    'order' => 10,
    'label' => 'Is Available',
    'type' => 'checkbox',
    'indexed' => '0',
    'fieldPrefix' => '',
    'checkedByDefault' => '1',
    'description' => '',
    'checkedValue' => 'Yes',
    'uncheckedValue' => 'No',
  ),
  'sort_order' => array(
    'order' => 11,
    'label' => 'Sort Order',
    'type' => 'textfield',
    'indexed' => '0',
    'defaultValue' => '0',
    'fieldPrefix' => '',
    'description' => '',
    'fieldWidth' => '',
    'isPasswordField' => '0',
    'isRequired' => '0',
    'isUnique' => '0',
    'minLength' => '',
    'maxLength' => '',
    'charsetRule' => '',
    'charset' => '',
  ),
);
?>";
  
  // Write schema files
  file_put_contents($schemaDir . '/menu_options.ini.php', $menuOptionsSchema);
  file_put_contents($schemaDir . '/menu_option_choices.ini.php', $menuOptionChoicesSchema);
}

// Get menu options for a specific menu item
function getMenuOptions($menuId) {
  $menuOptionsTable = 'cmsb_menu_options';
  $menuOptionChoicesTable = 'cmsb_menu_option_choices';
  
  // Get menu options
  $optionsQuery = "
    SELECT 
      mo.num as option_id,
      mo.option_name,
      mo.option_type,
      mo.option_category,
      mo.price as option_price,
      mo.is_required,
      mo.min_selection,
      mo.max_selection,
      mo.sort_order,
      mo.is_active
    FROM $menuOptionsTable mo
    WHERE mo.menu_id = " . intval($menuId) . "
    AND mo.is_active = 1
    ORDER BY mo.sort_order ASC, mo.option_name ASC
  ";
  
  $options = mysql_select_query($optionsQuery);
  
  if (!$options) {
    return [];
  }
  
  // Get choices for each option
  foreach ($options as &$option) {
    $choicesQuery = "
      SELECT 
        num as choice_id,
        choice_name,
        choice_description,
        price,
        is_available,
        sort_order
      FROM $menuOptionChoicesTable
      WHERE option_id = " . intval($option['option_id']) . "
      AND is_available = 1
      ORDER BY sort_order ASC, choice_name ASC
    ";
    
    $choices = mysql_select_query($choicesQuery);
    $option['choices'] = $choices ?: [];
  }
  
  return $options;
}

// Create menu options
function createMenuOptions($menuId, $options) {
  try {
    foreach ($options as $option) {
      $optionName = mysql_escape($option['option_name']);
      $optionType = mysql_escape($option['option_type']);
      $optionCategory = mysql_escape($option['option_category'] ?? '');
      $price = floatval($option['price'] ?? 0);
      $isRequired = intval($option['is_required'] ?? 0);
      $minSelection = intval($option['min_selection'] ?? 1);
      $maxSelection = intval($option['max_selection'] ?? 1);
      $sortOrder = intval($option['sort_order'] ?? 0);
      
      // Insert option
      $optionData = [
        'menu_id' => $menuId,
        'option_name' => $optionName,
        'option_type' => $optionType,
        'option_category' => $optionCategory,
        'price' => $price,
        'is_required' => $isRequired,
        'min_selection' => $minSelection,
        'max_selection' => $maxSelection,
        'sort_order' => $sortOrder
      ];
      
      $optionId = mysql_insert('cmsb_menu_options', $optionData);
      
      // Insert choices if provided
      if (isset($option['choices']) && is_array($option['choices'])) {
        foreach ($option['choices'] as $choice) {
          $choiceName = mysql_escape($choice['choice_name']);
          $choiceDescription = mysql_escape($choice['choice_description'] ?? '');
          $choicePrice = floatval($choice['price'] ?? 0);
          $choiceSortOrder = intval($choice['sort_order'] ?? 0);
          
          $choiceData = [
            'option_id' => $optionId,
            'choice_name' => $choiceName,
            'choice_description' => $choiceDescription,
            'price' => $choicePrice,
            'sort_order' => $choiceSortOrder
          ];
          
          mysql_insert('cmsb_menu_option_choices', $choiceData);
        }
      }
    }
    
    return true;
  } catch (Exception $e) {
    return false;
  }
}

// Validate menu options
function validateMenuOptions($menuId, $selectedOptions) {
  global $mysqli;
  
  foreach ($selectedOptions as $option) {
    $optionId = intval($option['option_id'] ?? 0);
    $selectedChoices = $option['selected_choices'] ?? [];
    
    // Validate min/max selections
    if ($optionId > 0) {
      $optionQuery = "SELECT min_selection, max_selection FROM cmsb_menu_options WHERE num = ? AND menu_id = ? AND is_active = 1";
      $optionStmt = $mysqli->prepare($optionQuery);
      $optionStmt->bind_param('ii', $optionId, $menuId);
      $optionStmt->execute();
      $optionResult = $optionStmt->get_result();
      $optionData = $optionResult->fetch_assoc();
      
      if ($optionData) {
        $choiceCount = count($selectedChoices);
        if ($choiceCount < $optionData['min_selection'] || $choiceCount > $optionData['max_selection']) {
          return [
            'valid' => false,
            'error' => "Invalid selection count for option '{$option['option_name']}'. Required: {$optionData['min_selection']}-{$optionData['max_selection']}, Selected: {$choiceCount}"
          ];
        }
      }
    }
  }
  
  return ['valid' => true];
}

// Import menu options from CSV
function importMenuOptionsFromCSV($filePath, $menuId) {
  global $mysqli;
  
  if (!file_exists($filePath)) {
    return ['success' => false, 'error' => 'File not found'];
  }
  
  $handle = fopen($filePath, 'r');
  if (!$handle) {
    return ['success' => false, 'error' => 'Cannot open file'];
  }
  
  $headers = fgetcsv($handle);
  if (!$headers) {
    fclose($handle);
    return ['success' => false, 'error' => 'Invalid CSV format'];
  }
  
  $mysqli->begin_transaction();
  
  try {
    $options = [];
    $currentOption = null;
    
    while (($data = fgetcsv($handle)) !== false) {
      $row = array_combine($headers, $data);
      
      if (!empty($row['option_name'])) {
        // New option
        if ($currentOption) {
          $options[] = $currentOption;
        }
        
        $currentOption = [
          'option_name' => $row['option_name'],
          'option_type' => $row['option_type'] ?? 'required',
          'option_category' => $row['option_category'] ?? '',
          'price' => floatval($row['price'] ?? 0),
          'is_required' => intval($row['is_required'] ?? 0),
          'min_selection' => intval($row['min_selection'] ?? 1),
          'max_selection' => intval($row['max_selection'] ?? 1),
          'sort_order' => intval($row['sort_order'] ?? 0),
          'choices' => []
        ];
      }
      
      if ($currentOption && !empty($row['choice_name'])) {
        // Add choice to current option
        $currentOption['choices'][] = [
          'choice_name' => $row['choice_name'],
          'choice_description' => $row['choice_description'] ?? '',
          'price' => floatval($row['choice_price'] ?? 0),
          'sort_order' => intval($row['choice_sort_order'] ?? 0)
        ];
      }
    }
    
    // Add the last option
    if ($currentOption) {
      $options[] = $currentOption;
    }
    
    fclose($handle);
    
    // Create the options
    if (createMenuOptions($menuId, $options)) {
      $mysqli->commit();
      return ['success' => true, 'options_created' => count($options)];
    } else {
      $mysqli->rollback();
      return ['success' => false, 'error' => 'Failed to create options'];
    }
    
  } catch (Exception $e) {
    fclose($handle);
    $mysqli->rollback();
    return ['success' => false, 'error' => $e->getMessage()];
  }
}

// Enhanced CSV Import: Menu with Options Integration
function enhancedMenuImport($csvData, $targetTable = 'menu') {
    try {
        $results = [
            'menus_imported' => 0,
            'options_imported' => 0,
            'choices_imported' => 0,
            'errors' => [],
            'success' => true
        ];
        
        foreach ($csvData as $rowIndex => $row) {
            $menuData = [];
            $optionData = [];
            $choiceData = [];
            
            // Parse menu fields
            $menuFields = ['name', 'category', 'price', 'ingredients', 'listingsNum', 'enable_order', 'delivery_type'];
            foreach ($menuFields as $field) {
                if (isset($row[$field]) && $row[$field] !== '') {
                    $menuData[$field] = $row[$field];
                }
            }
            
            // Create menu item first
            if (!empty($menuData)) {
                $menuData['createdDate'] = date('Y-m-d H:i:s');
                $menuData['updatedDate'] = date('Y-m-d H:i:s');
                
                $menuNum = mysql_insert($targetTable, $menuData, true);
                if ($menuNum) {
                    $results['menus_imported']++;
                } else {
                    $results['errors'][] = "Failed to import menu at row " . ($rowIndex + 1);
                    continue;
                }
            }
            
            // Parse and create option if available
            if (isset($menuNum) && !empty($row['option_name'])) {
                $optionData = [
                    'menu_id' => $menuNum,
                    'option_name' => $row['option_name'],
                    'option_type' => $row['option_type'] ?? 'required',
                    'option_category' => $row['option_category'] ?? '',
                    'price' => floatval($row['option_price'] ?? 0),
                    'is_required' => intval($row['is_required'] ?? 0),
                    'min_selection' => intval($row['min_selection'] ?? 1),
                    'max_selection' => intval($row['max_selection'] ?? 1),
                    'sort_order' => intval($row['option_sort_order'] ?? 0),
                    'is_active' => 1,
                    'createdDate' => date('Y-m-d H:i:s'),
                    'updatedDate' => date('Y-m-d H:i:s')
                ];
                
                $optionNum = mysql_insert('cmsb_menu_options', $optionData, true);
                if ($optionNum) {
                    $results['options_imported']++;
                } else {
                    $results['errors'][] = "Failed to import option for menu $menuNum at row " . ($rowIndex + 1);
                    continue;
                }
            }
            
            // Parse and create choice if available
            if (isset($optionNum) && !empty($row['choice_name'])) {
                $choiceData = [
                    'option_id' => $optionNum,
                    'choice_name' => $row['choice_name'],
                    'choice_description' => $row['choice_description'] ?? '',
                    'price' => floatval($row['choice_price'] ?? 0),
                    'sort_order' => intval($row['choice_sort_order'] ?? 0),
                    'is_available' => 1,
                    'createdDate' => date('Y-m-d H:i:s'),
                    'updatedDate' => date('Y-m-d H:i:s')
                ];
                
                $choiceNum = mysql_insert('cmsb_menu_option_choices', $choiceData, true);
                if ($choiceNum) {
                    $results['choices_imported']++;
                } else {
                    $results['errors'][] = "Failed to import choice for option $optionNum at row " . ($rowIndex + 1);
                }
            }
        }
        
        return $results;
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage(),
            'menus_imported' => 0,
            'options_imported' => 0,
            'choices_imported' => 0
        ];
    }
}

// eof

