<?php
/**
 * REVENDA — Migration v33.0.0
 * File: tools/migrate-v33-home.php
 *
 * Adds the verification + wallet + subscription columns required by the
 * v33.0.0 operator-first homepage (pages/home.php).
 *
 * - Idempotent: safe to run twice. Checks information_schema before ALTER.
 * - Backfills existing rows with sensible defaults.
 * - Sets the Revenda CTO row to Enterprise tier and 10.00 commission (floor).
 * - Does NOT touch: payout_requests, payments, subscription_plans,
 *   tour_bookings, mice_commissions, subscription_invoices.
 * - Does NOT insert subscription plans. Those are already in
 *   subscription_plans (5 rows confirmed). The homepage uses the static
 *   homeSubscriptionTiers() helper, not a DB read.
 *
 * Run via CLI:
 *     php /home/betvrtjcje/revenda.tanzaquest.com/tools/migrate-v33-home.php
 *
 * Or via browser (admin only, logged in):
 *     https://revenda.tanzaquest.com/?page=tools-migrate-v33-home
 *
 * Requires the router to include this file only for an admin route. If
 * running standalone, config/database/functions must be required first.
 */

if (!defined('APP_START')) {
    // Standalone CLI bootstrap. If included from index.php, this block is skipped.
    $basePath = realpath(__DIR__ . '/..');
    require_once $basePath . '/config.php';
    require_once $basePath . '/database.php';
    require_once $basePath . '/functions.php';
    if (!function_exists('isAdmin') || !isAdmin()) {
        if (PHP_SAPI !== 'cli') {
            http_response_code(403);
            exit('Admin access required.');
        }
    }
}

function mig_v33_log(string $msg): void {
    $line = '[' . date('Y-m-d H:i:s') . '] ' . $msg;
    if (PHP_SAPI === 'cli') {
        fwrite(STDOUT, $line . PHP_EOL);
    } else {
        echo '<div style="font-family:monospace;padding:4px 12px;border-bottom:1px solid #eee;">'
           . htmlspecialchars($line) . '</div>';
        if (function_exists('ob_flush')) { @ob_flush(); @flush(); }
    }
}

function mig_v33_safe(string $sql, string $context): void {
    try {
        db()->exec($sql);
        mig_v33_log("OK   $context");
    } catch (Throwable $e) {
        mig_v33_log("FAIL $context — " . $e->getMessage());
    }
}

function mig_v33_column_exists(string $table, string $column): bool {
    try {
        $row = db()->fetchOne(
            "SELECT COUNT(*) AS c
             FROM information_schema.columns
             WHERE table_schema = DATABASE()
               AND table_name = ?
               AND column_name = ?",
            [$table, $column]
        );
        return ((int)($row['c'] ?? 0)) > 0;
    } catch (Throwable $e) {
        return false;
    }
}

function mig_v33_add_column_if_missing(string $table, string $column, string $definition): bool {
    if (mig_v33_column_exists($table, $column)) {
        mig_v33_log("SKIP $table.$column — already exists");
        return false;
    }
    mig_v33_safe("ALTER TABLE `$table` ADD COLUMN `$column` $definition", "ADD $table.$column");
    return true;
}

if (PHP_SAPI !== 'cli') {
    echo '<!doctype html><html><head><meta charset="utf-8"><title>Revenda Migration v33.0.0</title>'
       . '<style>body{font-family:system-ui,sans-serif;background:#0f0c29;color:#e6e8f0;padding:30px;}'
       . 'h1{color:#a3bffa;}code{background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px;}'
       . '.ok{color:#00b894;} .fail{color:#f5576c;}</style></head><body>'
       . '<h1>Revenda — Migration v33.0.0</h1>'
       . '<p>Adding verification, wallet, and subscription columns to <code>tour_operators</code> and <code>meeting_venues</code>.</p>';
}

mig_v33_log('=== Migration v33.0.0 starting ===');

/* ----------------------------------------------------------------
 * 1. Columns to add to BOTH tables
 * ----------------------------------------------------------------
 * Types chosen to match existing conventions in the schema:
 *  - cto_verification_tier is enum('pending','provisional','verified','elite','suspended')
 *    -> verification_tier is our new enum('standard','premium','elite')
 *  - commission_rate is decimal(5,2) storing 15.00 = 15%
 *    -> we do not add commission_rate (already exists)
 *  - wallet columns are decimal(14,2) for currency, 12 digits + 2 dp
 */
