<?php

/*
Plugin Name: WooCommerce Mandatory Cart Minimum
Description: Enforces a minimum cart total for WooCommerce checkout.
Version: 1.0
Author: CodeWP
*/

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

class WC_Mandatory_Cart_Minimum {
    private $option_name = 'wc_mandatory_cart_minimum';

    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('woocommerce_check_cart_items', array($this, 'validate_cart_minimum'));
    }

    public function add_admin_menu() {
        add_options_page(
            'WooCommerce Mandatory Cart Minimum',
            'WC Cart Minimum',
            'manage_options',
            $this->option_name,
            array($this, 'create_settings_page')
        );
    }

    public function register_settings() {
        register_setting($this->option_name, $this->option_name, 'intval');
    }

    public function create_settings_page() {
        ?>
        <div class="wrap">
            <form method="post" action="options.php">
            <?php
                settings_fields($this->option_name);
                do_settings_sections($this->option_name);
                $minimum = get_option($this->option_name, 0);
            ?>
                <table class="form-table">
                    <tr valign="top">
                        <th scope="row">Minimum Cart Total</th>
                        <td><input type="number" name="<?php echo $this->option_name; ?>" value="<?php echo $minimum; ?>" /></td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>
        </div>
        <?php
    }

    public function validate_cart_minimum() {
        $minimum = get_option($this->option_name, 0);
        if (WC()->cart->total < $minimum) {
            wc_add_notice(sprintf('Your current cart total is %s — you must have an order with a minimum of %s to place your order.', wc_price(WC()->cart->total), wc_price($minimum)), 'error');
        }
    }
}

new WC_Mandatory_Cart_Minimum();