<?php
// modules/sales/delete_sale.php
session_start();
header('Content-Type: application/json');
require_once '../assets/db_connect.php'; // <- adjust path

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

$sale_id = isset($_POST['id']) ? intval($_POST['id']) : 0;
if (!$sale_id) {
    echo json_encode(['status' => 'error', 'message' => 'Sale ID required']);
    exit;
}

try {
    $pdo->beginTransaction();

    // Fetch sale lines
    $stmt = $pdo->prepare("SELECT id, batch_id, qty FROM sale_lines WHERE sale_id = :sid");
    $stmt->execute([':sid' => $sale_id]);
    $lines = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Restore stock for each line
    $upd = $pdo->prepare("UPDATE product_batches SET qty = qty + ? WHERE id = ?");
    foreach ($lines as $ln) {
        $upd->execute([$ln['qty'], $ln['batch_id']]);
    }

    // Delete sale_lines
    $delLines = $pdo->prepare("DELETE FROM sale_lines WHERE sale_id = :sid");
    $delLines->execute([':sid' => $sale_id]);

    // Delete sale
    $delSale = $pdo->prepare("DELETE FROM sales WHERE id = :sid");
    $delSale->execute([':sid' => $sale_id]);

    $pdo->commit();

    echo json_encode(['status' => 'success', 'message' => 'Sale deleted and stock restored.']);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
