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

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

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
if (!isset($_SESSION['user_id'])) {
    if (ob_get_level() > 0) ob_clean();
    http_response_code(401);
    echo json_encode(['draw' => (int)($_GET['draw'] ?? 1), 'recordsTotal' => 0, 'recordsFiltered' => 0, 'data' => [], 'error' => 'Your session has expired. Please sign in again.']);
    exit;
}

$branchId = $auth->getUserBranch($_SESSION['user_id']);
$inventory = new Inventory($conn);

$req = DataTableRequest::fromRequest();

$items = $inventory->getGroupedDetailedItems($branchId, $req['search'], $req['length'], $req['start']);
$total = $inventory->countGroupedDetailedItems($branchId);
$filtered = $req['search'] !== null ? $inventory->countGroupedDetailedItems($branchId, $req['search']) : $total;

$data = array_map(function ($item) {
    $minimumPrice = (float)($item['minimum_price'] ?? 0);
    $maximumPrice = (float)($item['maximum_price'] ?? 0);
    $price = number_format($minimumPrice, 2);
    if (abs($maximumPrice - $minimumPrice) > 0.001) {
        $price .= ' - ' . number_format($maximumPrice, 2);
    }
    $productCodeCount = (int)($item['product_code_count'] ?? 0);
    $productCode = $productCodeCount > 1
        ? $productCodeCount . ' product codes'
        : (string)($item['product_code'] ?? '');
    return [
        'group_key' => (string)($item['group_key'] ?? ''),
        'product_code' => htmlspecialchars($productCode),
        'item_name' => htmlspecialchars($item['item_name'] ?? 'N/A'),
        'item_details' => htmlspecialchars($item['item_details'] ?? 'N/A'),
        'available_quantity' => max(0, (int)($item['available_quantity'] ?? $item['quantity'] ?? 0)),
        'category' => htmlspecialchars($item['category'] ?? 'N/A'),
        'unit_price' => $price,
        'date_entered' => $item['date_entered'] ? date('Y-m-d', strtotime($item['date_entered'])) : 'N/A',
        'warranty' => htmlspecialchars(($item['warranty'] ?? 'N/A') . ' months'),
        'technical_specs' => htmlspecialchars($item['technical_specs'] ?? 'N/A'),
    ];
}, $items);

DataTableRequest::respond($req['draw'], $total, $filtered, $data);
} catch (Throwable $e) {
    error_log('Grouped branch stock data failed: ' . $e->getMessage());
    if (ob_get_level() > 0) ob_clean();
    http_response_code(500);
    echo json_encode(['draw' => (int)($_GET['draw'] ?? 1), 'recordsTotal' => 0, 'recordsFiltered' => 0, 'data' => [], 'error' => 'Unable to load grouped branch stock.']);
}
