<?php

/**
 * Migration 0060 — chat messages distinguish the owner from the assistant
 *
 * sender was enum('visitor','admin'), so a reply typed by the business owner
 * and an Instagent auto-reply were indistinguishable. 'owner' records replies
 * the owner sends from the tenant dashboard (desktop /dashboard/chat and
 * /dashboard/app/chat-send); 'admin' keeps meaning the business side that is
 * not the owner in person (AI replies, admin-inbox agents, system follow-ups).
 *
 * MODIFY guarded via INFORMATION_SCHEMA (MySQL 8 safe, idempotent). Appending
 * an enum value preserves existing rows. If the table does not exist yet,
 * skip: ChatService::createTables() now creates it with the full enum.
 *
 * @since 2.1.3075
 */

if (!defined('ABSPATH')) exit;

return [
    'description' => "chat_messages.sender gains 'owner' (owner replies vs assistant)",

    'up' => [],

    'php' => function () {
        $t = \Instinctor\Core\DB::prefix() . 'instinctor_chat_messages';
        $type = (string) \Instinctor\Core\DB::get_var(\Instinctor\Core\DB::prepare(
            'SELECT COLUMN_TYPE FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s',
            $t, 'sender'
        ));
        if ($type !== '' && stripos($type, "'owner'") === false) {
            \Instinctor\Core\DB::query("ALTER TABLE {$t} MODIFY COLUMN sender ENUM('visitor','admin','owner') NOT NULL");
        }
    },
];
