<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: /beauty_pos/login.php");
    exit;
}

include_once "../config/database.php";

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {

    header("Location: /beauty_pos/inventory/index.php?error=Invalid Inventory Record.");
    exit;

}

$id = (int)$_GET['id'];

$getInventory = mysqli_query($conn,"
SELECT *
FROM inventory
WHERE id='$id'
");

if(mysqli_num_rows($getInventory)==0){

    header("Location: /beauty_pos/inventory/index.php?error=Inventory record not found.");
    exit;

}

$inventory=mysqli_fetch_assoc($getInventory);

mysqli_begin_transaction($conn);

try{

    $delete=mysqli_query($conn,"
    DELETE FROM inventory
    WHERE id='$id'
    ");

    if(!$delete){
        throw new Exception();
    }

    $update=mysqli_query($conn,"
    UPDATE products
    SET stock='0'
    WHERE id='".$inventory['product_id']."'
    ");

    if(!$update){
        throw new Exception();
    }

    mysqli_commit($conn);

    header("Location: /beauty_pos/inventory/index.php?success=Inventory deleted successfully.");
    exit;

}catch(Exception $e){

    mysqli_rollback($conn);

    header("Location: /beauty_pos/inventory/index.php?error=Unable to delete inventory.");
    exit;

}
?>