<?php
session_start();
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$role = $_SESSION['role'];
$isAdmin = ($role == 'admin');

// শুধু admin ডিলেট করতে পারবে
if (!$isAdmin) {
    echo "<script>alert('Permission denied! Only admin can delete sales.'); window.history.back();</script>";
    exit();
}

if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo "<script>alert('No sale ID provided!'); window.location.href='sales_all_data.php';</script>";
    exit();
}

$sale_id = intval($_GET['id']);

// Transaction শুরু
$con->begin_transaction();

try {
    // ১. আগে sales_items থেকে quantity বের করে stock ফেরত দাও
    $items_result = $con->query("SELECT product_id, quantity FROM sales_items WHERE sales_id = $sale_id");
    if ($items_result) {
        while ($item = $items_result->fetch_assoc()) {
            $product_id = intval($item['product_id']);
            $qty = intval($item['quantity']);
            // Stock ফেরত দাও
            $con->query("UPDATE product SET Quantity = Quantity + $qty WHERE Product_id = $product_id");
        }
    }

    // ২. sales_items ডিলেট করো
    $con->query("DELETE FROM sales_items WHERE sales_id = $sale_id");

    // ৩. return_items থেকেও ডিলেট (যদি থাকে)
    $con->query("DELETE FROM return_items WHERE invoice_id = $sale_id");

    // ৪. sales ডিলেট করো
    $delete_result = $con->query("DELETE FROM sales WHERE id = $sale_id");

    if (!$delete_result) {
        throw new Exception("Failed to delete sale: " . $con->error);
    }

    $con->commit();
    echo "<script>alert('Sale #$sale_id deleted successfully and stock restored!'); window.location.href='sales_all_data.php';</script>";

} catch (Exception $e) {
    $con->rollback();
    echo "<script>alert('Error: " . addslashes($e->getMessage()) . "'); window.location.href='sales_all_data.php';</script>";
}

$con->close();
?>
