<?php

/**
 * Migration 0031 — `tip_total` column on orders
 *
 * Stores the gratuity a customer adds at checkout (restaurant stores). Kept as
 * its own column, not folded into discount/total, so tips report cleanly and
 * the owner can see them per order. The order `total` already includes the tip;
 * this records how much of that total was gratuity.
 *
 * Idempotent via INFORMATION_SCHEMA guard, same pattern as 0028 / 0030.
 */

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

return [
    'description' => 'Add `tip_total` 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  = 'tip_total'",
                $table
            )
        );
        if (!$colExists) {
            \Instinctor\Core\DB::query(
                "ALTER TABLE {$table}
                 ADD COLUMN tip_total DECIMAL(19,4) NOT NULL DEFAULT 0
                 AFTER shipping_total"
            );
            if (\Instinctor\Core\DB::last_error() !== '') {
                throw new \RuntimeException(
                    esc_html('tip_total column add failed: '
                    . \Instinctor\Core\DB::last_error())
                );
            }
        }
    },

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