<?php

/**
 * Migration 0045 — owner_id on chat conversations (multi-tenancy Phase 3)
 *
 * Adds a nullable owner_id to instinctor_chat_conversations so every chat thread
 * belongs to a specific tenant (owner). Until now the chat table had no owner
 * column: on instinctor.com, where all tenants share one origin (and one '/'-scoped
 * visitor cookie), two salons' conversations landed in one undifferentiated table
 * and could not be filtered per owner. NULL = vendor / single-tenant scope, so the
 * column is inert on standalone WP installs and only comes alive where real tenants
 * exist (matches pages.owner_id / bookings.owner_id, migration 0043).
 *
 * Guarded via the 'php' callback: the ADD is checked against information_schema
 * first, so it is safe on a fresh install, a re-run, or a partially-applied state.
 *
 * @since 2.1.2233
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- schema migration on the plugin's own tables

return [
    'description' => 'Add nullable owner_id to chat_conversations (tenant scoping)',

    'up' => [],

    'php' => function () {
        $t = \Instinctor\Core\DB::prefix() . 'instinctor_chat_conversations';

        $hasCol = (int) \Instinctor\Core\DB::get_var(\Instinctor\Core\DB::prepare(
            "SELECT COUNT(*) FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s",
            $t, 'owner_id'
        )) > 0;
        if (!$hasCol) {
            \Instinctor\Core\DB::query("ALTER TABLE {$t} ADD COLUMN owner_id INT UNSIGNED NULL DEFAULT NULL");
        }

        $hasIdx = (int) \Instinctor\Core\DB::get_var(\Instinctor\Core\DB::prepare(
            "SELECT COUNT(*) FROM information_schema.STATISTICS
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND INDEX_NAME = %s",
            $t, 'owner_id'
        )) > 0;
        if (!$hasIdx) {
            \Instinctor\Core\DB::query("ALTER TABLE {$t} ADD KEY owner_id (owner_id)");
        }
    },
];
