<?php

/**
 * Migration 0046 — owner_id on staff (multi-tenancy)
 *
 * instinctor_staff had NO owner column and every read was unscoped
 * (BookingService::staffCount/getStaff, AdminController's staff editor), so on
 * instinctor.com — where all tenants share one app and one database — two salons
 * would have shown each other's stylists in the booking picker and on their public
 * sites. Nothing leaked yet only because the table was still EMPTY: demos keep their
 * cast in the booking element's own settings (demo_staff) and never touched it.
 *
 * Caught while adding the dashboard staff UI, which is exactly what would have
 * started filling it. Adding the column while the table is empty means no backfill
 * and no risk; doing it after real salons had staff would have meant guessing which
 * row belonged to whom.
 *
 * 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 and
 * bookings.owner_id (0043) and chat_conversations.owner_id (0045).
 *
 * 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.2286
 */

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 staff (tenant scoping)',

    'up' => [],

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

        $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)");
        }
    },
];
