<?php
$page_title = 'Outgoing Etalase';
require_once('includes/sql.php');
page_require_level(3);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $transactionDate = $_POST['transactionDate'];

  foreach ($_POST['data'] as $data) {
    $productName = $db->escape($data['productName']);
    $quantity = (int)$data['quantity'];
    $remark = $db->escape($data['remark']);
    $loc = $db->escape($data['loc']);

    // Check if the product exists in the database
    $product = find_product_by_part_number($productName);

    if ($product) {
      // Insert record penjualan ke database
      $partNumber = $product['part_number'];
      $categorieId = $product['categorie_id'];
      $sql = "INSERT INTO sales (product_id, part_number, qty, date, categorie_id, remark, loc) VALUES ('{$product['id']}', '{$partNumber}', '{$quantity}', '{$transactionDate}', '{$categorieId}', '{$remark}', '{$loc}')";

      if ($db->query($sql)) {
        // Update kuantitas produk berdasarkan part_number
        insertStockHistory($partNumber, 'Sidoarjo Etalase',  'OUT', $quantity, $remark, 1, 'online_products', 'SALE');
        if (update_product_qty_online_products($quantity, $partNumber, true)) {
          $session->msg('s', 'Outgoing data added successfully!');
        } else {
          $session->msg('d', 'Failed to update product quantity.');
        }
      } else {
        $session->msg('d', 'Failed to add sale.');
      }
    } else {
      $session->msg('d', 'Product not found.');
    }
  }

  redirect('add_sale_online_products.php', false);
}

include_once('layouts/header.php');
echo display_msg($msg);
?>

<div class="row">
  <div class="col-md-12">
    <h2>Add Outgoing Etalase</h2>
    <form id="goods-form" method="post">
      <div id="input-container">
        <div class="input-row">
          <div class="form-group">
            <label for="product">Product:</label>
            <input type="text" class="form-control product-search" name="data[0][productName]"
              placeholder="Search for a product">
            <div class="suggestions"></div>
          </div>
          <div class="form-group">
            <label for="quantity">Quantity:</label>
            <input class="quantity form-control" type="number" name="data[0][quantity]" placeholder="Quantity">
          </div>
          <div class="form-group">
            <label for="remark">Remark:</label>
            <input type="text" class="form-control" name="data[0][remark]" placeholder="Enter remark">
          </div>
          <div class="form-group">
            <label for="loc">Location:</label>
            <input type="text" class="form-control" name="data[0][loc]" placeholder="Enter location">
          </div>
        </div>
      </div>
      <div class="form-group">
        <label for="transaction-date">Transaction Date:</label>
        <input type="date" id="transaction-date" name="transactionDate">
      </div>
      <button type="button" class="btn btn-success" id="add-input">Add Input</button>
      <button type="submit" class="btn btn-primary">Add Outgoing Goods</button>
      <div class="form-group">
        <label for="csv-file">Import CSV:</label>
        <input type="file" class="form-control-file" id="csv-file" accept=".csv">
      </div>
    </form>
  </div>
</div>

<style>
.input-row {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 1rem;
}

.input-row .form-group {
  flex: 1;
  min-width: 200px;
}

.suggestions {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ccc;
  background-color: white;
  z-index: 1;
}

