<?php
// Include your database connection and necessary functions
require_once('includes/load.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $salesData = json_decode($_POST['salesData'], true);

  foreach ($salesData as $data) {
    $partNumber = $db->escape($data['partNumber']);
    $quantity = (int)$data['quantity'];

    // Check if the part number exists in the database
    $product = find_product_by_part_number($partNumber);

    if ($product) {
      // Calculate the total sale amount
      $s_total = $product['sale_price'] * $quantity;
      $s_date = make_date();

      // Insert the sale record into the database
      $sql = "INSERT INTO sales (product_id, qty, price, date) VALUES ('{$product['id']}', '{$quantity}', '{$s_total}', '{$s_date}')";

      if ($db->query($sql)) {
        // Update the product quantity in stock
        update_product_qty(-$quantity, $product['id']);
      } else {
        echo "Failed to add sale for Part Number: {$partNumber}<br>";
      }
    } else {
      echo "Part Number not found: {$partNumber}<br>";
    }
  }

  echo "Sales data processed successfully!";
}
?>
