<?php
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);
$auth->requireLogin();

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

$req = DataTableRequest::fromRequest();

$items = $inventory->getSimpleItemsAssets($branchId, $req['search'], 'i.item_name ASC', $req['length'], $req['start']);
$total = $inventory->countSimpleItemsAssets($branchId);
$filtered = $req['search'] !== null ? $inventory->countSimpleItemsAssets($branchId, $req['search']) : $total;

$data = array_map(function ($item) {
    return [
        'unique_id' => htmlspecialchars($item['unique_id'] ?? 'N/A'),
        'item_name' => htmlspecialchars($item['item_name'] ?? 'N/A'),
        'item_details' => htmlspecialchars($item['item_details'] ?? 'N/A'),
        'unit_price' => $item['unit_price'] !== null && $item['unit_price'] !== '' ? number_format((float)$item['unit_price'], 2) : 'N/A',
        'date_entered' => $item['date_entered'] ? date('Y-m-d', strtotime($item['date_entered'])) : 'N/A',
        'warranty' => htmlspecialchars(($item['warranty'] ?? 'N/A') . ' months'),
        'serial_number' => htmlspecialchars($item['serial_number'] ?? 'N/A'),
        'technical_specs' => htmlspecialchars($item['technical_specs'] ?? 'N/A'),
    ];
}, $items);

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