<!DOCTYPE html>

<?php
function getVendors() {
  $db = mysqli_connect("localhost", "root", "", "shangrilaperfumes");

  if (!$db) {
      return array("Error: Unable to connect to the database");
  }

  $query = "SELECT id, VendorName FROM vendor";
  $result = mysqli_query($db, $query);

  if ($result) {
      $vendors = array();
      while ($row = mysqli_fetch_assoc($result)) {
          $vendors[$row['id']] = $row['VendorName'];
      }
      return $vendors;
  } else {
      return array("Error: Unable to fetch vendors");
  }

  mysqli_close($db);
}

// Function to display the options for vendors in the select list
function displayVendorOptions() {
  $vendors = getVendors();

  if (is_array($vendors)) {
      foreach ($vendors as $id => $vendorName) {
          echo "<option value=\"$id\">$vendorName</option>";
      }
  } else {
      echo "<option value=\"\">Error fetching vendors</option>";
  }
}
?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.4/css/bulma.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js"></script>
    <link rel="stylesheet" href="styles.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="bootstrap.min.js"></script>

    <title>Document</title>

<?php
$file = @$_POST['file'] ?: @$_GET['file'];

$file ="".$file;

$mataara = [];
$file1 = fopen($file, 'r');
while (($line = fgetcsv($file1)) !== FALSE) {
  //$line is an array of the csv elements
  $mataara = $line;
  break;
}
fclose($file1);

