<?php
if (!defined('ABSPATH')) exit;

add_action('stakmv_auctions_render_tab_vendors', function () {

    ?>
    <hr>
    <h2>Escrow Automation (Free)</h2>
    <p>Control when vendor funds are automatically credited after payment completes.</p>

    <?php
    if ( isset( $_POST['save_escrow_automation'] ) && check_admin_referer( 'stakmv_save_escrow_auto', 'stakmv_save_escrow_auto_nonce' ) ) {

        update_option(
            'stakmv_enable_auto_escrow',
            isset( $_POST['stakmv_enable_auto_escrow'] ) ? 'yes' : 'no'
        );

        update_option(
            'stakmv_auto_escrow_threshold',
            floatval( $_POST['stakmv_auto_escrow_threshold'] ?? 0 )
        );

        echo '<div class="updated"><p>Escrow automation settings saved.</p></div>';
    }

    $auto_enabled = get_option( 'stakmv_enable_auto_escrow', 'no' );
    $auto_thresh  = get_option( 'stakmv_auto_escrow_threshold', 0 );
    ?>

    <form method="post">
        <?php wp_nonce_field( 'stakmv_save_escrow_auto', 'stakmv_save_escrow_auto_nonce' ); ?>
        <table class="form-table">
            <tr>
                <th scope="row">Enable Automatic Crediting</th>
                <td>
                    <label>
                        <input type="checkbox" name="stakmv_enable_auto_escrow" <?php checked( $auto_enabled, 'yes' ); ?>>
                        Credit vendors automatically when payment is completed (see threshold below).
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row">Auto-credit Threshold</th>
                <td>
                    <input type="number" step="0.01" min="0" name="stakmv_auto_escrow_threshold" value="<?php echo esc_attr( $auto_thresh ); ?>">
                    <p class="description">
                        Orders at or below this amount will be auto-approved immediately on payment completion.
                        Higher amounts require buyer confirmation or delivery window to elapse.
                    </p>
                </td>
            </tr>
        </table>
        <p><button type="submit" class="button-primary" name="save_escrow_automation">Save Settings</button></p>
    </form>
    <?php
});
