<?php

/**
 * Migration 0048 — owner_id on the image library (multi-tenancy + upload cap)
 *
 * instinctor_images had NO owner column and the library picker (ajaxGetImages)
 * queried it globally, so on instinctor.com — where every tenant shares one app
 * and one database — a salon's media picker showed every OTHER tenant's uploads,
 * and there was no way to count "this owner's images" to cap free accounts.
 *
 * Adding the column lets ImageLibraryService (a) stamp each new upload with the
 * uploading site_owner's id, (b) scope the picker to "own + vendor stock", and
 * (c) enforce TenantPlan::imageUploadCap() per owner (free 10, Pro 50).
 *
 * Existing rows stay NULL = vendor / global pool: they are the vendor's own demo
 * and stock imagery, which is exactly what NULL should mean, and which every
 * tenant may still pick from. No backfill, no guessing. NULL is also inert on
 * single-tenant standalone installs (their one owner uploads as vendor). Matches
 * pages.owner_id, bookings.owner_id (0043), chat_conversations.owner_id (0045),
 * staff.owner_id (0046), estimates.owner_id (0047).
 *
 * 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.2361
 */

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 the image library (tenant scoping + upload cap)',

    'up' => [],

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

        $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 AFTER id");
        }

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