<?php // actions/sale_create.php
require_once('../config/db.php');

$ProductID = trim($_POST['ProductID'] ?? '');
$Quantity = (int)($_POST['Quantity'] ?? 0);
$PricePerUnit = (float)($_POST['PricePerUnit'] ?? 0.0);
$TotalAmount = (float)($_POST['TotalAmount'] ?? 0.0);

if ($ProductID && $Quantity > 0 && $PricePerUnit > 0) {
  // Check stock
  $stmt = $pdo->prepare("SELECT StockQuantity FROM products WHERE ProductID=?");
  $stmt->execute([$ProductID]);
  $prod = $stmt->fetch();
  if (!$prod) {
    header('Location: ../sales.php'); exit;
  }
  if ($prod['StockQuantity'] < $Quantity) {
    // Not enough stock; you can handle with error flash (simplified redirect)
    header('Location: ../sales.php'); exit;
  }

  // Insert sale
  $insert = $pdo->prepare("INSERT INTO sales (ProductID, Quantity, PricePerUnit, TotalAmount)
                           VALUES (?, ?, ?, ?)");
  $insert->execute([$ProductID, $Quantity, $PricePerUnit, $TotalAmount]);

  // Decrement stock
  $update = $pdo->prepare("UPDATE products SET StockQuantity = StockQuantity - ? WHERE ProductID=?");
  $update->execute([$Quantity, $ProductID]);
}

header('Location: ../sales.php');

