<?php
declare(strict_types=1);

require_once __DIR__ . '/../auth/guard.php';
require_once __DIR__ . '/../conexion.php';
require_once __DIR__ . '/../_helpers.php';

$u = require_login();
require_module_access($u, "vivienda");
$rut = $u['rut'] ?? null;

if (!function_exists('respond')) {
  function respond(array $payload, int $code = 200): void { json_response($payload, $code); }
}
if (!function_exists('respond_error')) {
  function respond_error(string $msg, int $code = 400): void { json_response(['ok'=>false,'message'=>$msg], $code); }
}

try {
  $year = (int)date('Y');
  $prefix = "VIV-$year-";

  $st = $pdo->prepare("
    SELECT MAX(CAST(SUBSTRING(cod_vivienda, :pos) AS UNSIGNED)) AS max_n
    FROM vivienda
    WHERE cod_vivienda LIKE :pref
  ");
  // posición donde empieza el número: strlen("VIV-YYYY-") + 1
  $pos = strlen($prefix) + 1;

  $st->execute([
    ':pos'  => $pos,
    ':pref' => $prefix . '%'
  ]);

  $max = (int)($st->fetchColumn() ?? 0);
  $next = $max + 1;
  $code = $prefix . str_pad((string)$next, 4, '0', STR_PAD_LEFT);

  respond(['ok'=>true, 'code'=>$code, 'rut'=>$rut]);
} catch (Throwable $e) {
  error_log("VIVIENDA next_code ERROR: ".$e->getMessage());
  respond_error("Error de servidor", 500);
}
