<?php
/**
 * GGM Commerce MCP Discount Resources
 * Provides MCP resources for discount and voucher data
 *
 * @package GGM_Commerce
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * MCP Discount Resources class
 */
class GGM_Commerce_MCP_Discount_Resources {

    /**
     * MCP Server instance
     *
     * @var GGM_Commerce_MCP_Server
     */
    private $server;

    /**
     * Constructor
     *
     * @param GGM_Commerce_MCP_Server $server MCP Server instance.
     */
    public function __construct( $server ) {
        $this->server = $server;
        $this->register_resources();
    }

    /**
     * Check if discounts feature is activated
     *
     * @return bool
     */
    private function is_activated() {
        return class_exists( 'GGM_Commerce_Discounts' ) && GGM_Commerce_Discounts::is_activated();
    }

    /**
     * Register MCP resources
     */
    private function register_resources() {
        // List all discounts resource.
        $this->server->register_resource(
            'discounts',
            'discounts',
            __( 'List of all discounts and vouchers', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_discounts' )
        );

        // Single discount resource.
        $this->server->register_resource(
            'discount',
            'discount://{id}',
            __( 'Get a specific discount by ID', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_discount' )
        );

        // Discount by code resource.
        $this->server->register_resource(
            'discount_by_code',
            'discount_code://{code}',
            __( 'Get a discount by its code', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_discount_by_code' )
        );

        // Discount usage history resource.
        $this->server->register_resource(
            'discount_usage',
            'discount_usage://{id}',
            __( 'Get usage history for a discount', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_discount_usage' )
        );

        // Voucher balance resource.
        $this->server->register_resource(
            'voucher_balance',
            'voucher_balance://{code}',
            __( 'Get the current balance of a voucher', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_voucher_balance' )
        );

        // Active discounts resource.
        $this->server->register_resource(
            'active_discounts',
            'active_discounts',
            __( 'List of all currently active and valid discounts', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_active_discounts' )
        );

        // Discount statistics resource.
        $this->server->register_resource(
            'discount_statistics',
            'discount_statistics',
            __( 'Overview statistics for discounts and vouchers', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_discount_statistics' )
        );

        // Gift card products resource.
        $this->server->register_resource(
            'gift_card_products',
            'gift_card_products',
            __( 'List of all gift card/voucher products', 'ggm-commerce' ),
            'application/json',
            array( $this, 'get_gift_card_products' )
        );
    }

    /**
     * Get all discounts
     *
     * @param array $args Resource arguments.
     * @return array Discounts data.
     */
    public function get_discounts( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $page = isset( $args['page'] ) ? absint( $args['page'] ) : 1;
        $per_page = isset( $args['per_page'] ) ? absint( $args['per_page'] ) : 50;
        $status = isset( $args['status'] ) ? sanitize_text_field( $args['status'] ) : '';
        $type = isset( $args['type'] ) ? sanitize_text_field( $args['type'] ) : '';

        $discounts = GGM_Commerce_Discounts::get_instance();
        $result = $discounts->list_discounts(
            array(
                'page'     => $page,
                'per_page' => $per_page,
                'status'   => $status,
                'type'     => $type,
            )
        );

        return array(
            'discounts'   => $result['discounts'],
            'total'       => $result['total'],
            'page'        => $result['page'],
            'per_page'    => $result['per_page'],
            'total_pages' => $result['total_pages'],
        );
    }

    /**
     * Get a single discount
     *
     * @param array $args Resource arguments.
     * @return array Discount data.
     */
    public function get_discount( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $id = isset( $args['id'] ) ? absint( $args['id'] ) : 0;

        if ( ! $id ) {
            return array(
                'error' => __( 'Discount ID is required.', 'ggm-commerce' ),
            );
        }

        $discounts = GGM_Commerce_Discounts::get_instance();
        $discount = $discounts->get_discount( $id );

        if ( ! $discount ) {
            return array(
                'error' => __( 'Discount not found.', 'ggm-commerce' ),
            );
        }

        return array(
            'discount' => $discount,
        );
    }

    /**
     * Get a discount by code
     *
     * @param array $args Resource arguments.
     * @return array Discount data.
     */
    public function get_discount_by_code( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $code = isset( $args['code'] ) ? sanitize_text_field( $args['code'] ) : '';

        if ( empty( $code ) ) {
            return array(
                'error' => __( 'Discount code is required.', 'ggm-commerce' ),
            );
        }

        $discounts = GGM_Commerce_Discounts::get_instance();
        $discount = $discounts->get_discount_by_code( $code );

        if ( ! $discount ) {
            return array(
                'error' => __( 'Discount not found.', 'ggm-commerce' ),
            );
        }

        return array(
            'discount' => $discount,
        );
    }

    /**
     * Get discount usage history
     *
     * @param array $args Resource arguments.
     * @return array Usage history.
     */
    public function get_discount_usage( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $id = isset( $args['id'] ) ? absint( $args['id'] ) : 0;
        $limit = isset( $args['limit'] ) ? absint( $args['limit'] ) : 50;

        if ( ! $id ) {
            return array(
                'error' => __( 'Discount ID is required.', 'ggm-commerce' ),
            );
        }

        $discounts = GGM_Commerce_Discounts::get_instance();
        $usage = $discounts->get_usage_history( $id, $limit );

        return array(
            'discount_id' => $id,
            'usage'       => $usage,
            'count'       => count( $usage ),
        );
    }

    /**
     * Get voucher balance
     *
     * @param array $args Resource arguments.
     * @return array Balance data.
     */
    public function get_voucher_balance( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $code = isset( $args['code'] ) ? sanitize_text_field( $args['code'] ) : '';

        if ( empty( $code ) ) {
            return array(
                'error' => __( 'Voucher code is required.', 'ggm-commerce' ),
            );
        }

        $discounts = GGM_Commerce_Discounts::get_instance();
        return $discounts->get_voucher_balance( $code );
    }

    /**
     * Get active discounts
     *
     * @param array $args Resource arguments.
     * @return array Active discounts.
     */
    public function get_active_discounts( $args ) {
        global $wpdb;

        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $now = current_time( 'mysql' );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $discounts = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_discounts
                 WHERE status = 'active'
                 AND (valid_from IS NULL OR valid_from <= %s)
                 AND (valid_to IS NULL OR valid_to >= %s)
                 AND (usage_limit IS NULL OR usage_count < usage_limit)
                 ORDER BY created_at DESC",
                $now,
                $now
            )
        );

        // Decode JSON fields
        $discounts_handler = GGM_Commerce_Discounts::get_instance();
        foreach ( $discounts as &$discount ) {
            $json_fields = array( 'product_ids', 'category_ids', 'exclude_product_ids', 'exclude_category_ids' );
            foreach ( $json_fields as $field ) {
                if ( ! empty( $discount->$field ) ) {
                    $discount->$field = json_decode( $discount->$field, true );
                } else {
                    $discount->$field = array();
                }
            }
        }

        return array(
            'discounts' => $discounts,
            'count'     => count( $discounts ),
        );
    }

    /**
     * Get discount statistics
     *
     * @param array $args Resource arguments.
     * @return array Statistics.
     */
    public function get_discount_statistics( $args ) {
        global $wpdb;

        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $now = current_time( 'mysql' );

        // Total discounts count.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $total_discounts = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_discounts" );

        // Active discounts count.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $active_discounts = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_discounts
                 WHERE status = 'active'
                 AND (valid_from IS NULL OR valid_from <= %s)
                 AND (valid_to IS NULL OR valid_to >= %s)",
                $now,
                $now
            )
        );

        // Count by type.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $by_type = $wpdb->get_results(
            "SELECT discount_type, COUNT(*) as count FROM {$wpdb->prefix}ggmc_discounts GROUP BY discount_type"
        );

        $type_counts = array();
        foreach ( $by_type as $row ) {
            $type_counts[ $row->discount_type ] = (int) $row->count;
        }

        // Total usage count.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $total_uses = $wpdb->get_var( "SELECT SUM(usage_count) FROM {$wpdb->prefix}ggmc_discounts" );

        // Total discount amount given.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $total_discount_amount = $wpdb->get_var( "SELECT SUM(discount_amount) FROM {$wpdb->prefix}ggmc_discount_usage" );

        // Voucher statistics.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $voucher_stats = $wpdb->get_row(
            "SELECT
                COUNT(*) as total_vouchers,
                SUM(initial_value) as total_value,
                SUM(current_balance) as remaining_balance
             FROM {$wpdb->prefix}ggmc_discounts
             WHERE discount_type = 'voucher'"
        );

        return array(
            'total_discounts'        => (int) $total_discounts,
            'active_discounts'       => (int) $active_discounts,
            'by_type'                => $type_counts,
            'total_uses'             => (int) $total_uses,
            'total_discount_amount'  => (float) $total_discount_amount,
            'voucher_statistics'     => array(
                'total_vouchers'     => (int) ( $voucher_stats->total_vouchers ?? 0 ),
                'total_value'        => (float) ( $voucher_stats->total_value ?? 0 ),
                'remaining_balance'  => (float) ( $voucher_stats->remaining_balance ?? 0 ),
                'redeemed_value'     => (float) ( ( $voucher_stats->total_value ?? 0 ) - ( $voucher_stats->remaining_balance ?? 0 ) ),
            ),
        );
    }

    /**
     * Get gift card products
     *
     * @param array $args Resource arguments.
     * @return array Gift card products.
     */
    public function get_gift_card_products( $args ) {
        global $wpdb;

        if ( ! $this->is_activated() ) {
            return array(
                'error' => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $products = $wpdb->get_results(
            "SELECT id, name, sku, price, status, gift_card_value, gift_card_type,
                    gift_card_single_use, gift_card_valid_days, gift_card_code_prefix
             FROM {$wpdb->prefix}ggmc_products
             WHERE product_type = 'gift_card'
             ORDER BY name ASC"
        );

        return array(
            'products' => $products,
            'count'    => count( $products ),
        );
    }
}
