-- ============================================================
-- Gustito Express — Cerrar el negocio: OCULTAR los datos del cliente (no borrar).
-- Los pedidos se conservan para el historial y los reportes, pero sin datos
-- personales (nombre, telefono, cedula, direccion, nota, comprobante).
-- La recuperacion por telefono deja de encontrarlos.
-- ============================================================
create or replace function public.cerrar_negocio()
returns void language plpgsql security definer set search_path = public
as $$
declare v_rest uuid := fn_mi_restaurante();
begin
  if v_rest is null or not (fn_es_staff_de(v_rest) or fn_es_admin()) then
    raise exception 'Sin permiso';
  end if;
  update public.restaurantes set abierto = false 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 <> '';            -- no re-procesar pedidos ya ocultados
  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.repartidores set estado = 'disponible' where restaurante_id = v_rest and estado = 'ocupado';
end;
$$;
grant execute on function public.cerrar_negocio() to authenticated;
