-- Monzer follow-up fixes: Deals page permission + safe quotation_items sync helper

-- Give account owners/admins access to the new Deals page where permissions are explicit.
INSERT INTO user_permissions (account_id, user_id, page_key, action_key, allowed)
SELECT u.account_id, u.id, 'deals', x.action_key, 1
FROM users u
JOIN (
  SELECT 'view' action_key UNION ALL SELECT 'open'
) x
LEFT JOIN user_permissions up
  ON up.account_id=u.account_id AND up.user_id=u.id AND up.page_key='deals' AND up.action_key=x.action_key
WHERE up.id IS NULL
  AND (u.id=1 OR u.role_id=1 OR u.is_account_owner=1 OR u.is_super_admin=1);

-- If an old quotation has exactly one header item and no quotation_items, create the row.
INSERT INTO quotation_items (quotation_id, item_id, quantity, unit_price, line_total)
SELECT q.id, q.item_id, q.quantity, q.unit_price, (q.quantity*q.unit_price)
FROM quotations q
LEFT JOIN quotation_items qi ON qi.quotation_id=q.id
WHERE qi.id IS NULL AND q.item_id IS NOT NULL;
