<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Set header for JSON response
header('Content-Type: application/json');

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

try {
    // Check if master_color_id is provided
    if (!isset($_GET['master_color_id']) || empty($_GET['master_color_id'])) {
        throw new Exception("Master Color ID is required");
    }
    
    $master_color_id = (int)$_GET['master_color_id'];
    
    // Validate master color exists
    $master_check_query = "SELECT id, code_color, name_color FROM master_color WHERE id = ?";
    $stmt = $conn->prepare($master_check_query);
    $stmt->bind_param("i", $master_color_id);
    $stmt->execute();
    $master_result = $stmt->get_result();
    
    if ($master_result->num_rows === 0) {
        throw new Exception("Master color not found");
    }
    
    $master_data = $master_result->fetch_assoc();
    $stmt->close();
    
    // Query to get all copy panel items for specific master color
    $query = "SELECT 
                csi.id,
                csi.kode_barang,
                csi.rack_no,
                csi.status,
                mcp.code_color,
                mcp.lemari,
                cc.component_name
              FROM color_stock_items csi
              JOIN master_color_panel mcp ON csi.color_id = mcp.id
              LEFT JOIN color_components cc ON csi.component_id = cc.id
              WHERE csi.item_type = 'copy_panel'
              AND mcp.master_color_id = ?
              ORDER BY csi.id ASC
              LIMIT 200";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $master_color_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if (!$result) {
        throw new Exception("Query error: " . $conn->error);
    }
    
    $items = [];
    while ($row = $result->fetch_assoc()) {
        $items[] = [
            'id' => $row['id'],
            'kode_barang' => $row['kode_barang'],
            'current_rack' => $row['rack_no'] ?? 'N/A',
            'status' => $row['status'],
            'code_color' => $row['code_color'],
            'lemari' => $row['lemari'] ?? 'A',
            'component_name' => $row['component_name'] ?? 'N/A'
        ];
    }
    
    $stmt->close();
    
    echo json_encode([
        'success' => true,
        'items' => $items,
        'total' => count($items),
        'master_color' => $master_data
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>