<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $entry_id = intval($_POST['id']);

    include('../../includes/config.php');

    // Check if entry exists and get quantity/product/store
    $check = $conn->prepare("SELECT id, product_id, store_id, quantity FROM stock_entries WHERE id = ?");
    $check->bind_param("i", $entry_id);
    $check->execute();
    $result = $check->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Stock entry not found.']);
        exit;
    }

    $entry = $result->fetch_assoc();
    $check->close();

    // Optionally roll back inventory quantity
    $rollback = $conn->prepare("UPDATE inventory SET quantity = quantity - ? WHERE product_id = ? AND store_id = ?");
    $rollback->bind_param("iii", $entry['quantity'], $entry['product_id'], $entry['store_id']);
    $rollback->execute();
    $rollback->close();

    // Proceed to delete
    $delete = $conn->prepare("DELETE FROM stock_entries WHERE id = ?");
    $delete->bind_param("i", $entry_id);

    if ($delete->execute()) {
        echo json_encode(['success' => true, 'message' => '✅ Stock entry deleted successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => '❌ Error deleting stock entry.']);
    }

    $delete->close();
    $conn->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request.']);
}
?>
