<?php
session_start();
include_once('../../includes/config.php');

header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if POST data exists
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !isset($data['itemId'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request data']);
    exit();
}

$itemId = (int)$data['itemId'];

if ($itemId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid item ID']);
    exit();
}

// Get item details before deletion
$selectQuery = "SELECT ItemCode, ItemName, ItemImage FROM tblitems WHERE ID = ?";
$stmt = mysqli_prepare($con, $selectQuery);

if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($con)]);
    exit();
}

mysqli_stmt_bind_param($stmt, 'i', $itemId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if ($row = mysqli_fetch_assoc($result)) {
    $itemImage = $row['ItemImage'];
    $itemName = $row['ItemName'];
    
    mysqli_stmt_close($stmt);
    
    // Start transaction
    mysqli_begin_transaction($con);
    
    try {
        // Delete variants first (if any)
        $deleteVariantsQuery = "DELETE FROM tblitemvariants WHERE ItemID = ?";
        $variantStmt = mysqli_prepare($con, $deleteVariantsQuery);
        mysqli_stmt_bind_param($variantStmt, 'i', $itemId);
        mysqli_stmt_execute($variantStmt);
        mysqli_stmt_close($variantStmt);
        
        // Delete the item
        $deleteItemQuery = "DELETE FROM tblitems WHERE ID = ?";
        $deleteStmt = mysqli_prepare($con, $deleteItemQuery);
        mysqli_stmt_bind_param($deleteStmt, 'i', $itemId);
        $deleteResult = mysqli_stmt_execute($deleteStmt);
        mysqli_stmt_close($deleteStmt);
        
        if ($deleteResult) {
            // Delete item image if exists
            if (!empty($itemImage)) {
                $imagePath = '../../uploads/items/' . $itemImage;
                if (file_exists($imagePath)) {
                    @unlink($imagePath);
                }
            }
            
            // Commit transaction
            mysqli_commit($con);
            
            echo json_encode([
                'success' => true,
                'message' => 'Item deleted successfully',
                'itemName' => $itemName
            ]);
        } else {
            // Rollback on failure
            mysqli_rollback($con);
            echo json_encode(['success' => false, 'message' => 'Failed to delete item']);
        }
        
    } catch (Exception $e) {
        // Rollback on error
        mysqli_rollback($con);
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    
} else {
    echo json_encode(['success' => false, 'message' => 'Item not found']);
    mysqli_stmt_close($stmt);
}

mysqli_close($con);
?>