.suggestion {
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.suggestion:hover {
  background-color: #f5f5f5;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const inputContainer = document.getElementById('input-container');
  const addButton = document.getElementById('add-input');
  const transactionDateInput = document.getElementById('transaction-date');

  let inputCount = 1;

  addButton.addEventListener('click', function() {
    const inputRow = document.createElement('div');
    inputRow.classList.add('input-row');

    const formGroups = ['productName', 'quantity', 'remark', 'loc'].map(fieldName => {
      const formGroup = document.createElement('div');
      formGroup.classList.add('form-group');

      const label = document.createElement('label');
      label.setAttribute('for', fieldName);
      label.textContent = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);

      const input = document.createElement('input');
      input.classList.add('form-control');
      input.setAttribute('type', fieldName === 'quantity' ? 'number' : 'text');
      input.setAttribute('name', `data[${inputCount}][${fieldName}]`);
      input.setAttribute('placeholder', `Enter ${fieldName}`);

      formGroup.appendChild(label);
      formGroup.appendChild(input);

      return formGroup;
    });

    inputRow.append(...formGroups);

    inputContainer.appendChild(inputRow);
    inputCount++;
  });

  const productSearchInputs = document.querySelectorAll('.product-search');
  productSearchInputs.forEach(input => {
    const suggestionsContainer = input.nextElementSibling;

    input.addEventListener('input', function() {
      const query = input.value;

      if (query.length >= 2) {
        fetch(`autocomplete.php?query=${encodeURIComponent(query)}`)
          .then(response => response.json())
          .then(products => {
            suggestionsContainer.innerHTML = '';

            if (products.length > 0) {
              products.forEach(product => {
                const suggestionItem = document.createElement('div');
                suggestionItem.classList.add('suggestion');
                suggestionItem.textContent = `${product.part_number} - ${product.name}`;
                suggestionItem.addEventListener('click', function() {
                  input.value = product.part_number;
                  suggestionsContainer.innerHTML = '';
                });
                suggestionsContainer.appendChild(suggestionItem);
              });
            } else {
              suggestionsContainer.innerHTML = '<div class="suggestion">No suggestions</div>';
            }
          })
          .catch(error => console.error(error));
      } else {
        suggestionsContainer.innerHTML = '';
      }
    });
  });

  // CSV import functionality
  const csvFileInput = document.getElementById('csv-file');

  csvFileInput.addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();

    reader.onload = function(e) {
      const contents = e.target.result;
      processData(contents);
    };

    reader.readAsText(file);
  });

  function processData(csvData) {
    const rows = csvData.split('\n');
    const data = [];

    rows.forEach(row => {
      const columns = row.split(';');
      const [partNumber, quantity, remark, loc] = columns.map(column => column.trim());
      if (partNumber && quantity && remark && loc) {
        data.push({
          productName: partNumber,
          quantity,
          remark,
          loc
        });
      }
    });

    if (data.length > 0) {
      appendDataToForm(data);
    } else {
      alert('No valid data found in the CSV file.');
    }
  }

  function appendDataToForm(data) {
    const inputContainer = document.getElementById('input-container');
    inputContainer.innerHTML = ''; // Clear existing inputs

    data.forEach((item, index) => {
      const inputRow = document.createElement('div');
      inputRow.classList.add('input-row');

      const formGroups = ['productName', 'quantity', 'remark', 'loc'].map(fieldName => {
        const formGroup = document.createElement('div');
        formGroup.classList.add('form-group');

        const label = document.createElement('label');
        label.setAttribute('for', fieldName);
        label.textContent = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);

        const input = document.createElement('input');
        input.classList.add('form-control');
        input.setAttribute('type', fieldName === 'quantity' ? 'number' : 'text');
        input.setAttribute('name', `data[${index}][${fieldName}]`);
        input.setAttribute('placeholder', `Enter ${fieldName}`);
        input.value = item[fieldName];

        formGroup.appendChild(label);
        formGroup.appendChild(input);

        return formGroup;
      });

      inputRow.append(...formGroups);

      inputContainer.appendChild(inputRow);
    });
  }
});
</script>

<?php require_once('layouts/footer.php'); ?>

<?php


function add_sale_online_products($productName, $quantity, $remark, $loc, $transactionDate)
{
  global $db, $session;

  // Check if the product exists in the database
  $product = find_product_by_part_number($productName);

  if ($product) {
    // Insert the sale record into the database with part_number and categorie_id
    $partNumber = $product['part_number'];
    $categorieId = $product['categorie_id'];
    $sql = "INSERT INTO sales (product_id, part_number, qty, date, categorie_id, remark, loc) VALUES ('{$product['id']}', '{$partNumber}', '{$quantity}', '{$transactionDate}', '{$categorieId}', '{$remark}', '{$loc}')";

    if ($db->query($sql)) {
      // Update the product quantity in stock
      if (update_product_qty_online_products($quantity, $product['id'], true)) {
        $session->msg('s', 'Outgoing data added successfully!');
        return true;
      } else {
        $session->msg('d', 'Failed to update product quantity.');
      }
    } else {
      $session->msg('d', 'Failed to add sale.');
    }
  } else {
    // Product not found
    $session->msg('d', 'Product not found.');
  }

  return false;
}
?>