<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.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'])) {
    header('Location: ../../login.php');
    exit();
}

if (!in_array($_SESSION['role'] ?? '', ['admin', 'warehouse', 'branch'], true)) {
    header('Location: /IMS/unauthorized.php');
    exit;
}

$source_branch_id = ($_SESSION['role'] == 'admin') ? 7 : $auth->getUserBranch($_SESSION['user_id']);
if (!$source_branch_id) {
    DataTableRequest::respond((int)($_REQUEST['draw'] ?? 1), 0, 0, []);
}

$inventory = new Inventory($conn);
$req = DataTableRequest::fromRequest(10000, 10000);

$items = $inventory->getGroupedDetailedItems($source_branch_id, $req['search'], $req['length'], $req['start'], 10000);
$total = $inventory->countGroupedDetailedItems($source_branch_id);
$filtered = $req['search'] !== null ? $inventory->countGroupedDetailedItems($source_branch_id, $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);
    }
    return [
        'group_key' => (string)($item['group_key'] ?? ''),
        'item_name' => htmlspecialchars($item['item_name'] ?? ''),
        'item_details' => htmlspecialchars($item['item_details'] ?? ''),
        'product_code' => htmlspecialchars($item['product_code'] ?? ''),
        'available_quantity' => max(0, (int)($item['available_quantity'] ?? 0)),
        'unit_price' => $price,
        'category' => htmlspecialchars($item['category'] ?? ''),
        'condition_status' => htmlspecialchars($item['conditions'] ?? ''),
        'warranty_months' => htmlspecialchars($item['warranty'] ?? '0'),
        'technical_specs' => htmlspecialchars($item['technical_specs'] ?? ''),
        'date_entered' => $item['date_entered'] ? date('Y-m-d', strtotime($item['date_entered'])) : '',
    ];
}, $items);

DataTableRequest::respond($req['draw'], $total, $filtered, $data);
