<?php
/**
 * The admin-specific functionality of the plugin.
 * class-wootrello-hook.php
 * * @link       http://javmah.tk
 * @since      1.0.0
 * @package    Wootrello
 * @subpackage Wootrello/admin
 * @author     javmah <jaedmah@gmail.com>
*/

# Include the helper class
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-wootrello-helpers.php';
# Include the Trello API class
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-wootrello-trello-api.php';

class Wootrello_Hooks {
    
    /**
     * Property to hold the instance of Wootrello_Helpers
     * @var Wootrello_Helpers
     */
    protected $helpers;

    /**
     * Property to hold the instance of Wootrello_Trello_API
     * @var Wootrello_Trello_API
     */
    protected $trelloApi;

    /**
     * The ID of this plugin.
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
    */
    private $plugin_name;

    /**
     * The version of this plugin.
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
    */
    private $version;

    /**
     * List of active plugins.
     * @since    1.0.0
     * @access   private
     * @var      array    $active_plugins    Active plugins in WordPress.
    */
    private $active_plugins = array();

    /**
     * Initialize the class and set its properties.
     * @since      1.0.0
     * @param      string    $plugin_name   The name of this plugin.
     * @param      string    $version       The version of this plugin.
    */
    public function __construct( $plugin_name, $version ) {
        # Set plugin name 
        $this->plugin_name   = $plugin_name;
        # Set plugin version 
        $this->version       = $version;
        # Get Active plugins 
        $this->active_plugins = get_option('active_plugins');
        # Create an instance of the Wootrello_Helpers class
        $this->helpers       = new Wootrello_Helpers();
        # Create an instance of the Wootrello_Trello_API class
        $this->trelloApi     = new Wootrello_Trello_API();
    }

    /**
	 * Admin notice function;
	 * @since    1.0.0
	*/
	public function wootrello_hooks_notice(){
		# testing is in Here 
		// echo"<pre>";


		// echo"</pre>";
	}


