<?php

/**
 * Migration 0051 — listing manage tokens (member portal, phase 2)
 *
 * Every listing gets a permanent secret token; possession of the link
 * IS the owner's identity (no account, no password — the fleet is frozen
 * and owners are non-technical, so the portal lives entirely on
 * instinctor.com at /directory/manage/:token). The owner edits their
 * blurb and notify contacts there and reads their messages.
 *
 * Backfills a token for every existing row; DirectoryService::save()
 * mints one for every new insert from here on.
 *
 * @since 2.1.2501
 */

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

return [
    'description' => 'Listing manage_token column + backfill (member self-serve portal)',

    'up' => [],

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

        $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, 'manage_token'
        )) > 0;
        if (!$hasCol) {
            \Instinctor\Core\DB::query("ALTER TABLE {$t} ADD COLUMN manage_token varchar(64) 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, 'manage_token'
        )) > 0;
        if (!$hasIdx) {
            \Instinctor\Core\DB::query("ALTER TABLE {$t} ADD UNIQUE KEY manage_token (manage_token)");
        }

        $ids = \Instinctor\Core\DB::get_col(
            "SELECT id FROM {$t} WHERE manage_token IS NULL OR manage_token = ''"
        );
        foreach ((array) $ids as $id) {
            \Instinctor\Core\DB::update($t, ['manage_token' => bin2hex(random_bytes(20))], ['id' => (int) $id]);
        }
    },
];
