<?php
// color_details_it.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(['error' => 'Unauthorized access']);
    exit();
}

// Check if ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['error' => 'Invalid ID']);
    exit();
}

$color_id = $_GET['id'];
$response = [];

try {
    // Get color information
    $color_query = "SELECT c.*, b.nama_buyer, b.kode_buyer, col.nama_collection
                   FROM master_color_panel c
                   JOIN buyers b ON c.buyer_id = b.id
                   JOIN collections col ON c.collection_id = col.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) {
        throw new Exception("Color not found");
    }
    
    $response['color'] = $color_result->fetch_assoc();
    
    // Get components information
    $components_query = "SELECT cpc.*, cc.component_name
                       FROM color_panel_components cpc
                       JOIN color_components cc ON cpc.component_id = cc.id
                       WHERE cpc.color_id = ?";
    $components_stmt = $conn->prepare($components_query);
    $components_stmt->bind_param("i", $color_id);
    $components_stmt->execute();
    $components_result = $components_stmt->get_result();
    
    $response['components'] = [];
    while ($component = $components_result->fetch_assoc()) {
        $response['components'][] = $component;
    }
    
    // Get stock items information
    $stock_query = "SELECT csi.id, csi.kode_barang, csi.stock_number, csi.status, 
                          csi.lokasi, csi.rack_no, csi.tanggal_pembuatan, csi.tanggal_kedaluwarsa,
                          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();
    
    $response['stock_items'] = [];
    while ($stock = $stock_result->fetch_assoc()) {
        $response['stock_items'][] = $stock;
    }
    
    // Return JSON response
    echo json_encode($response);
    
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>