$columns = [
    'verification_tier'         => "enum('standard','premium','elite') DEFAULT NULL",
    'verification_status'       => "enum('unverified','pending','verified','suspended','revoked') NOT NULL DEFAULT 'unverified'",
    'settlement_compliance'     => "tinyint(3) unsigned NOT NULL DEFAULT 100",
    'outcome_score'             => "tinyint(3) unsigned DEFAULT NULL",
    'response_score'            => "tinyint(3) unsigned DEFAULT NULL",
    'review_score'              => "decimal(3,2) DEFAULT NULL",
    'subscription_tier'         => "enum('free','starter','pro','business','enterprise') NOT NULL DEFAULT 'free'",
    'wallet_balance_pending'    => "decimal(14,2) NOT NULL DEFAULT 0.00",
    'wallet_balance_available'  => "decimal(14,2) NOT NULL DEFAULT 0.00",
    'wallet_lifetime_earned'    => "decimal(14,2) NOT NULL DEFAULT 0.00",
    'wallet_lifetime_commission'=> "decimal(14,2) NOT NULL DEFAULT 0.00",
];

foreach (['tour_operators', 'meeting_venues'] as $table) {
    mig_v33_log("--- $table ---");
    foreach ($columns as $col => $def) {
        mig_v33_add_column_if_missing($table, $col, $def);
    }
}

/* ----------------------------------------------------------------
 * 2. Indexes for AI-agent queries and tier lookups
 * ----------------------------------------------------------------
 * Prefix idx_ to match existing naming if possible. Use IF NOT EXISTS
 * is not supported on all MariaDB versions, so we check first.
 */
function mig_v33_index_exists(string $table, string $index): bool {
    try {
        $row = db()->fetchOne(
            "SELECT COUNT(*) AS c
             FROM information_schema.statistics
             WHERE table_schema = DATABASE()
               AND table_name = ?
               AND index_name = ?",
            [$table, $index]
        );
        return ((int)($row['c'] ?? 0)) > 0;
    } catch (Throwable $e) {
        return false;
    }
}

$indexes = [
    'idx_v33_verification' => '(verification_tier, verification_status)',
    'idx_v33_subscription' => '(subscription_tier)',
    'idx_v33_compliance'   => '(settlement_compliance)',
];

foreach (['tour_operators', 'meeting_venues'] as $table) {
    foreach ($indexes as $name => $cols) {
        if (mig_v33_index_exists($table, $name)) {
            mig_v33_log("SKIP index $table.$name — exists");
            continue;
        }
        mig_v33_safe("ALTER TABLE `$table` ADD INDEX `$name` $cols", "ADD INDEX $table.$name");
    }
}

/* ----------------------------------------------------------------
 * 3. Backfill — tour_operators
 * ----------------------------------------------------------------
 * Map existing signals to the new columns:
 *   cto_verification_tier = 'elite'      -> verification_tier = 'elite'
 *   cto_verification_tier = 'verified'   -> verification_tier = 'premium'
 *   cto_verification_tier = 'provisional'-> verification_tier = 'standard'
 *   cto_verification_tier = 'pending'    -> verification_tier = NULL
 *
 *   is_verified = 1 AND status = 'published' -> verification_status = 'verified'
 *   is_verified = 0                         -> verification_status = 'unverified'
 *   status = 'suspended'                    -> verification_status = 'suspended'
 *   status = 'pending'                      -> verification_status = 'pending'
 */
mig_v33_log('--- Backfill tour_operators ---');

