-- Village Grove at La Cita: post owner payments directly to the operating
-- checking account (HOLII COGENT Checking XX2814) instead of Undeposited Funds.
-- Scoped to this one company per request; all others keep the Undeposited flow.
-- (Interim hardcoded routing until a per-company "operating/deposit account"
-- setting exists.)
create or replace function accounting.post_payment_gl(_payment_id uuid)
 returns void
 language plpgsql
 security definer
 set search_path to 'public', 'accounting'
as $function$
declare p accounting.payments_received%rowtype; _ar uuid; _dest uuid; _je uuid;
begin
  select * into p from accounting.payments_received where id=_payment_id;
  if not found then return; end if;
  perform accounting._gl_clear(p.company_id, 'acmacc_pay', p.id::text);
  if not accounting.gl_managed(p.company_id) then return; end if;
  if coalesce(p.amount,0) = 0 then return; end if;
  if p.company_id = '3216c404-496f-4d98-b6fe-36d0f9b1278a' then
    _dest := 'db656b9e-f27a-4c0f-be2a-dc1fa793be49';  -- HOLII COGENT Checking -- XX2814
  else
    _dest := accounting.coa_undeposited(p.company_id);
  end if;
  _ar := accounting.coa_ar(p.company_id);
  insert into accounting.journal_entries (company_id, date, description, reference, external_source, external_id)
  values (p.company_id, p.payment_date, coalesce(nullif(p.memo,''), 'Payment received'), p.reference, 'acmacc_pay', p.id::text)
  returning id into _je;
  insert into accounting.journal_entry_lines (journal_entry_id, account_id, debit, credit, description) values
    (_je, _dest, p.amount, 0, 'Payment received'),
    (_je, _ar,   0, p.amount, 'Payment received');
end$function$;
