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

/* Helpers simples */
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
  if (preg_match('~^(\d{2})/(\d{2})/(\d{4})$~', $d, $m)) return "$m[3]-$m[2]-$m[1]"; // dd/mm/aaaa
  return null;
}
function norm_money($s): ?string {
  if ($s === null) return null;
  $s = trim((string)$s);
  if ($s === '') return null;
  // remove milhar e troca vírgula por ponto
  $s = str_replace([' ', '.'], ['', ''], $s);
  $s = str_replace(',', '.', $s);
  if (!is_numeric($s)) return null;
  // mantém duas casas (se desejar)
  return number_format((float)$s, 2, '.', '');
}

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

// Lê a solicitação
$rr = $pdo->prepare("SELECT * FROM return_requests WHERE id=? LIMIT 1");
$rr->execute([$id]);
$rr = $rr->fetch(PDO::FETCH_ASSOC);
if (!$rr) { http_response_code(404); exit('Solicitação não encontrada'); }

switch ($action) {

  case 'set_in_progress':
    if ($rr['status'] === 'ABERTA') {
      $pdo->prepare("UPDATE return_requests SET status='EM_ANDAMENTO', updated_at=NOW() WHERE id=?")
          ->execute([$id]);
    }
    break;

  case 'set_done':
    if (in_array($rr['status'], ['ABERTA','EM_ANDAMENTO'], true)) {
      $pdo->prepare("UPDATE return_requests SET status='CONCLUIDA', updated_at=NOW() WHERE id=?")
          ->execute([$id]);
    }
    break;

  case 'set_cancel':
    if (in_array($rr['status'], ['ABERTA','EM_ANDAMENTO'], true)) {
      $pdo->prepare("UPDATE return_requests SET status='CANCELADA', updated_at=NOW() WHERE id=?")
          ->execute([$id]);
    }
    break;

  case 'set_charge':
    $amount = norm_money($_POST['charge_amount'] ?? null);   // aceita "1.234,56" ou "1234.56"
    $notes  = trim($_POST['charge_notes'] ?? '');
    $pdo->prepare("
        UPDATE return_requests
           SET status='COBRANCA',
               charge_amount = :amt,
               charge_notes  = :notes,
               updated_at    = NOW()
         WHERE id = :id
    ")->execute([
      ':amt'   => $amount,           // null se vazio/ inválido
      ':notes' => ($notes !== '' ? $notes : null),
      ':id'    => $id
    ]);
    break;

  case 'update_meta':
    $deadline = br_to_sql_date($_POST['deadline'] ?? null);
    $notes    = trim($_POST['notes'] ?? '');
    $pdo->prepare("
        UPDATE return_requests
           SET deadline   = :deadline,
               notes      = :notes,
               updated_at = NOW()
         WHERE id = :id
    ")->execute([
      ':deadline' => $deadline,
      ':notes'    => ($notes !== '' ? $notes : null),
      ':id'       => $id
    ]);
    break;

  default:
    // ação desconhecida: só ignora
    break;
}

header('Location: '.base_url('return_request_view.php?id='.$id));
exit;