    /**
     * Data Extraction Method (The Source of Truth).
     * Extracts all available WooCommerce order data into a single array.
     * 
     * @since    3.4.0
     * @access   private
     * @param    int       $order_id    WooCommerce Order ID.
     * @param    string    $status_to   The new status (optional).
     * @return   array|bool             Extracted data array or false on failure.
    */
    private function get_all_order_data( $order_id, $status_to = '' ) {
        # 1. Get Order Object
        $order = wc_get_order( $order_id );
        if ( ! $order ) return false;

        # 2. Extract Basic Data
        $data = array(
            'orderID'                 => ( method_exists( $order, 'get_id' ) && is_int( $order->get_id() ) ) ? $order->get_id() : "",
            'cart_tax'                => ( method_exists( $order, 'get_cart_tax' ) && is_string( $order->get_cart_tax() ) ) ? $order->get_cart_tax() : "",
            'currency'                => ( method_exists( $order, 'get_currency' ) && is_string( $order->get_currency() ) ) ? $order->get_currency() : "",
            'discount_tax'            => ( method_exists( $order, 'get_discount_tax' ) && is_string( $order->get_discount_tax() ) ) ? $order->get_discount_tax() : "",
            'discount_total'          => ( method_exists( $order, 'get_discount_total' ) && is_string( $order->get_discount_total() ) ) ? $order->get_discount_total() : "",
            'fees'                    => ( method_exists( $order, 'get_fees' ) && ! empty( $order->get_fees() ) && is_array( $order->get_fees() ) ) ? json_encode( $order->get_fees() ) : "",
            'shipping_method'         => ( method_exists( $order, 'get_shipping_method' ) && is_string( $order->get_shipping_method() ) ) ? $order->get_shipping_method() : "",
            'shipping_tax'            => ( method_exists( $order, 'get_shipping_tax' ) && is_string( $order->get_shipping_tax() ) ) ? $order->get_shipping_tax() : "",
            'shipping_total'          => ( method_exists( $order, 'get_shipping_total' ) && is_string( $order->get_shipping_total() ) ) ? $order->get_shipping_total() : "",
            'subtotal'                => ( method_exists( $order, 'get_subtotal' ) && is_float( $order->get_subtotal() ) ) ? $order->get_subtotal() : "",
            'subtotal_to_display'     => ( method_exists( $order, 'get_subtotal_to_display' ) && is_string( $order->get_subtotal_to_display() ) ) ? $order->get_subtotal_to_display() : "",
            'total'                   => ( method_exists( $order, 'get_total' ) && is_string( $order->get_total() ) ) ? $order->get_total() : "",
            'total_discount'          => ( method_exists( $order, 'get_total_discount' ) && is_float( $order->get_total_discount() ) ) ? $order->get_total_discount() : "",
            'total_refunded'          => ( method_exists( $order, 'get_total_refunded' ) && is_float( $order->get_total_refunded() ) ) ? $order->get_total_refunded() : "",
            'total_tax_refunded'      => ( method_exists( $order, 'get_total_tax_refunded' ) && is_int( $order->get_total_tax_refunded() ) ) ? $order->get_total_tax_refunded() : "",
            'total_shipping_refunded' => ( method_exists( $order, 'get_total_shipping_refunded' ) && is_int( $order->get_total_shipping_refunded() ) ) ? $order->get_total_shipping_refunded() : "",
            'item_count_refunded'     => ( method_exists( $order, 'get_item_count_refunded' ) && is_int( $order->get_item_count_refunded() ) ) ? $order->get_item_count_refunded() : "",
            'total_qty_refunded'      => ( method_exists( $order, 'get_total_qty_refunded' ) && is_int( $order->get_total_qty_refunded() ) ) ? $order->get_total_qty_refunded() : "",
            'remaining_refund_amount' => ( method_exists( $order, 'get_remaining_refund_amount' ) && is_string( $order->get_remaining_refund_amount() ) ) ? $order->get_remaining_refund_amount() : "",
            'item_count'              => ( method_exists( $order, 'get_item_count' ) && is_int( $order->get_item_count() ) ) ? $order->get_item_count() : "",
            'status'                  => ! empty( $status_to ) ? $status_to : $order->get_status(),
        );

        # 3. Process Coupon Codes - Extract clean string
        $coupon_codes = "";
        if ( method_exists( $order, 'get_coupon_codes' ) ) {
            $coupons = $order->get_coupon_codes();
            if ( ! empty( $coupons ) && is_array( $coupons ) ) {
                $coupon_codes = implode( ', ', $coupons );
            }
        }
        $data['coupon_code'] = $coupon_codes;

        # 4. Process Tax Totals - Extract total tax amount as number
        $total_tax_amount = "";
        if ( method_exists( $order, 'get_tax_totals' ) ) {
            $tax_totals = $order->get_tax_totals();
            if ( ! empty( $tax_totals ) && is_array( $tax_totals ) ) {
                $tax_sum = 0;
                foreach ( $tax_totals as $tax ) {
                    if ( isset( $tax->amount ) ) {
                        $tax_sum += floatval( $tax->amount );
                    }
                }
                $total_tax_amount = $tax_sum > 0 ? number_format( $tax_sum, 2, '.', '' ) : "";
            }
        }
        $data['tax_totals'] = $total_tax_amount;

        # 5. Process Taxes - Extract clean string or leave empty
        $taxes_data = "";
        if ( method_exists( $order, 'get_total_tax' ) ) {
            $total_tax = $order->get_total_tax();
            if ( ! empty( $total_tax ) && $total_tax > 0 ) {
                $taxes_data = $total_tax;
            }
        }
        $data['taxes'] = $taxes_data;
        $data['total_tax'] = $taxes_data; // Keep this consistent

        # 6. Process Order Items
        $items = array();
        $cart_items_weight = array();
        $order_categories = array(); 

        if ( is_array( $order->get_items() ) ) { 
            foreach ( $order->get_items() as $item_id => $item_data ) {
                $items[$item_id]['product_id']   = ( method_exists( $item_data, "get_product_id" ) && is_int( $item_data->get_product_id() ) ) ? $item_data->get_product_id() : ""; 
                $items[$item_id]['variation_id'] = ( method_exists( $item_data, "get_variation_id" ) && is_int( $item_data->get_variation_id() ) ) ? $item_data->get_variation_id() : ""; 
                $items[$item_id]['product_sku']  = ( empty( $items[$item_id]['variation_id'] ) ) ? get_post_meta( $items[$item_id]['product_id'], '_sku', true ) : get_post_meta( $items[$item_id]['variation_id'], '_sku', true ); 
                $items[$item_id]['product_name'] = ( method_exists( $item_data, "get_name" ) && is_string( $item_data->get_name() ) ) ? $item_data->get_name() : ""; 
                $items[$item_id]['qty']          = ( method_exists( $item_data, "get_quantity" ) && is_int( $item_data->get_quantity() ) ) ? $item_data->get_quantity() : ""; 
                $items[$item_id]['product_qty_price'] = ( method_exists( $item_data, "get_total" ) && is_string( $item_data->get_total() ) ) ? $item_data->get_total() : ""; 
                
                # Get product categories
                $items[$item_id]['product_categories'] = "";
                if ( ! empty( $items[$item_id]['product_id'] ) ) {
                    $terms = wp_get_post_terms( $items[$item_id]['product_id'], 'product_cat', array( 'fields' => 'names' ) );
                    if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
                        $items[$item_id]['product_categories'] = $terms;
                        $order_categories = array_merge( $order_categories, $terms );
                    }
                }
                
                # Get Weight
                if ( method_exists( $item_data->get_product(), 'get_weight' ) && ! empty( $item_data->get_product()->get_weight() ) ) {
                    $weight = $item_data->get_product()->get_weight() * $items[$item_id]['qty'];
                    $items[$item_id]['product_weight'] = $weight;
                    $cart_items_weight[] = $weight;
                }else{
                    $items[$item_id]['product_weight'] = "";
                }
            }
        }

