SET NAMES utf8mb4;
SELECT
    oi.id AS item_id,
    oi.original_name AS product_name,
    oi.personalization,
    oi.quantity,
    o.id AS order_id,
    o.internal_order_number,
    o.status_code AS status_code,
    oa.name AS buyer_name,
    oa.email AS buyer_email,
    pm.script_name,
    pm.output_dir,
    pm.requires_photo,
    (SELECT GROUP_CONCAT(n.comment SEPARATOR '\n---\n') FROM order_notes n WHERE n.order_id = o.id AND n.note_type = 'message') AS customer_message
FROM order_items oi
JOIN orders o ON oi.order_id = o.id
JOIN order_statuses os ON o.status_code = os.code
JOIN order_status_groups osg ON os.group_id = osg.id
JOIN project_mappings pm ON pm.is_active = 1 AND oi.original_name = pm.product_name_pattern
LEFT JOIN order_addresses oa ON o.id = oa.order_id AND oa.address_type = 'customer'
WHERE osg.id = 2
  AND oi.project_generated = 0
  AND oi.personalization IS NOT NULL
  AND oi.personalization <> ''
  AND oa.name LIKE '%Żarnowska%'
ORDER BY o.id;
