<?php
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

$loan_id = (int)($_POST['loan_id'] ?? 0);
if (!$loan_id) { http_response_code(400); exit('ID inválido'); }

// Atualiza equipamento -> EM_ESTOQUE
$ids = $pdo->prepare('SELECT equipment_id FROM loan_items WHERE loan_id=?');
$ids->execute([$loan_id]);
$ids = $ids->fetchAll();
$up = $pdo->prepare("UPDATE equipment SET status='EM_ESTOQUE' WHERE id=?");
foreach ($ids as $row) { $up->execute([(int)$row['equipment_id']]); }

// Atualiza empréstimo -> DEVOLVIDO
$pdo->prepare("UPDATE loans SET status='DEVOLVIDO' WHERE id=?")->execute([$loan_id]);

header('Location: ' . base_url('loan_view.php?id='.$loan_id));
