<?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['color_id']) || !isset($input['component_id'])) {
    echo json_encode(['success' => false, 'message' => 'Color ID atau Component ID tidak diberikan']);
    exit();
}

try {
    $color_id = intval($input['color_id']);
    $component_id = intval($input['component_id']);
    
    if ($color_id <= 0 || $component_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid color ID atau component ID']);
        exit();
    }
    
    // Get component info
    $info_query = "
        SELECT 
            mcp.code_color,
            cc.component_name
        FROM master_color_panel mcp, color_components cc
        WHERE mcp.id = ? AND cc.id = ?
    ";
    
    $info_stmt = $conn->prepare($info_query);
    $info_stmt->bind_param('ii', $color_id, $component_id);
    $info_stmt->execute();
    $info_result = $info_stmt->get_result();
    
    if ($info_result->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Color panel atau component tidak ditemukan']);
        exit();
    }
    
    $info_data = $info_result->fetch_assoc();
    
    // Check if component exists in color panel
    $panel_comp_check = $conn->prepare("SELECT id FROM color_panel_components WHERE color_id = ? AND component_id = ?");
    $panel_comp_check->bind_param('ii', $color_id, $component_id);
    $panel_comp_check->execute();
    $panel_comp_result = $panel_comp_check->get_result();
    
    if ($panel_comp_result->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Component tidak terdaftar untuk color panel ini']);
        exit();
    }
    
    // Check if there are any borrowed items
    $borrowed_check = $conn->prepare("
        SELECT COUNT(*) as borrowed_count 
        FROM color_stock_items 
        WHERE color_id = ? AND component_id = ? AND status = 'Dipinjam'
    ");
    $borrowed_check->bind_param('ii', $color_id, $component_id);
    $borrowed_check->execute();
    $borrowed_result = $borrowed_check->get_result();
    $borrowed_data = $borrowed_result->fetch_assoc();
    
    if ($borrowed_data['borrowed_count'] > 0) {
        echo json_encode(['success' => false, 'message' => 'Tidak dapat menghapus component karena masih ada ' . $borrowed_data['borrowed_count'] . ' item yang sedang dipinjam']);
        exit();
    }
    
    // Get count of stock items that will be deleted
    $count_query = "SELECT COUNT(*) as total FROM color_stock_items WHERE color_id = ? AND component_id = ?";
    $count_stmt = $conn->prepare($count_query);
    $count_stmt->bind_param('ii', $color_id, $component_id);
    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $count_data = $count_result->fetch_assoc();
    $total_items = $count_data['total'];
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Delete all stock items for this component
        $delete_stock_query = "DELETE FROM color_stock_items WHERE color_id = ? AND component_id = ?";
        $delete_stock_stmt = $conn->prepare($delete_stock_query);
        $delete_stock_stmt->bind_param('ii', $color_id, $component_id);
        
        if (!$delete_stock_stmt->execute()) {
            throw new Exception('Gagal menghapus stock items: ' . $conn->error);
        }
        
        // Delete the component from color_panel_components
        $delete_comp_query = "DELETE FROM color_panel_components WHERE color_id = ? AND component_id = ?";
        $delete_comp_stmt = $conn->prepare($delete_comp_query);
        $delete_comp_stmt->bind_param('ii', $color_id, $component_id);
        
        if (!$delete_comp_stmt->execute()) {
            throw new Exception('Gagal menghapus component: ' . $conn->error);
        }
        
        $conn->commit();
        
        // Log the activity
        $it_id = $_SESSION['user_id'];
        $details = "Deleted component '{$info_data['component_name']}' and {$total_items} stock items from color '{$info_data['code_color']}'";
        create_audit_log($conn, 'Delete Component', $it_id, 'it', $details);
        
        echo json_encode([
            'success' => true,
            'message' => "Component '{$info_data['component_name']}' berhasil dihapus beserta {$total_items} stock items"
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>