<?php
session_start();
require_once "../config/connection.php";

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

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

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

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

if (!isset($input['stock_id'])) {
    echo json_encode(['success' => false, 'message' => 'Stock ID tidak diberikan']);
    exit();
}

try {
    $stock_id = intval($input['stock_id']);
    
    if ($stock_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid stock ID']);
        exit();
    }
    
    // Get stock item info and check if it can be deleted
    $check_query = "
        SELECT 
            csi.id,
            csi.kode_barang,
            csi.status,
            csi.color_id,
            csi.component_id,
            mcp.code_color,
            cc.component_name
        FROM color_stock_items_semarang csi
        JOIN master_color_panel_semarang mcp ON csi.color_id = mcp.id
        JOIN color_components_semarang cc ON csi.component_id = cc.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) {
        echo json_encode(['success' => false, 'message' => 'Stock item tidak ditemukan']);
        exit();
    }
    
    $stock_data = $check_result->fetch_assoc();
    
    // Check if status allows deletion (only Tersedia can be deleted)
    if ($stock_data['status'] !== 'Tersedia') {
        echo json_encode(['success' => false, 'message' => 'Stock item dengan status "' . $stock_data['status'] . '" tidak dapat dihapus']);
        exit();
    }
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Delete the stock item
        $delete_query = "DELETE FROM color_stock_items_semarang WHERE id = ?";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bind_param('i', $stock_id);
        
        if (!$delete_stmt->execute()) {
            throw new Exception('Gagal menghapus stock item: ' . $conn->error);
        }
        
        // Update available quantity in color_panel_components_semarang
        $update_query = "
            UPDATE color_panel_components_semarang 
            SET available_quantity = available_quantity - 1 
            WHERE color_id = ? AND component_id = ? AND available_quantity > 0
        ";
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bind_param('ii', $stock_data['color_id'], $stock_data['component_id']);
        $update_stmt->execute();
        
        $conn->commit();
        
        // Log the activity
        $it_id = $_SESSION['user_id'];
        $details = "Deleted stock item '{$stock_data['kode_barang']}' for component '{$stock_data['component_name']}' in color '{$stock_data['code_color']}'";
        create_audit_log($conn, 'Delete Stock Item', $it_id, 'it', $details);
        
        echo json_encode([
            'success' => true,
            'message' => 'Stock item berhasil dihapus'
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>