<?php
ob_start();
header('Content-Type: application/json; charset=utf-8');

try {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    require_once __DIR__ . '/../../includes/auth.php';
    require_once __DIR__ . '/../../classes/Database.php';
    require_once __DIR__ . '/../../classes/Inventory.php';

    $database = new Database();
    $conn = $database->getConnection();
    if (!$conn instanceof PDO) {
        throw new RuntimeException('Database connection is unavailable.');
    }
    $auth = new Auth($conn);
    if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['admin', 'warehouse'], true)) {
        if (ob_get_level() > 0) ob_clean();
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
        exit;
    }

    $sourceBranchId = $_SESSION['role'] === 'admin'
        ? 7
        : (int)$auth->getUserBranch($_SESSION['user_id']);
    $groupKey = trim((string)($_GET['group_key'] ?? ''));
    if ($sourceBranchId <= 0 || $groupKey === '' || strlen($groupKey) > 500) {
        throw new RuntimeException('Invalid shipment item group.');
    }

    $rows = (new Inventory($conn))->getDetailedItemGroupCodes($sourceBranchId, $groupKey);
    $items = array_map(static function (array $row): array {
        return [
            'item_id' => (int)$row['item_id'],
            'item_name' => (string)($row['item_name'] ?? ''),
            'item_details' => (string)($row['item_details'] ?? ''),
            'product_code' => (string)($row['product_code'] ?? ''),
            'unique_code' => (string)($row['unique_code'] ?? ''),
            'unit_price' => (float)($row['unit_price'] ?? 0),
            'condition_status' => (string)($row['condition_status'] ?? ''),
            'serial_number' => (string)($row['serial_number'] ?? ''),
            'warranty_months' => (int)($row['warranty_months'] ?? 0),
            'technical_specs' => (string)($row['technical_specs'] ?? ''),
            'date_entered' => !empty($row['date_entered']) ? date('Y-m-d', strtotime($row['date_entered'])) : '',
        ];
    }, $rows);

    if (ob_get_level() > 0) ob_clean();
    echo json_encode(['success' => true, 'items' => $items], JSON_INVALID_UTF8_SUBSTITUTE);
} catch (Throwable $e) {
    error_log('Unable to load shipment item group: ' . $e->getMessage());
    if (ob_get_level() > 0) ob_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Unable to load shipment item group.']);
}