        $data['items']              = ( $items ) ? $items : "";
        $data['cart_items_weight']  = array_sum( $cart_items_weight );
        $data['product_categories'] = ! empty( $order_categories ) ? implode( ', ', array_unique( $order_categories ) ) : "";

        # 7. Dates & Additional Info
        $date_format = "F j, Y, g:i:s A T";
        $data['date_created']   = ( method_exists( $order, 'get_date_created' ) && ! empty( $order->get_date_created() ) ) ? $order->get_date_created()->date( $date_format ) : "";
        $data['date_modified']  = ( method_exists( $order, 'get_date_modified' ) && ! empty( $order->get_date_modified() ) ) ? $order->get_date_modified()->date( $date_format ) : "";
        $data['date_completed'] = ( method_exists( $order, 'get_date_completed' ) && ! empty( $order->get_date_completed() ) ) ? $order->get_date_completed()->date( $date_format ) : "";
        $data['date_paid']      = ( method_exists( $order, 'get_date_paid' ) && ! empty( $order->get_date_paid() ) ) ? $order->get_date_paid()->date( $date_format ) : "";

        $data['downloadable_items']  = ( method_exists( $order, 'get_downloadable_items' ) && ! empty( $order->get_downloadable_items() ) && is_array( $order->get_downloadable_items() ) ) ? json_encode( $order->get_downloadable_items() ) : "";
        $data['user']                = ( method_exists( $order, 'get_user' ) && ! empty( $order->get_user() ) && is_object( $order->get_user() ) ) ? $order->get_user()->user_login . " - " . $order->get_user()->user_email : "";
        $data['customer_id']         = ( method_exists( $order, 'get_customer_id' ) && is_int( $order->get_customer_id() ) ) ? $order->get_customer_id() : "";
        $data['user_id']             = ( method_exists( $order, 'get_user_id' ) && is_int( $order->get_user_id() ) ) ? $order->get_user_id() : "";
        $data['customer_ip_address'] = ( method_exists( $order, 'get_customer_ip_address' ) && is_string( $order->get_customer_ip_address() ) ) ? $order->get_customer_ip_address() : "";
        $data['customer_user_agent'] = ( method_exists( $order, 'get_customer_user_agent' ) && is_string( $order->get_customer_user_agent() ) ) ? $order->get_customer_user_agent() : "";
        $data['created_via']         = ( method_exists( $order, 'get_created_via' ) && is_string( $order->get_created_via() ) ) ? $order->get_created_via() : "";
        $data['customer_note']       = ( method_exists( $order, 'get_customer_note' ) && is_string( $order->get_customer_note() ) ) ? $order->get_customer_note() : "";

