<?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;
}

$branchIdRaw = isset($_GET['branch_id']) ? filter_var($_GET['branch_id'], FILTER_SANITIZE_NUMBER_INT) : null;
$branchId = ($branchIdRaw === null || $branchIdRaw === '' || (int)$branchIdRaw === 0) ? null : (int)$branchIdRaw;
$itemType = ($_GET['item_type'] ?? 'detailed') === 'simple' ? 'simple' : 'detailed';

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

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

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

$data = array_map(function ($item) use ($itemType, $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="move_to_shelf.php?item_id=' . $itemId . '" class="btn btn-sm btn-nark-as-damage" title="Move back to shelf"><i class="fas fa-suitcase"></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>';

    $row = [
        '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',
        'actions' => $actions,
    ];

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

    return $row;
}, $items);

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