<?php
session_start();
include("db_connect.php");
function generateReceiptID() {
    return 'RCPT-' . date('Ymd-His') . '-' . rand(1000, 9999);
}


$receipt_id = generateReceiptID(); // Same as above
$datetime = date('Y-m-d H:i:s');
$cashier = $_SESSION['username'];

$product_ids = $_POST['product_id'];
$quantities = $_POST['quantity'];

for ($i = 0; $i < count($product_ids); $i++) {
    $product_id = $product_ids[$i];
    $quantity = floatval($quantities[$i]);

    $query = "SELECT * FROM products WHERE id = $product_id";
    $result = mysqli_query($conn, $query);
    $product = mysqli_fetch_assoc($result);

    if ($product && $quantity <= $product['quantity']) {
        $buy_price = $product['buying_price'];
        $sell_price = $product['selling_price'];
        $total = $sell_price * $quantity;
        $profit = ($sell_price - $buy_price) * $quantity;

        // Insert sale with receipt_id
        $insert = "INSERT INTO sales (
            receipt_id, sale_datetime, cashier, product_id, quantity,
            buying_price, selling_price, total_sale, profit
        ) VALUES (
            '$receipt_id', '$datetime', '$cashier', $product_id, $quantity,
            $buy_price, $sell_price, $total, $profit
        )";
        mysqli_query($conn, $insert);

        // Update stock
        $new_stock = $product['quantity'] - $quantity;
        mysqli_query($conn, "UPDATE products SET quantity = $new_stock WHERE id = $product_id");
    }
}

// Redirect to receipt
header("Location: view_receipt.php?receipt_id=$receipt_id");
exit();
?>