<?php

/**
 * Migration 0034 — `invoice_token` column on orders
 *
 * Home Services invoicing: an invoice is an order the owner creates for a
 * client (not from cart checkout). The token backs a public, own-branded pay
 * page at /invoice/{token} so the client can pay online without an account.
 * NULL for normal storefront orders.
 *
 * Idempotent via INFORMATION_SCHEMA guard, same pattern as 0031 / 0032.
 */

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

return [
    'description' => 'Add `invoice_token` column to inst_instinctor_orders',

    'up' => [],

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

        $colExists = \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  = 'invoice_token'",
                $table
            )
        );
        if (!$colExists) {
            \Instinctor\Core\DB::query(
                "ALTER TABLE {$table}
                 ADD COLUMN invoice_token VARCHAR(64) DEFAULT NULL,
                 ADD KEY invoice_token (invoice_token)"
            );
            if (\Instinctor\Core\DB::last_error() !== '') {
                throw new \RuntimeException(
                    esc_html('invoice_token column add failed: '
                    . \Instinctor\Core\DB::last_error())
                );
            }
        }
    },

    'down' => [
        "ALTER TABLE {prefix}instinctor_orders DROP COLUMN IF EXISTS invoice_token",
    ],
];
