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

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

$loan = $pdo->prepare('SELECT * FROM loans WHERE id=?');
$loan->execute([$loan_id]);
$loan = $loan->fetch();
if (!$loan) { http_response_code(404); exit('Empréstimo não encontrado'); }

$qItems = $pdo->prepare('SELECT equipment_id FROM loan_items WHERE loan_id=?');
$qItems->execute([$loan_id]);
$loanItems = array_map(fn($r)=> (int)$r['equipment_id'], $qItems->fetchAll());

$pdo->beginTransaction();
try {
  $notes = trim($_POST['notes'] ?? '');
  $pdo->prepare('INSERT INTO loan_returns (loan_id, received_by, notes) VALUES (?,?,?)')
      ->execute([$loan_id, current_user()['id'], $notes ?: null]);
  $lrid = (int)$pdo->lastInsertId();

  $RET_DIR = __DIR__ . '/uploads/returns';
  if (!is_dir($RET_DIR)) { @mkdir($RET_DIR, 0775, true); }
  $max = 8*1024*1024; $allowed = ['image/png','image/jpeg'];

  $ins = $pdo->prepare('INSERT INTO loan_return_items (loan_return_id,equipment_id,funciona,fonte,cabos,perifericos,avarias,observacoes,photo_path) VALUES (?,?,?,?,?,?,?,?,?)');
  $up  = $pdo->prepare("UPDATE equipment SET status='EM_ESTOQUE' WHERE id=?");
  $log = $pdo->prepare("INSERT INTO equipment_log (equipment_id,user_id,loan_id,action,from_status,to_status,notes) VALUES (?,?,?,?,?,?,?)");

  foreach ($loanItems as $eid) {
    $funciona = $_POST['funciona'][$eid] ?? 'SIM';
    if (!in_array($funciona, ['SIM','NAO','NA'], true)) $funciona = 'SIM';
    $fonte = isset($_POST['fonte'][$eid]) ? 1 : 0;
    $cabos = isset($_POST['cabos'][$eid]) ? 1 : 0;
    $perif = trim($_POST['perifericos'][$eid] ?? '') ?: null;
    $avarias = $_POST['avarias'][$eid] ?? 'NENHUMA';
    if (!in_array($avarias, ['NENHUMA','LEVE','GRAVE'], true)) $avarias = 'NENHUMA';
    $obs = trim($_POST['obs'][$eid] ?? '') ?: null;
    $photo = null;

    if (isset($_FILES['photo']) && isset($_FILES['photo']['tmp_name'][$eid]) && is_uploaded_file($_FILES['photo']['tmp_name'][$eid])) {
      $tmp  = $_FILES['photo']['tmp_name'][$eid];
      $type = mime_content_type($tmp);
      $size = (int)$_FILES['photo']['size'][$eid];
      if (in_array($type, $allowed, true) && $size <= $max) {
        $ext  = pathinfo($_FILES['photo']['name'][$eid], PATHINFO_EXTENSION) ?: 'jpg';
        $dest = $RET_DIR . '/' . $eid . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
        if (move_uploaded_file($tmp, $dest)) { $photo = basename($dest); }
      }
    }

    $ins->execute([$lrid,$eid,$funciona,$fonte,$cabos,$perif,$avarias,$obs,$photo]);
    $up->execute([$eid]);

    $note = 'Checklist: Funciona=' . $funciona . ', Fonte=' . ($fonte?'Sim':'Não') . ', Cabos=' . ($cabos?'Sim':'Não') .
            ', Periféricos=' . ($perif ?: '—') . ', Avarias=' . $avarias . ', Obs=' . ($obs ?: '—');
    $log->execute([$eid, current_user()['id'], $loan_id, 'RETURNED', 'EMPRESTADO', 'EM_ESTOQUE', $note]);
  }

  $pdo->prepare("UPDATE loans SET status='DEVOLVIDO' WHERE id=?")->execute([$loan_id]);
  $pdo->commit();
  header('Location: ' . base_url('return_receipt.php?id='.$lrid));
} catch (Exception $e) {
  if ($pdo->inTransaction()) $pdo->rollBack();
  http_response_code(500); echo 'Erro ao salvar devolução: '.$e->getMessage();
}
