<?php
// delete_stock_item.php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Set content type to JSON for ALL responses
header('Content-Type: application/json');

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Check if ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'ID stok tidak valid']);
    exit();
}

$stock_id = $_GET['id'];

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Check if the stock item exists and is available for deletion
    $check_query = "SELECT csi.*, cc.component_name, mc.code_color, cpc.id as panel_component_id, cpc.quantity, cpc.available_quantity 
                   FROM color_stock_items_semarang csi
                   JOIN master_color_panel_semarang mc ON csi.color_id = mc.id
                   JOIN color_components_semarang cc ON csi.component_id = cc.id 
                   JOIN color_panel_components_semarang cpc ON (csi.color_id = cpc.color_id AND csi.component_id = cpc.component_id)
                   WHERE csi.id = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("i", $stock_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        throw new Exception("Item stok tidak ditemukan");
    }
    
    $stock_data = $check_result->fetch_assoc();
    
    if ($stock_data['status'] !== 'Tersedia') {
        throw new Exception("Tidak dapat menghapus item stok karena statusnya bukan 'Tersedia'");
    }
    
    // Update color_panel_components_semarang to decrease quantity and available_quantity
    $new_quantity = $stock_data['quantity'] - 1;
    $new_available_quantity = $stock_data['available_quantity'] - 1;
    
    if ($new_quantity <= 0) {
        // If no more items of this component, delete the component from color_panel_components_semarang
        $delete_component_stmt = $conn->prepare("DELETE FROM color_panel_components_semarang WHERE id = ?");
        $delete_component_stmt->bind_param("i", $stock_data['panel_component_id']);
        $delete_component_stmt->execute();
    } else {
        // Update the quantities
        $update_component_stmt = $conn->prepare("
            UPDATE color_panel_components_semarang 
            SET quantity = ?, available_quantity = ? 
            WHERE id = ?
        ");
        $update_component_stmt->bind_param("ddi", $new_quantity, $new_available_quantity, $stock_data['panel_component_id']);
        $update_component_stmt->execute();
    }
    
    // Delete the stock item
    $delete_stock_stmt = $conn->prepare("DELETE FROM color_stock_items_semarang WHERE id = ?");
    $delete_stock_stmt->bind_param("i", $stock_id);
    $delete_stock_stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    // Log activity
    log_activity(
        $conn, 
        $it_id, 
        'it', 
        'Delete Stock Item', 
        "IT user deleted stock item: {$stock_data['kode_barang']} (Color: {$stock_data['code_color']}, Component: {$stock_data['component_name']})"
    );
    
    // Return success response
    echo json_encode([
        'success' => true, 
        'message' => "Item stok {$stock_data['kode_barang']} berhasil dihapus",
        'color_id' => $stock_data['color_id']
    ]);
    
} catch (Exception $e) {
    // Rollback transaction
    $conn->rollback();
    
    // Return error response
    echo json_encode([
        'success' => false, 
        'message' => "Gagal menghapus item stok: " . $e->getMessage()
    ]);
}

exit();
?>