-- ============================================================
-- Gustito Xpress — la JORNADA la marca el CIERRE DE CAJA, no la medianoche.
--
-- Problema: "Ventas de hoy" y el reporte cortaban a las 00:00. Un local que
-- abre 11am a 2am (cruza medianoche) queda partido en dos. Ahora la jornada
-- va desde el ULTIMO cierre de caja hasta el proximo. Cerrar la caja
-- (cerrar_negocio) sella la jornada guardando la hora; la siguiente arranca
-- en cero desde ahi.
-- ============================================================
alter table public.restaurantes add column if not exists ultimo_cierre_en timestamptz;

create or replace function public.cerrar_negocio()
returns void
language plpgsql security definer set search_path to 'public'
as $function$
declare v_rest uuid := fn_mi_restaurante();
begin
  if v_rest is null or not (fn_es_dueno_de(v_rest) or fn_es_admin()) then
    raise exception 'Sin permiso';
  end if;
  -- Cierra el negocio Y sella la jornada (desde aqui arranca la siguiente).
  update public.restaurantes set abierto = false, ultimo_cierre_en = now() where id = v_rest;
  -- ocultar datos personales (se conserva el pedido y sus totales)
  update public.pedidos
     set cliente_nombre     = 'Cliente',
         cliente_telefono   = '',
         cliente_cedula     = null,
         direccion          = null,
         direccion_latitud  = null,
         direccion_longitud = null,
         nota               = null
   where restaurante_id = v_rest
     and cliente_telefono <> '';
  update public.pagos
     set referencia = null, comprobante_url = null
   where pedido_id in (select id from public.pedidos where restaurante_id = v_rest);
  update public.pagos_mesa
     set referencia = null
   where restaurante_id = v_rest and referencia is not null;
  update public.repartidores set estado = 'disponible' where restaurante_id = v_rest and estado = 'ocupado';
end;
$function$;
