<?php
include '../db_connect.php';

$customer_name = trim($_POST['customer_name']);
$product_id    = $_POST['product_id'];
$batch_no      = $_POST['batch_no'];
$qty           = $_POST['qty'];
$user_id       = 1; // from session

// 1. FIND OR CREATE CUSTOMER
$stmt = $pdo->prepare("SELECT id FROM customers WHERE name=?");
$stmt->execute([$customer_name]);
$cust = $stmt->fetch();

if(!$cust){
    $ins = $pdo->prepare("INSERT INTO customers(name) VALUES(?)");
    $ins->execute([$customer_name]);
    $customer_id = $pdo->lastInsertId();
} else {
    $customer_id = $cust['id'];
}

// 2. CREATE A NEW SALE
$invoice = "INV".time();

$stmt = $pdo->prepare("INSERT INTO sales(invoice_no, customer_id, created_by) VALUES(?,?,?)");
$stmt->execute([$invoice, $customer_id, $user_id]);

$sale_id = $pdo->lastInsertId();

// 3. INSERT INTO sale_items
$insert_item = $pdo->prepare("INSERT INTO sale_items(sale_id, product_id, batch_no, qty) VALUES(?,?,?,?)");
$insert_item->execute([$sale_id, $product_id, $batch_no, $qty]);

echo "<div class='alert alert-success'>Sale recorded successfully! Invoice: <b>$invoice</b></div>";