        # 8. Billing & Shipping Info
        $billing_fields = array('first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'email', 'phone');
        foreach ( $billing_fields as $f ) {
            $bill_fn = "get_billing_$f";
            $data["billing_$f"] = ( method_exists( $order, $bill_fn ) && is_string( $order->$bill_fn() ) ) ? $order->$bill_fn() : "";
        }

        $shipping_fields = array('first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country');
        foreach ( $shipping_fields as $f ) {
            $ship_fn = "get_shipping_$f";
            $data["shipping_$f"] = ( method_exists( $order, $ship_fn ) && is_string( $order->$ship_fn() ) ) ? $order->$ship_fn() : "";
        }
        
        $data['address']                      = ( method_exists( $order, 'get_address' ) && is_array( $order->get_address() ) ) ? json_encode( $order->get_address() ) : "";
        $data['shipping_address_map_url']     = ( method_exists( $order, 'get_shipping_address_map_url' ) && is_string( $order->get_shipping_address_map_url() ) ) ? $order->get_shipping_address_map_url() : "";
        $data['formatted_billing_full_name']  = ( method_exists( $order, 'get_formatted_billing_full_name' ) && is_string( $order->get_formatted_billing_full_name() ) ) ? $order->get_formatted_billing_full_name() : "";
        $data['formatted_shipping_full_name'] = ( method_exists( $order, 'get_formatted_shipping_full_name' ) && is_string( $order->get_formatted_shipping_full_name() ) ) ? $order->get_formatted_shipping_full_name() : "";
        $data['formatted_billing_address']    = ( method_exists( $order, 'get_formatted_billing_address' ) && is_string( $order->get_formatted_billing_address() ) ) ? $order->get_formatted_billing_address() : "";
        $data['formatted_shipping_address']   = ( method_exists( $order, 'get_formatted_shipping_address' ) && is_string( $order->get_formatted_shipping_address() ) ) ? $order->get_formatted_shipping_address() : "";

        # 9. Payment & URLs
        $data['payment_method']               = ( method_exists( $order, 'get_payment_method' ) && is_string( $order->get_payment_method() ) ) ? $order->get_payment_method() : "";
        $data['payment_method_title']         = ( method_exists( $order, 'get_payment_method_title' ) && is_string( $order->get_payment_method_title() ) ) ? $order->get_payment_method_title() : "";
        $data['transaction_id']               = ( method_exists( $order, 'get_transaction_id' ) && is_string( $order->get_transaction_id() ) ) ? $order->get_transaction_id() : "";
        $data['checkout_payment_url']         = ( method_exists( $order, 'get_checkout_payment_url' ) && is_string( $order->get_checkout_payment_url() ) ) ? $order->get_checkout_payment_url() : "";
        $data['checkout_order_received_url']  = ( method_exists( $order, 'get_checkout_order_received_url' ) && is_string( $order->get_checkout_order_received_url() ) ) ? $order->get_checkout_order_received_url() : "";
        $data['cancel_order_url']             = ( method_exists( $order, 'get_cancel_order_url' ) && is_string( $order->get_cancel_order_url() ) ) ? $order->get_cancel_order_url() : "";
        $data['cancel_order_url_raw']         = ( method_exists( $order, 'get_cancel_order_url_raw' ) && is_string( $order->get_cancel_order_url_raw() ) ) ? $order->get_cancel_order_url_raw() : "";
        $data['cancel_endpoint']              = ( method_exists( $order, 'get_cancel_endpoint' ) && is_string( $order->get_cancel_endpoint() ) ) ? $order->get_cancel_endpoint() : "";
        $data['view_order_url']               = ( method_exists( $order, 'get_view_order_url' ) && is_string( $order->get_view_order_url() ) ) ? $order->get_view_order_url() : "";
        $data['edit_order_url']               = ( method_exists( $order, 'get_edit_order_url' ) && is_string( $order->get_edit_order_url() ) ) ? $order->get_edit_order_url() : "";

        # 10. Support for Checkout Field Editor Pro (3rd party custom fields)
        if ( method_exists( $this->helpers, 'wootrello_woo_checkout_field_editor_pro_fields' ) ) {
            $custom_fields = $this->helpers->wootrello_woo_checkout_field_editor_pro_fields();
            if ( isset( $custom_fields[0] ) && $custom_fields[0] === true ) {
                foreach ( $custom_fields[1] as $field ) {
                    $key = $field['name'];
                    $data[$key] = $order->get_meta( $key ) ?: $order->get_meta( '_' . $key );
                }
            }
        }

        return $data;
    }

