-- Per-invoice notifications toggle for AR.
--
-- Wholesale customers (today: orders sold by Robert Baker) pay on a mix of
-- prepay / partial-pay / negotiated terms, so the standard automated reminder
-- cadence is opt-in instead of opt-out for them. Default ON for everyone else.
--
-- The reminder cron skips invoices with notifications_enabled = 0; the toggle
-- on the AR detail panel UPDATEs this column and either schedules future
-- reminders (on enable) or cancels pending schedule rows (on disable).

ALTER TABLE ar_invoices
  ADD COLUMN IF NOT EXISTS notifications_enabled TINYINT(1) NOT NULL DEFAULT 1
  AFTER source;

-- Backfill: existing Robert Baker invoices land at disabled so the cron stops
-- the moment this ships. Re-runnable.
UPDATE ar_invoices SET notifications_enabled = 0 WHERE rep = 'Robert Baker';

-- Cancel any pending schedule rows for those invoices so they don't fire
-- the moment AR_EXTERNAL_SEND_ENABLED flips to true. Re-runnable.
UPDATE ar_notification_schedule s
  JOIN ar_invoices i ON i.id = s.invoice_id
  SET s.status = 'cancelled', s.processed_at = NOW()
  WHERE i.rep = 'Robert Baker' AND s.status = 'pending';
