<?php
/*
Plugin Name: CSV Import
Description: Import CSV files to create and/or update records in your existing sections.
Version: 1.14
Requires at least: 3.10
*/

### DON'T UPDATE ANYTHING BELOW THIS LINE

$GLOBALS['CSV_IMPORT_DEFAULTS'] = array(
  'USE_COLUMN_HEADERS'   => 1,             // 1 or 0
  'TARGET_TABLE'         => '',
  'USE_ID_FIELD'         => 0,             // 1 or 0
    'ID_FIELD'           => '',
    'UPDATE_DUPLICATES'  => 0,             // 1 or 0
    'REMOVE_ORPHANS'     => 0,             // 1 or 0
  'WIPE_DATABASE'        => 0,             // 1 or 0
    'SET_AUTO_INCREMENT' => 0,             // 1 or 0
    'NEW_AUTO_INCREMENT' => '1',           // starting record number
);

// Import Options Page: This list is checked for determining out default mappings of column names to target fields
$GLOBALS['CSV_IMPORT_DEFAULTS']['FIELD_MAP'] = array(
  'Product Code/SKU'    => 'sku',
  'Product Name'        => 'name',
  'Product Description' => 'description',
  'Price'               => 'retail_price',
//  '*'                   => 'specifications', // all other unmatched fields
);

// 
$GLOBALS['CSV_IMPORT_OPTIONS'] = array(
  'ENCODING'              => 'CP1252', // CP1252, ASCII, ISO-8859-1, UTF-8 - More: http://php.net/manual/en/mbstring.supported-encodings.php
  'CSV_DELIMITER'         => ',',
  'PREFIX_VALUES_FOR'     => array(''),               // values imported into these target fields will be prefixed with their column name
  'PREFIX_SEPARATOR'      => ': ',                    // this is added after the prefix
  'MULTI_VALUE_SEPARATOR' => "\n",                    // if multiple values are inserted into a single field they will be joined with this
);

// These user defined functions are called before passing data to mysql.  This is for stripping non-numeric data, etc.
$GLOBALS['CSV_IMPORT_OPTIONS']['FIELD_FILTERS'] = array(
//  'wholesale_price' => '_csvFilter_force_float',
//  'retail_price'    => '_csvFilter_force_float',
);
function _csvFilter_force_float($string) { return (float) preg_replace('/[^0-9\.]/', '', $string); }

// Uncomment this line to show the skipValidation checkbox
//$GLOBALS['CSV_IMPORT_ALLOW_SKIPVALIDATION'] = true;

// Plugin Functions: Load plugin functions when we're in the admin
if (defined('IS_CMS_ADMIN')) { // if in CMS Plugins Menu

  // load functions
  require_once("csvImport_functions.php");

  // set defaults
  // ini_set('auto_detect_line_endings', true); // client data is uploaded with mac line-endings // deprecated in PHP 8.1; line endings should still be detected (https://php.watch/versions/8.1/auto_detect_line_endings-ini-deprecated)
  if (@$_REQUEST['fileFormat'] == 'csvg') { $GLOBALS['CSV_IMPORT_OPTIONS']['CSV_DELIMITER'] = ';'; } // set delimiter for CSV parsing (done in csvImport_init and _csvImport_loadImportJob)

  // register callbacks
  addAction('admin_postlogin', '_csvImport_pluginSetup_createSchemas', null, -999); // lower priorities run first
  pluginAction_addHandlerAndLink('Import CSV File', 'csvImport_redirectToUploadForm', 'admins');
  pluginAction_addHandlerAndLink('Import Jobs >>',  'csvImport_redirectToImportJobs', 'admins');
  pluginAction_addHandlerAndLink('Simple Menu Import', 'csvImport_redirectToSimpleMenuImport', 'admins');
  addAction('admin_postlogin', 'csvImport_init', null, 10);

}

