<?php
/**
 * WooCommerce Integration
 *
 * @package Invizo\SubscriptionsLite\Integrations
 */

namespace Invizo\SubscriptionsLite\Integrations;

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

class WooCommerce_Integration {

    public static function init() {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return;
        }

        $engine_mode = get_option( 'invizo_engine_mode', 'standalone' );
        if ( $engine_mode !== 'woocommerce' ) {
            return;
        }

        // Include the Product Class
        require_once __DIR__ . '/WC_Product_Subscription.php';

        // Add to Product Type Dropdown
        add_filter( 'product_type_selector', array( __CLASS__, 'add_product_type' ) );
        add_filter( 'woocommerce_product_class', array( __CLASS__, 'map_product_class' ), 10, 2 );

        // Add Product Data Tab for Subscriptions
        add_filter( 'woocommerce_product_data_tabs', array( __CLASS__, 'add_subscription_tab' ) );
        add_action( 'woocommerce_product_data_panels', array( __CLASS__, 'subscription_tab_content' ) );
        add_action( 'woocommerce_process_product_meta', array( __CLASS__, 'save_subscription_meta' ) );

        // Hook into Woo Checkout!
        add_action( 'woocommerce_checkout_order_processed', array( __CLASS__, 'process_subscription_on_checkout' ), 10, 3 );
    }

    public static function add_product_type( $types ) {
        $types['invizo_subscription'] = __( 'Subscription', 'invizo-subscriptions-lite' );
        return $types;
    }

    /**
     * Map the custom product type to a uniquely-prefixed PHP class.
     *
     * @param string $classname Product class name.
     * @param string $product_type Product type slug.
     * @return string
     */
    public static function map_product_class( $classname, $product_type ) {
        if ( 'invizo_subscription' === $product_type ) {
            return WC_Product_Subscription::class;
        }

        return $classname;
    }

    public static function add_subscription_tab( $tabs ) {
        $tabs['invizo_sub'] = array(
            'label'    => __( 'Subscription Settings', 'invizo-subscriptions-lite' ),
            'target'   => 'invizo_subscription_data',
            'class'    => array( 'show_if_invizo_subscription', 'invizo_subscription_tab' ),
        );
        return $tabs;
    }

    public static function subscription_tab_content() {
        global $post;
        $intervals = array(
            'day'   => __( 'Days', 'invizo-subscriptions-lite' ),
            'week'  => __( 'Weeks', 'invizo-subscriptions-lite' ),
            'month' => __( 'Months', 'invizo-subscriptions-lite' ),
            'year'  => __( 'Years', 'invizo-subscriptions-lite' ),
        );

        $interval_count  = get_post_meta( $post->ID, '_invizo_sub_interval_count', true );
        $interval_period = get_post_meta( $post->ID, '_invizo_sub_interval_period', true );
        $expiry_count    = get_post_meta( $post->ID, '_invizo_sub_expiry_count', true );
        $expiry_period   = get_post_meta( $post->ID, '_invizo_sub_expiry_period', true );
        $trial_count     = get_post_meta( $post->ID, '_invizo_sub_trial_count', true );
        $trial_period    = get_post_meta( $post->ID, '_invizo_sub_trial_period', true );
        ?>
        <div id="invizo_subscription_data" class="panel woocommerce_options_panel hidden">
            <div class="options_group">
                
                <p class="form-field _invizo_sub_interval_field">
                    <label for="_invizo_sub_interval_count"><?php esc_html_e( 'Subscriptions Per Interval', 'invizo-subscriptions-lite' ); ?></label>
                    <input type="number" step="1" min="1" class="short" style="width: 150px; margin-right: 10px;" name="_invizo_sub_interval_count" id="_invizo_sub_interval_count" value="<?php echo esc_attr( $interval_count ); ?>" placeholder="1" />
                    <select name="_invizo_sub_interval_period" id="_invizo_sub_interval_period" class="short" style="width: auto;">
                        <?php foreach ( $intervals as $key => $value ) : ?>
                            <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $interval_period, $key ); ?>><?php echo esc_html( $value ); ?></option>
                        <?php endforeach; ?>
                    </select>
                </p>

                <p class="form-field _invizo_sub_expiry_field">
                    <label for="_invizo_sub_expiry_count"><?php esc_html_e( 'Subscriptions Expiry Interval', 'invizo-subscriptions-lite' ); ?></label>
                    <input type="number" step="1" min="1" class="short" style="width: 150px; margin-right: 10px;" name="_invizo_sub_expiry_count" id="_invizo_sub_expiry_count" value="<?php echo esc_attr( $expiry_count ); ?>" placeholder="<?php echo esc_attr__( 'Enter subscription expiry', 'invizo-subscriptions-lite' ); ?>" />
                    <select name="_invizo_sub_expiry_period" id="_invizo_sub_expiry_period" class="short" style="width: auto;">
                        <?php foreach ( $intervals as $key => $value ) : ?>
                            <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $expiry_period, $key ); ?>><?php echo esc_html( $value ); ?></option>
                        <?php endforeach; ?>
                    </select>
                </p>

                <?php
                // Recurring Price
                woocommerce_wp_text_input( array(
                    'id'          => '_regular_price',
                    'label'       => __( 'Recurring Price ($)', 'invizo-subscriptions-lite' ),
                    'placeholder' => __( 'e.g. 19.99', 'invizo-subscriptions-lite' ),
                    'desc_tip'    => true,
                    'description' => __( 'The amount billed each interval.', 'invizo-subscriptions-lite' ),
                    'type'        => 'text',
                    'data_type'   => 'price'
                ) );

                // Initial Signup fee
                woocommerce_wp_text_input( array(
                    'id'          => '_invizo_sub_signup_fee',
                    'label'       => __( 'Initial Signup fee($)', 'invizo-subscriptions-lite' ),
                    'placeholder' => __( 'Enter signup fee', 'invizo-subscriptions-lite' ),
                    'desc_tip'    => true,
                    'description' => __( 'Optional one-time fee added to the first invoice.', 'invizo-subscriptions-lite' ),
                    'type'        => 'number',
                    'custom_attributes' => array(
                        'step' => '0.01',
                        'min'  => '0'
                    )
                ) );
                ?>

                <p class="form-field _invizo_sub_trial_field">
                    <label for="_invizo_sub_trial_count"><?php esc_html_e( 'Free trial interval', 'invizo-subscriptions-lite' ); ?></label>
                    <input type="number" step="1" min="1" class="short" style="width: 150px; margin-right: 10px;" name="_invizo_sub_trial_count" id="_invizo_sub_trial_count" value="<?php echo esc_attr( $trial_count ); ?>" placeholder="<?php echo esc_attr__( 'Enter free trial interval', 'invizo-subscriptions-lite' ); ?>" />
                    <select name="_invizo_sub_trial_period" id="_invizo_sub_trial_period" class="short" style="width: auto;">
                        <?php foreach ( $intervals as $key => $value ) : ?>
                            <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $trial_period, $key ); ?>><?php echo esc_html( $value ); ?></option>
                        <?php endforeach; ?>
                    </select>
                </p>

            </div>
        </div>
        <?php
    }

    public static function save_subscription_meta( $post_id ) {
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        if ( ! isset( $_POST['woocommerce_meta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) ), 'woocommerce_save_data' ) ) {
            return;
        }

        // Native Woo handles _regular_price and _price mapping, but we
        // need to explicitly sync _price to _regular_price if they entered it.
        $product_type = isset( $_POST['product-type'] ) ? sanitize_text_field( wp_unslash( $_POST['product-type'] ) ) : '';
        if ( isset( $_POST['_regular_price'] ) && 'invizo_subscription' === $product_type ) {
            $price_raw = sanitize_text_field( wp_unslash( $_POST['_regular_price'] ) );
            $price     = wc_format_decimal( $price_raw );
            update_post_meta( $post_id, '_price', $price );
            update_post_meta( $post_id, '_regular_price', $price );
        }

        $fields = array(
            '_invizo_sub_interval_count',
            '_invizo_sub_interval_period',
            '_invizo_sub_expiry_count',
            '_invizo_sub_expiry_period',
            '_invizo_sub_signup_fee',
            '_invizo_sub_trial_count',
            '_invizo_sub_trial_period',
        );

        foreach ( $fields as $field ) {
            if ( isset( $_POST[ $field ] ) ) {
                update_post_meta( $post_id, $field, sanitize_text_field( wp_unslash( $_POST[ $field ] ) ) );
            }
        }
    }

    public static function process_subscription_on_checkout( $order_id, $posted_data, $order ) {
        // Iterate over Woo Cart items, check if they map to an `invizo_subscription` product type
        foreach ( $order->get_items() as $item_id => $item ) {
            $product = $item->get_product();
            
            if ( $product && $product->get_type() === 'invizo_subscription' ) {
                $user_id = $order->get_user_id();
                $email = $order->get_billing_email();

                $sub_post_id = wp_insert_post( array(
                    'post_title'  => sprintf( 'Subscription - Order #%d - %s', $order_id, $email ),
                    'post_type'   => 'invizo_sub',
                    'post_status' => 'publish',
                ) );

                // Calculate next payment and expiry
                $interval_count  = $product->get_meta( '_invizo_sub_interval_count' );
                $interval_period = $product->get_meta( '_invizo_sub_interval_period' );
                $expiry_count    = $product->get_meta( '_invizo_sub_expiry_count' );
                $expiry_period   = $product->get_meta( '_invizo_sub_expiry_period' );

                $next_payment = '';
                if ( $interval_count && $interval_period ) {
                    $next_payment = gmdate( 'Y-m-d H:i:s', strtotime( "+{$interval_count} {$interval_period}" ) );
                }

                $expiry_date = '';
                if ( $expiry_count && $expiry_period ) {
                    $expiry_date = gmdate( 'Y-m-d H:i:s', strtotime( "+{$expiry_count} {$expiry_period}" ) );
                }

                update_post_meta( $sub_post_id, '_customer_email', $email );
                update_post_meta( $sub_post_id, '_wp_user_id', $user_id );
                update_post_meta( $sub_post_id, '_plan_id', $product->get_id() );
                update_post_meta( $sub_post_id, '_woo_order_id', $order_id );
                update_post_meta( $sub_post_id, '_status', 'active' );
                update_post_meta( $sub_post_id, '_next_payment_date', $next_payment );
                update_post_meta( $sub_post_id, '_expiry_date', $expiry_date );
            }
        }
    }
}
