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

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

// Get color ID from query string
$color_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($color_id <= 0) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Invalid color ID']);
    exit();
}

try {
    // Get color details
    $color_query = "SELECT c.*, b.nama_buyer, col.nama_collection, mc.code_color as master_code
                   FROM master_color_panel c
                   JOIN buyers b ON c.buyer_id = b.id
                   JOIN collections col ON c.collection_id = col.id
                   LEFT JOIN master_color mc ON c.master_color_id = mc.id
                   WHERE c.id = ?";
    $color_stmt = $conn->prepare($color_query);
    $color_stmt->bind_param("i", $color_id);
    $color_stmt->execute();
    $color_result = $color_stmt->get_result();
    
    if ($color_result->num_rows == 0) {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Color not found']);
        exit();
    }
    
    $color = $color_result->fetch_assoc();
    
    // Get components
    $components_query = "SELECT cc.component_name, cpc.quantity, cpc.available_quantity
                        FROM color_panel_components cpc
                        JOIN color_components cc ON cpc.component_id = cc.id
                        WHERE cpc.color_id = ?
                        ORDER BY cc.component_name";
    $components_stmt = $conn->prepare($components_query);
    $components_stmt->bind_param("i", $color_id);
    $components_stmt->execute();
    $components_result = $components_stmt->get_result();
    
    $components = [];
    while ($comp = $components_result->fetch_assoc()) {
        $components[] = $comp;
    }
    
    // Get stock items
    $stock_query = "SELECT csi.*, cc.component_name
                   FROM color_stock_items csi
                   JOIN color_components cc ON csi.component_id = cc.id
                   WHERE csi.color_id = ?
                   ORDER BY csi.rack_no";
    $stock_stmt = $conn->prepare($stock_query);
    $stock_stmt->bind_param("i", $color_id);
    $stock_stmt->execute();
    $stock_result = $stock_stmt->get_result();
    
    $stock_items = [];
    while ($item = $stock_result->fetch_assoc()) {
        $stock_items[] = $item;
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode([
        'color' => $color,
        'components' => $components,
        'stock_items' => $stock_items
    ]);
    
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage()]);
}
?>