<?php
session_start();
require_once "../assets/db_connect.php";

try {
    $pdo->beginTransaction();

    $customer_id = $_POST['customer_id'] ?: null;
    $cart = $_POST['cart'];

    $stmt = $pdo->prepare("
        INSERT INTO sales (customer_id, user_id, total_amount)
        VALUES (?, ?, 0)
    ");
    $stmt->execute([$customer_id, $_SESSION['user']['id']]);
    $sale_id = $pdo->lastInsertId();

    $total = 0;

    foreach ($cart as $item) {

        $batch = $pdo->prepare("
            SELECT id FROM product_batches
            WHERE product_id = ?
            AND quantity >= ?
            ORDER BY expiry_date ASC
            LIMIT 1
        ");
        $batch->execute([$item['id'], $item['qty']]);
        $batch_id = $batch->fetchColumn();

        if (!$batch_id) {
            throw new Exception("Insufficient stock");
        }

        $subtotal = $item['qty'] * $item['price'];
        $total += $subtotal;

        $pdo->prepare("
            INSERT INTO sale_items
            (sale_id, product_id, batch_id, quantity, price)
            VALUES (?,?,?,?,?)
        ")->execute([
            $sale_id, $item['id'], $batch_id,
            $item['qty'], $item['price']
        ]);

        $pdo->prepare("
            INSERT INTO inventory_movements
            (product_id, batch_id, quantity, movement_type, reference)
            VALUES (?,?,?,?,?)
        ")->execute([
            $item['id'], $batch_id,
            -$item['qty'], 'SALE', $sale_id
        ]);
    }

    $pdo->prepare("UPDATE sales SET total_amount=? WHERE id=?")
        ->execute([$total, $sale_id]);

    $pdo->commit();

    echo json_encode(['success' => true, 'sale_id' => $sale_id]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
