-- Support tickets (table prefix UOYP7Y_). Run once in phpMyAdmin, top to bottom.
-- Take a backup of UOYP7Y_c2p_tickets first. Each step is safe to run on its own;
-- if a step says "Duplicate column" or "Duplicate key name", it is already done — skip it.

-- 1. New columns on the tickets table.
--    topic            what the ticket is about (chosen in the "New ticket" form)
--    customer_unread  1 = the pharmacy replied and the customer hasn't opened it yet
--                     (drives the dot in the customer's list; cleared when they open it)
ALTER TABLE UOYP7Y_c2p_tickets
  ADD COLUMN topic VARCHAR(50) NOT NULL DEFAULT '' AFTER subject,
  ADD COLUMN customer_unread TINYINT(1) NOT NULL DEFAULT 0 AFTER status;

-- 2. Index for "my tickets, newest activity first" (customer list) and the admin list.
ALTER TABLE UOYP7Y_c2p_tickets
  ADD KEY user_updated (user_id, updated_at),
  ADD KEY status_updated (status, updated_at);

-- 3. Pharmacist notes / tags history (used by the admin ticket screen).
CREATE TABLE IF NOT EXISTS UOYP7Y_c2p_ticket_outcomes (
  id             BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  ticket_id      BIGINT UNSIGNED NOT NULL,
  admin_id       BIGINT UNSIGNED NOT NULL,
  outcome_notes  LONGTEXT NULL,
  tags           LONGTEXT NULL,
  status_at_save VARCHAR(50) NULL,
  created_at     DATETIME NOT NULL,
  PRIMARY KEY (id),
  KEY ticket_id (ticket_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

-- 4. Data clean-up for existing tickets.
-- 4a. updated_at was not moved forward when someone replied. Set it to the latest message,
--     so lists sort by real last activity.
UPDATE UOYP7Y_c2p_tickets t
LEFT JOIN (SELECT ticket_id, MAX(created_at) last_at FROM UOYP7Y_c2p_ticket_replies GROUP BY ticket_id) r
       ON r.ticket_id = t.id
SET t.updated_at = GREATEST(COALESCE(t.created_at, '1970-01-01'), COALESCE(t.updated_at, '1970-01-01'), COALESCE(r.last_at, '1970-01-01'));

-- 4b. The old admin screen set every ticket to "resolved" as soon as staff replied, so
--     "resolved" really meant "waiting for the customer". Statuses are now:
--       open     = waiting for the pharmacy     (customer sees "Waiting for pharmacy")
--       pending  = pharmacy replied             (customer sees "Pharmacy replied")
--       resolved / closed = done                (customer sees "Closed", can reopen)
--     Move those auto-resolved tickets (last message from staff) to "pending".
UPDATE UOYP7Y_c2p_tickets t
JOIN (SELECT r.ticket_id, r.user_id
        FROM UOYP7Y_c2p_ticket_replies r
        JOIN (SELECT ticket_id, MAX(id) id FROM UOYP7Y_c2p_ticket_replies GROUP BY ticket_id) m ON m.id = r.id) lr
  ON lr.ticket_id = t.id
SET t.status = 'pending'
WHERE t.status = 'resolved' AND lr.user_id <> t.user_id;
