<?php
include "db.php";

if(!isset($_GET['id'])){ echo "<p>No ID provided.</p>"; exit; }
$id = intval($_GET['id']);

// 1) Pehle ye entry fetch karte hain taake pata chale ye "in" thi ya "out",
//    aur kitni quantity thi — taake stock ko reverse kar sakein.
$stmt = $conn->prepare("SELECT product_id, type, quantity FROM inventory WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$entry_result = $stmt->get_result();
$entry = $entry_result->fetch_assoc();
$stmt->close();

if(!$entry){
    echo "<p style='color:red;'>Error: Entry not found.</p>";
    exit;
}

$conn->begin_transaction();

try {
    // 2) Stock ko reverse karo:
    //    Agar entry "in" thi (stock add hua tha) -> delete karte waqt stock se wapas minus
    //    Agar entry "out" thi (stock nikala gaya tha) -> delete karte waqt stock mein wapas add
    if ($entry['type'] === 'in') {
        $reverse = $conn->prepare("UPDATE products SET stock_quantity = stock_quantity - ? WHERE product_id = ?");
    } else {
        $reverse = $conn->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE product_id = ?");
    }
    $reverse->bind_param("ii", $entry['quantity'], $entry['product_id']);
    $reverse->execute();
    $reverse->close();

    // 3) Ab inventory se entry delete karo
    $delete = $conn->prepare("DELETE FROM inventory WHERE id = ?");
    $delete->bind_param("i", $id);
    $delete->execute();
    $delete->close();

    $conn->commit();

    echo "<p style='color:green;'>Item deleted successfully! Stock has been adjusted accordingly.</p>";
    echo "<script>setTimeout(function(){ window.location.href='inventory_view.php'; }, 1500);</script>";

} catch (Exception $e) {
    $conn->rollback();
    echo "<p style='color:red;'>Error: ".htmlspecialchars($e->getMessage())."</p>";
}
?>