<?php
// Start session
session_start();

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

// Set JSON header
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();
}

// Check if item_id is provided
if (!isset($_GET['item_id']) || empty($_GET['item_id'])) {
    echo json_encode(['success' => false, 'message' => 'Item ID is required']);
    exit();
}

$item_id = (int)$_GET['item_id'];

try {
    // Get complete item data with related information
    $query = "
        SELECT 
            csi.id,
            csi.kode_barang,
            csi.stock_number,
            csi.status,
            csi.lokasi,
            csi.rack_no,
            csi.qr_code,
            csi.tanggal_pembuatan,
            csi.tanggal_kedaluwarsa,
            csi.keterangan,
            cc.component_name,
            mcp.code_color,
            mcp.deskripsi as color_description,
            mcp.lemari,
            b.nama_buyer,
            b.kode_buyer
        FROM color_stock_items csi
        JOIN color_components cc ON csi.component_id = cc.id
        JOIN master_color_panel mcp ON csi.color_id = mcp.id
        JOIN buyers b ON mcp.buyer_id = b.id
        WHERE csi.id = ?
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Item not found']);
        exit();
    }
    
    $item = $result->fetch_assoc();
    $stmt->close();
    
    // Check if QR code exists
    if (empty($item['qr_code'])) {
        echo json_encode(['success' => false, 'message' => 'QR code not found for this item']);
        exit();
    }
    
    // Format dates
    if ($item['tanggal_pembuatan']) {
        $item['tanggal_pembuatan_formatted'] = date('d M Y', strtotime($item['tanggal_pembuatan']));
    }
    
    if ($item['tanggal_kedaluwarsa']) {
        $item['tanggal_kedaluwarsa_formatted'] = date('d M Y', strtotime($item['tanggal_kedaluwarsa']));
    }
    
    // Create date range string for print
    $date_range = '';
    if ($item['tanggal_pembuatan'] && $item['tanggal_kedaluwarsa']) {
        $date_range = date('Y-m-d', strtotime($item['tanggal_pembuatan'])) . ' - ' . date('Y-m-d', strtotime($item['tanggal_kedaluwarsa']));
    }
    $item['date_range'] = $date_range;
    
    echo json_encode([
        'success' => true,
        'item' => $item
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>