try {
    // verification_tier from cto_verification_tier
    db()->exec("
        UPDATE `tour_operators`
        SET verification_tier = CASE
            WHEN cto_verification_tier = 'elite'       THEN 'elite'
            WHEN cto_verification_tier = 'verified'    THEN 'premium'
            WHEN cto_verification_tier = 'provisional' THEN 'standard'
            ELSE NULL
        END
        WHERE verification_tier IS NULL
    ");
    mig_v33_log("OK   backfill verification_tier");

    // verification_status from is_verified + status
    db()->exec("
        UPDATE `tour_operators`
        SET verification_status = CASE
            WHEN status = 'suspended'                     THEN 'suspended'
            WHEN status = 'pending'                        THEN 'pending'
            WHEN is_verified = 1 AND status = 'published'  THEN 'verified'
            ELSE 'unverified'
        END
        WHERE verification_status = 'unverified'
          AND is_verified IN (0,1)
    ");
    mig_v33_log("OK   backfill verification_status");

    // settlement_compliance = 100 for all (no breach history yet)
    db()->exec("UPDATE `tour_operators` SET settlement_compliance = 100 WHERE settlement_compliance <> 100 OR settlement_compliance IS NULL");
    mig_v33_log("OK   backfill settlement_compliance = 100");

    // subscription_tier = 'enterprise' for the Revenda CTO (slug: revenda-cto-tours)
    // All other operators start on 'free'.
    db()->exec("
        UPDATE `tour_operators`
        SET subscription_tier = CASE
            WHEN slug = 'revenda-cto-tours' THEN 'enterprise'
            ELSE 'free'
        END
        WHERE subscription_tier = 'free'
    ");
    mig_v33_log("OK   backfill subscription_tier (Revenda CTO -> enterprise, others -> free)");

    // commission_rate floor 10.00 for the Revenda CTO row (was 5.00, below the published floor)
    db()->exec("
        UPDATE `tour_operators`
        SET commission_rate = 10.00
        WHERE slug = 'revenda-cto-tours'
          AND commission_rate < 10.00
    ");
    mig_v33_log("OK   raised Revenda CTO commission_rate to 10.00 floor");

    // review_score from rating_average (0..5 scale, which matches decimal(3,2))
    db()->exec("
        UPDATE `tour_operators`
        SET review_score = rating_average
        WHERE review_score IS NULL
          AND rating_average IS NOT NULL
          AND rating_average > 0
    ");
    mig_v33_log("OK   backfill review_score from rating_average");
} catch (Throwable $e) {
    mig_v33_log("FAIL backfill tour_operators — " . $e->getMessage());
}

/* ----------------------------------------------------------------
 * 4. Backfill — meeting_venues
 * ----------------------------------------------------------------
 * meeting_venues has no existing cto_verification_tier column, so we
 * derive from is_active + status:
 *   status = 'published' AND is_active = 1 -> verified / standard
 *   status = 'pending'                     -> pending / NULL tier
 *   status = 'suspended'                   -> suspended / NULL tier
 *   status = 'draft'                       -> unverified / NULL tier
 */
mig_v33_log('--- Backfill meeting_venues ---');

try {
    db()->exec("
        UPDATE `meeting_venues`
        SET verification_tier = CASE
            WHEN status = 'published' AND is_active = 1 THEN 'standard'
            ELSE NULL
        END
        WHERE verification_tier IS NULL
    ");
    mig_v33_log("OK   backfill meeting_venues.verification_tier");

    db()->exec("
        UPDATE `meeting_venues`
        SET verification_status = CASE
            WHEN status = 'published' AND is_active = 1 THEN 'verified'
            WHEN status = 'suspended'                   THEN 'suspended'
            WHEN status = 'pending'                     THEN 'pending'
            ELSE 'unverified'
        END
        WHERE verification_status = 'unverified'
    ");
    mig_v33_log("OK   backfill meeting_venues.verification_status");

    db()->exec("UPDATE `meeting_venues` SET settlement_compliance = 100 WHERE settlement_compliance <> 100 OR settlement_compliance IS NULL");
    mig_v33_log("OK   backfill meeting_venues.settlement_compliance = 100");

    db()->exec("UPDATE `meeting_venues` SET subscription_tier = 'free' WHERE subscription_tier = 'free'");
    mig_v33_log("OK   meeting_venues.subscription_tier = 'free' for all");

    db()->exec("
        UPDATE `meeting_venues`
        SET review_score = (
            SELECT AVG(r.rating) FROM reviews r
            WHERE r.venue_id = meeting_venues.id
        )
        WHERE review_score IS NULL
    ");
    mig_v33_log("OK   attempted meeting_venues.review_score from reviews (best effort)");
} catch (Throwable $e) {
    mig_v33_log("FAIL backfill meeting_venues — " . $e->getMessage());
}

/* ----------------------------------------------------------------
 * 5. Verification report
 * ---------------------------------------------------------------- */
mig_v33_log('--- Verification ---');

foreach (['tour_operators', 'meeting_venues'] as $table) {
    try {
        $row = db()->fetchOne("SELECT COUNT(*) AS total FROM `$table`");
        $total = (int)($row['total'] ?? 0);

        $row = db()->fetchOne("SELECT COUNT(*) AS c FROM `$table` WHERE verification_status = 'verified'");
        $verified = (int)($row['c'] ?? 0);

        $row = db()->fetchOne("SELECT COUNT(*) AS c FROM `$table` WHERE verification_tier = 'elite'");
        $elite = (int)($row['c'] ?? 0);

        $row = db()->fetchOne("SELECT COUNT(*) AS c FROM `$table` WHERE subscription_tier = 'enterprise'");
        $ent = (int)($row['c'] ?? 0);

        mig_v33_log("$table — total=$total  verified=$verified  elite=$elite  enterprise=$ent");
    } catch (Throwable $e) {
        mig_v33_log("FAIL report $table — " . $e->getMessage());
    }
}

mig_v33_log('=== Migration v33.0.0 complete ===');

if (PHP_SAPI !== 'cli') {
    echo '<p style="margin-top:24px;"><a href="/?page=home" style="color:#a3bffa;font-weight:700;">→ Open the homepage</a></p>';
    echo '</body></html>';
}