<?php
/**
 * NIS Asset Management System
 * API Endpoint: Get Issued Weapons
 * Returns list of currently issued weapons for return processing
 */

require_once __DIR__ . '/../config/init.php';

header('Content-Type: application/json');

// Check authentication
Auth::requireAuth();

// Check permission
if (!Auth::can('weapons.edit') && !Auth::can('weapons.return')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$search = $_GET['search'] ?? '';

if ($search) {
    $weapons = Database::fetchAll(
        "SELECT wil.id as issue_log_id, wil.officer_name, wil.issue_date, wil.expected_return_date,
                wi.id as weapon_id, wi.weapon_id as weapon_code, wi.make_model, wi.serial_no, wi.current_location
         FROM weapon_issue_log wil
         JOIN weapons_inventory wi ON wil.weapon_id = wi.id
         WHERE wil.status = 'Issued' 
           AND (wi.weapon_id LIKE ? OR wi.serial_no LIKE ? OR wi.make_model LIKE ? OR wil.officer_name LIKE ?)
         ORDER BY wil.issue_date DESC
         LIMIT 50",
        ["%$search%", "%$search%", "%$search%", "%$search%"]
    );
} else {
    $weapons = Database::fetchAll(
        "SELECT wil.id as issue_log_id, wil.officer_name, wil.issue_date, wil.expected_return_date,
                wi.id as weapon_id, wi.weapon_id as weapon_code, wi.make_model, wi.serial_no, wi.current_location
         FROM weapon_issue_log wil
         JOIN weapons_inventory wi ON wil.weapon_id = wi.id
         WHERE wil.status = 'Issued'
         ORDER BY wil.issue_date DESC
         LIMIT 50"
    );
}

// Calculate days out for each weapon
foreach ($weapons as &$weapon) {
    $issueDate = new DateTime($weapon['issue_date']);
    $today = new DateTime();
    $weapon['days_out'] = $issueDate->diff($today)->days;
    
    if ($weapon['expected_return_date']) {
        $expectedDate = new DateTime($weapon['expected_return_date']);
        $weapon['is_overdue'] = $expectedDate < $today;
        $weapon['days_overdue'] = $weapon['is_overdue'] ? $expectedDate->diff($today)->days : 0;
    } else {
        $weapon['is_overdue'] = false;
        $weapon['days_overdue'] = 0;
    }
}

echo json_encode([
    'success' => true,
    'data' => $weapons,
    'count' => count($weapons)
]);