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

function br_to_sql_date(?string $d): ?string {
  if (!$d) return null;
  $d = trim($d);
  if ($d === '') return null;
  if (preg_match('~^\d{4}-\d{2}-\d{2}$~', $d)) return $d;                // yyyy-mm-dd (input type="date")
  if (preg_match('~^(\d{2})/(\d{2})/(\d{4})$~', $d, $m)) return "$m[3]-$m[2]-$m[1]"; // dd/mm/aaaa
  return null;
}

$employee_id = (int)($_POST['employee_id'] ?? 0);
$deadline    = br_to_sql_date($_POST['deadline'] ?? null);
$notes       = trim($_POST['notes'] ?? '');
$user        = current_user();
$user_id     = $user['id'] ?? null;

if ($employee_id <= 0) { http_response_code(400); exit('Empregado inválido'); }
if (!$user_id)         { http_response_code(403); exit('Usuário não autenticado'); }

// Confirma se o colaborador existe (evita abrir RR órfã)
$emp = $pdo->prepare("SELECT id FROM employees WHERE id=? LIMIT 1");
$emp->execute([$employee_id]);
if (!$emp->fetchColumn()) { http_response_code(404); exit('Colaborador não encontrado'); }

// Evita duplicar se já houver aberta/andamento
$chk = $pdo->prepare("SELECT id FROM return_requests WHERE employee_id=? AND status IN ('ABERTA','EM_ANDAMENTO') LIMIT 1");
$chk->execute([$employee_id]);
$exists = $chk->fetchColumn();
if ($exists) {
  header('Location: '.base_url('return_request_view.php?id='.(int)$exists));
  exit;
}

try {
  $pdo->beginTransaction();

  // Cria solicitação
  $ins = $pdo->prepare("
    INSERT INTO return_requests (employee_id, created_by, status, source, notes, deadline)
    VALUES (?, ?, 'ABERTA', 'RH', ?, ?)
  ");
  $ins->execute([$employee_id, $user_id, ($notes !== '' ? $notes : null), $deadline]);
  $req_id = (int)$pdo->lastInsertId();

  // Snapshot dos itens emprestados neste momento (empréstimos ativos)
  $loans = $pdo->prepare("SELECT id FROM loans WHERE employee_id=? AND status='DISPONIBILIZADO'");
  $loans->execute([$employee_id]);
  $loans = $loans->fetchAll(PDO::FETCH_ASSOC);

  $insItem = $pdo->prepare("INSERT INTO return_request_items (request_id, loan_id, equipment_id) VALUES (?, ?, ?)");
  $log     = $pdo->prepare("INSERT INTO equipment_log (equipment_id, user_id, action, notes) VALUES (?, ?, ?, ?)");

  foreach ($loans as $l) {
    $loan_id = (int)$l['id'];
    $items = $pdo->prepare("SELECT equipment_id FROM loan_items WHERE loan_id=?");
    $items->execute([$loan_id]);
    foreach ($items->fetchAll(PDO::FETCH_ASSOC) as $it) {
      $eq = (int)$it['equipment_id'];
      $insItem->execute([$req_id, $loan_id, $eq]);
      $log->execute([$eq, $user_id, 'RETURN_REQUEST_OPENED', 'RR#'.$req_id.' aberto pelo RH']);
    }
  }

  $pdo->commit();
  header('Location: '.base_url('return_request_view.php?id='.$req_id));
  exit;

} catch (Throwable $e) {
  if ($pdo->inTransaction()) $pdo->rollBack();
  http_response_code(500);
  echo 'Erro: '.$e->getMessage();
}