$array = $fields = array(); $i = 0;
$handle = fopen($file, "r");
if ($handle) {
    while (($row = fgetcsv($handle, 4096)) !== false) {
        if (empty($fields)) {
            $fields = $row;
            continue;
        }
        foreach ($row as $k=>$value) {
            $array[$i][$fields[$k]] = $value;
        }
        $i++;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
$objects = [];
$objects[] = (object) [
  'data' => $array,
  'errors' => "",
  'meta' => ['fields'=>$mataara] 
];


// $printjson = "<script>var dataarray = '" . str_replace("'", '', json_encode($objects)) . "';var reportarray = JSON.parse(dataarray)[0];console.log(reportarray);</script>";
$printjson = "<script>var dataarray = " . json_encode($objects, JSON_UNESCAPED_SLASHES) . ";var reportarray = dataarray[0];console.log(reportarray);</script>";

echo $printjson;
?>
<style>
    .loader {
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            display: none; /* Initially hide the loader */
            position: fixed;
            top: 50%;
            left: 50%;
            margin-top: -25px;
            margin-left: -25px;
            z-index: 9999;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }


</style>
</head>
<body>
<section class="section content" style="margin-right:180px">
         <div class="container box" id="input">
          <!-- <h2>File Input</h2> -->
          <div class="file" style="display:none">
            <form method="POST" enctype="multipart/form-data" id="uploadForm">
              <label class="file-label">
                <input class="file-input" value="<?php echo $file; ?>" accept=".csv" type="file" name="resume" id="fileInput">
                <span class="file-cta">
                  <span class="file-icon">
                    <i class="fas fa-upload"></i>
                  </span>
                  <span class="file-label">
                    <!-- Choose a file… -->
                  </span>
                </span>
              </label>
            </form>
          </div> 
        </div>
        <label for="vendor">Select Vendor:</label>
        <select name="vendor" id="vendor">
    <option value="">Select a vendor</option>
    <?php displayVendorOptions(); ?>
</select>
        <div class="container box content">
          <h2>Headers</h2>
          <div id="controls">
          </div>
        </div>
        <div id="csvcont"></div>
        <button type="button" id="importButton" style="width: 150px; margin: 0 auto; display: block;">Import</button>
            <div class="loader" id="loader"></div>
           
           
        </div>
        <div class="container box content">
          <h2>Output</h2>
          <div id="output">
          </div>
        </div>
        <!-- <div class="container box content">
          <h2>Result</h2>
          <pre id="csvout"></pre>
          <div id="csvcont"></div>
          <button class="button is-primary" id="uploadButton">Upload</button>
        </div> --> 
      </section>
     
</body>
<script>

$(document).ready(function() {
            $('#importButton').click(function() {
                var selectedVendor = $('#vendor').val();

                if (selectedVendor === '') {
                    alert('Please select a vendor before importing data.');
                    return;
                }

                

                var fieldMapping = {};
                $('#controls select').each(function() {
                    var inputField = $(this).closest('tr').find('td:first').text().trim();
                    var mappedField = $(this).val();
                    fieldMapping[inputField] = mappedField;
                });

                var updatedData = reportarray.data.map(function(row) {
                    var updatedRow = {};
                    for (var inputField in fieldMapping) {
                        var mappedField = fieldMapping[inputField];
                        updatedRow[mappedField] = row[inputField];
                    }
                    return updatedRow;
                });

                $.ajax({
    url: 'import_data.php',
    type: 'POST',
    data: {
        data: JSON.stringify(updatedData),
        vendor: selectedVendor
    },
    beforeSend: function() {
        $('#loader').show();
    },
    success: function(response) {
        alert(response);
        window.location.href = 'text.php';
    },
    error: function(xhr, status, error) {
        console.error(xhr.responseText);
    },
    complete: function() {
        
    }
});

            });
        });

        document.addEventListener("DOMContentLoaded", function() {
            csvload(reportarray);
        });


  const fileInput = document.getElementById('fileInput');
  const controls  = document.getElementById('controls');
  const out       = document.getElementById('output');
  const csvout    = document.getElementById('csvout');
  const csvcont   = document.getElementById('csvcont');

  const expectedFieldsSpec = {

    'UPC': {
        synonyms: ['UPC']
    },
    'SKU': {
        synonyms: ['SKU']
    },
    'Product': {
        synonyms: ['Product']
    },
    'Price': {
        synonyms: ['Price']
    },
    'Brand': {
        synonyms: ['Brand']
    },
    'Stock': {
        synonyms: ['Stock']
    }
};

  const expectedFields = Object.keys(expectedFieldsSpec);

  const desc = document.createElement('div');
  desc.innerHTML = `CSV file with the following headers: <code>${expectedFields.join(", ")}</code>`;

  document.getElementById('input').appendChild(desc);

  const sameCheck = (a, b) => {
    return a === b ||
    a.toLowerCase().trim() === b.toLowerCase().trim() ||
    a.replace(/[^\w]+/g,'').toLowerCase().trim() === b.replace(/[^\w]+/g, '').toLowerCase().trim();
  };

  const doOutput = (data) => {
    csvcont.innerHTML = '';
    console.log(data);
    const mapping = {};
    controls.querySelectorAll('select').forEach(a => {
      if (a.value) {
        mapping[a.dataset.field] = a.value;
      }
    });
    const newOut = [];
    for (let row of data) {
      let newRow = {};
      let allNull = true;
      for (let [key, val] of Object.entries(mapping)) {
        allNull = allNull && (row[key] === null || typeof row[key] === 'undefined');
        newRow[val] = row[key];
      }
      if (!allNull) {
        newOut.push(newRow);
      }
    }
    const headers = Object.values(mapping);
    out.innerHTML = '';
    const table = document.createElement('table');
    const thead = document.createElement('thead');
    const theadtr = document.createElement('tr');
    thead.appendChild(theadtr);
    table.appendChild(thead);
    headers.forEach(a => {
      console.log(a);
      const th = document.createElement('th');
      th.innerText = a;
      theadtr.appendChild(th);
    });
    table.classList.add('table');
    const tbody = document.createElement('tbody');
    newOut.forEach(a => {
      const trow = document.createElement('tr');
      for (const header of headers) {
        const td = document.createElement('td');
        td.innerText = a[header];
        trow.appendChild(td);
      }
      tbody.appendChild(trow);
    });
    table.appendChild(tbody);
    out.appendChild(table);

    const csvContent = Papa.unparse(newOut);
    //csvout.innerHTML = csvContent;

    const button = document.createElement('button');
    button.classList.add('button');
    button.classList.add('is-primary');
    button.innerHTML = 'Download';
    const filename = 'remapped_csv.csv';
    button.addEventListener('click', () => {
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
      } else {
        const link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
          // Browsers that support HTML5 download attribute
          const url = URL.createObjectURL(blob);
          link.setAttribute("href", url);
          link.setAttribute("download", filename);
          link.style.visibility = 'hidden';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      }
    });
    csvcont.appendChild(button);
  };



  function csvload(results){
    console.log(results)
        if (results.data && results.meta && results.meta.fields) {
          const outTable = document.createElement('table');
          outTable.classList.add('table');
          outTable.innerHTML = `<tr><th>Input Field</th><th>Mapped Field</th></tr>`;
          for (const field of results.meta.fields) {
            const row = document.createElement('tr');
            const cellinput  = document.createElement('td');
            const celloutput = document.createElement('td');
            const select     = document.createElement('select');
            row.appendChild(cellinput);
            row.appendChild(celloutput);

            cellinput.innerHTML = field;

            select.dataset.field = field;
            select.appendChild(document.createElement('option'));
            select.addEventListener('change', () => {
              doOutput(results.data)
            });

            expectedFields.forEach(a => {
              
                const opt = document.createElement('option');
                opt.value = a;
                opt.innerText = a;
                const synList = expectedFieldsSpec[a].synonyms ?? [];
                const isSame = sameCheck(a, field);
                const isSynonym = synList.reduce((carr, a) => carr || sameCheck(a, field), false);
             
                  if (isSame || isSynonym) {
                    opt.selected = true;
                  }
                  
                  select.appendChild(opt);
                

            });

            celloutput.appendChild(select);

            outTable.append(row);
          }
          
          controls.innerHTML = '';
          controls.appendChild(outTable);
          doOutput(results.data);
        }
  }

  fileInput.addEventListener('change', (e) => {
    Papa.parse(fileInput.files[0], {
      complete: (results) => {
      
      },
      header: true,
      dynamicTyping: true
    });
  });


</script>
</html>