    /**
     * Core Automation Processor.
     * Manages settings lookup, duplicate prevention, and API execution.
     * @since    3.4.0
     * @access   private
     * @param    int       $order_id         The WooCommerce Order ID.
     * @param    string    $status           Target status to check settings for.
     * @param    string    $manual_settings  Optional base64 encoded settings for AJAX calls.
     * @return   array                       Success/Failure status and message.
     */
    private function process_automation( $order_id, $status) {
        # 1. Get the full data object
        $full_data = $this->get_all_order_data( $order_id, $status );
        if ( ! $full_data ) return array( false, "Order not found." );

        # 2. Call Trello API to create card
        $result = $this->trelloApi->wootrello_create_trello_card( $status, $full_data );

        # 3. Record history on success
        if ( $result === true ) {
            $history[] = $status;
            update_post_meta( $order_id, 'wootrello_status', $history );
        }

        return array( true, "Processed successfully." );
    }

    /**
     * Hook: WooCommerce order status changed.
     * @since    1.0.0
     */
    public function wootrello_woocommerce_order_status_changed( $order_id, $from, $to ) {
        return $this->process_automation( $order_id, $to );
    }

    /**
	 * woocommerce_new_orders New Order  HOOK's callback function
	 * I'M USE THIS FOR ADMIN FRONT -> woocommerce_thankyou HOOK for FRONT END
	 * @since     1.0.0
	 * @param     int     $order_id     Order ID
	*/
	public function wootrello_woocommerce_new_order_admin( $order_id ){
        $order = wc_get_order( $order_id );
        if ( ! $order ) return;
        return $this->process_automation( $order_id, $order->get_status() );
    }

    /**
     * Hook: WooCommerce checkout order processed (New Order).
     * @since    1.0.0
    */
    public function wootrello_woocommerce_new_order_checkout( $order_id ) {
        $order = wc_get_order( $order_id );
        if ( ! $order ) return;
        return $this->process_automation( $order_id, $order->get_status() );
    }

    /**
     * Hook: AJAX handler for single order card creation.
     * @since    3.0.0
     */
    public function wootrello_ajax_single_order() {
        if ( wp_verify_nonce( $_POST['security'], 'wootrello-ajax-nonce' ) ) {
            # Check Permissions - Allow Admins and Shop Managers
            if ( ! current_user_can( 'edit_shop_orders' ) ) {
                echo json_encode( array( false, "Permission denied." ) );
                exit();
            }
            # getting the AJAX value
            $orderID 		 = sanitize_text_field( trim( $_POST['orderID'] ));
            $relatedSettings = sanitize_text_field( trim( $_POST['relatedSettings'] ));
            // Process the automation
            $res = $this->process_automation($orderID, $relatedSettings);
            echo json_encode( $res );
        }
        exit();
    }


}