// Execute plugin actions
function csvImport_init() {
  global $CURRENT_USER;

  // SECURITY CHECK - Don't let user past this point if they don't have menu access
  $isCustomMenu = csvImport_isCustomMenu();
  if (!$CURRENT_USER['isAdmin'] && !$isCustomMenu) { return; } // Let regular menu security show error message

  // Custom Import Menu Defaults
  if ($isCustomMenu) {  // Custom Import Menu - Defaults
    $_REQUEST['_pluginAction'] = coalesce(@$_REQUEST['_pluginAction'], 'csvImport_uploadForm'); // default action

    $parentJobNum = csvImport_isCustomMenu();
    $parentJob    = mysql_get('_csv_import_jobs', $parentJobNum);
    if (!$parentJob) { die("The source job (#$parentJobNum) for this import menu has been removed.  Try removing this menu and creating a new one."); }
    
    // override form input
    $copyKeys = array('fileFormat','hasColumnHeaders','targetTable',
    //                  //'columnNamesMap',
    //                  //'columnCount','recordCount',
    //                  //'useIdField','idField','updateDuplicates','removeOrphans','wipeDatabase','setAutoIncrement','newAutoIncrement','mapFields'
                      );
    foreach ($copyKeys as $key) {
      $_REQUEST[$key] = $parentJob[$key]; // force user to uses these values
}

  }
  
  // dispatch
  if ($CURRENT_USER['isAdmin'] || $isCustomMenu) {
    $_pluginAction = @$_REQUEST['_pluginAction'];
    $isAdmin       = $CURRENT_USER['isAdmin'];
    if ($_pluginAction == 'csvImport_uploadForm')              { csvImport_uploadForm(); }
    if ($_pluginAction == 'csvImport_uploadForm_uploadIframe') { csvImport_uploadForm_uploadIframe(); }
    if ($_pluginAction == 'csvImport_previewData_ajax')        { csvImport_previewData_ajax(); }
    if ($_pluginAction == 'csvImport_analyseForm')             { csvImport_analyseForm(); }
    if ($_pluginAction == 'csvImport_analyseForm_ajax')        { csvImport_analyseForm_ajax(); }
    if ($_pluginAction == 'csvImport_optionsForm' && $isAdmin) { csvImport_optionsForm(); } // Don't let custom import menus set options
    if ($_pluginAction == 'csvImport_validateForm')            { csvImport_validateForm(); }
    if ($_pluginAction == 'csvImport_importForm')              { csvImport_importForm(); }
    if ($_pluginAction == 'csvImport_importForm_ajax')         { csvImport_importForm_ajax(); }
    if ($_pluginAction == 'csvImport_simpleMenuImport')        { csvImport_simpleMenuImport(); }
  }
  }
  
// returns source job # if an authorized user is on a custom import menu, or false otherwise
function csvImport_isCustomMenu() {
  static $result = null;
  
  if (is_null($result)) {
    $result              = false;
    $onCustomMenu        = preg_match("/^_csv_import_menu_(\d+)$/", $_REQUEST['menu']??'', $matches);
    $sourceJobNum        = @$matches[1];
    $hasCustomMenuAccess = $onCustomMenu && (userSectionAccess(@$_REQUEST['menu']) >= 6);
    if ($onCustomMenu && $hasCustomMenuAccess) {
      $result = $sourceJobNum;
      }
      else {
      $result = false;
    }
  }

  return $result;
}



//
function csvImport_redirectToImportJobs() {
  redirectBrowserToURL('?menu=_csv_import_jobs');
  }

  //
function csvImport_redirectToUploadForm() {
  redirectBrowserToURL('?_pluginAction=csvImport_uploadForm');
}

//
function csvImport_redirectToSimpleMenuImport() {
  redirectBrowserToURL('?_pluginAction=csvImport_simpleMenuImport');
}

//
function csvImport_simpleMenuImport() {
  // Check if user has access
  global $CURRENT_USER;
  if (empty($CURRENT_USER['isAdmin'])) {
    die("Access denied. Admin privileges required.");
  }
  
  // Include the simple menu import functionality
  require_once(__DIR__ . '/simple_menu_import.php');
  
  // Call the simple menu import function
  if (function_exists('csvImp_simpleMenuImport')) {
    csvImp_simpleMenuImport();
  } else {
    echo "<div style='padding:20px;'>";
    echo "<h2>Simple Menu Import</h2>";
    echo "<p>Simple menu import functionality not found. Please check the plugin installation.</p>";
    echo "<a href='?_pluginAction=csvImport_uploadForm' style='background:#007cba;color:#fff;padding:10px 20px;text-decoration:none;border-radius:4px;'>Back to CSV Import</a>";
    echo "</div>";
  }
}

// eof