<?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();
}

try {
    $color_id = intval($_POST['color_id']);
    $component_id = intval($_POST['component_id']);
    $quantity = intval($_POST['quantity']);
    
    // Validate input
    if ($color_id <= 0 || $component_id <= 0 || $quantity <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid input data']);
        exit();
    }
    
    // Check if color panel exists
    $color_check = $conn->prepare("SELECT code_color FROM master_color_panel WHERE id = ?");
    $color_check->bind_param('i', $color_id);
    $color_check->execute();
    $color_result = $color_check->get_result();
    
    if ($color_result->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Color panel tidak ditemukan']);
        exit();
    }
    
    $color_data = $color_result->fetch_assoc();
    
    // Check if component exists
    $comp_check = $conn->prepare("SELECT component_name FROM color_components WHERE id = ?");
    $comp_check->bind_param('i', $component_id);
    $comp_check->execute();
    $comp_result = $comp_check->get_result();
    
    if ($comp_result->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Component tidak ditemukan']);
        exit();
    }
    
    $comp_data = $comp_result->fetch_assoc();
    
    // Check if component already exists for this color
    $existing_check = $conn->prepare("SELECT id FROM color_panel_components WHERE color_id = ? AND component_id = ?");
    $existing_check->bind_param('ii', $color_id, $component_id);
    $existing_check->execute();
    $existing_result = $existing_check->get_result();
    
    if ($existing_result->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Component sudah ada untuk color panel ini']);
        exit();
    }
    
    // Insert new component to color panel
    $insert_query = "INSERT INTO color_panel_components (color_id, component_id, quantity, available_quantity) VALUES (?, ?, ?, 0)";
    $insert_stmt = $conn->prepare($insert_query);
    $insert_stmt->bind_param('iii', $color_id, $component_id, $quantity);
    
    if ($insert_stmt->execute()) {
        // Log the activity
        $it_id = $_SESSION['user_id'];
        $details = "Added component '{$comp_data['component_name']}' (qty: {$quantity}) to color panel '{$color_data['code_color']}'";
        create_audit_log($conn, 'Add Component', $it_id, 'it', $details);
        
        echo json_encode([
            'success' => true,
            'message' => 'Component berhasil ditambahkan'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Gagal menambahkan component: ' . $conn->error
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>