<?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 ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    header('Location: /IMS/unauthorized.php');
    exit;
}

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

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

$canDelete = (($_SESSION['username'] ?? '') === 'testuser');

$data = array_map(function ($item) use ($canDelete) {
    $itemId = (int)$item['item_id'];

    $actions = '<div class="action-buttons">'
        . '<a href="edit_item.php?item_id=' . $itemId . '" class="btn btn-sm btn-edit" title="Edit Item"><i class="fas fa-edit"></i></a>'
        . '<a href="send_to_damaged_item.php?item_id=' . $itemId . '" class="btn btn-sm btn-send-to-damage" title="Move to warehouse"><i class="fas fa-exclamation-circle"></i></a>';
    if ($canDelete) {
        $actions .= '<a href="delete_item.php?item_id=' . $itemId . '" class="btn btn-sm btn-nark-as-delete danger" title="Delete Item"><i class="fas fa-trash"></i></a>';
    }
    $actions .= '</div>';

    $condition = 'N/A';
    if (!empty($item['condition_status'])) {
        $conditionText = htmlspecialchars($item['condition_status']);
        $condition = '<span class="condition-badge condition-' . strtolower($conditionText) . '">' . $conditionText . '</span>';
    } else {
        $condition = '<span style="color: #6c757d;">N/A</span>';
    }

    return [
        'unique_id' => htmlspecialchars($item['unique_id'] ?? 'N/A'),
        'item_name' => '<strong>' . htmlspecialchars($item['item_name'] ?? 'N/A') . '</strong>',
        'item_details' => htmlspecialchars($item['item_details'] ?? 'N/A'),
        'unit_price' => 'MWK' . ($item['unit_price'] !== null && $item['unit_price'] !== '' ? number_format((float)$item['unit_price'], 2) : '0.00'),
        'date_entered' => $item['date_entered'] ? date('M d, Y', strtotime($item['date_entered'])) : 'N/A',
        'serial_number' => htmlspecialchars($item['serial_number'] ?? 'N/A'),
        'technical_specs' => htmlspecialchars($item['technical_specs'] ?? 'N/A'),
        'condition' => $condition,
        'actions' => $actions,
    ];
}, $items);

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