<?php

namespace Bookingor\Integrations\WooCommerce;

use Bookingor\Helper\HelperControl;
use Bookingor\Integrations\Email\EmailNotification;

class WooCommercePaymentService
{
    private static $bookingorDb;
    public static $dp_prefix = "bookingor_";
    public static $data;
    public static  $bookedingorDb;


    public static function init()
    {
        add_action('woocommerce_checkout_order_created', [__CLASS__, 'save_booking_payload_to_order'], 10, 1);
    }

    public static function save_booking_payload_to_order($order)
    {
        $payload = null;
        if (function_exists('WC') && WC()->session) {
            $payload = WC()->session->get('design_final_booking');
        }
        if (!$payload && isset($_SESSION['design_final_booking'])) {
            $payload = $_SESSION['design_final_booking'];
        }
        if (!$payload && function_exists('WC') && WC()->cart) {
            foreach (WC()->cart->get_cart() as $cart_item) {
                if (isset($cart_item['design_final_booking'])) {
                    $payload = $cart_item['design_final_booking'];
                    break;
                }
            }
        }
        if ($payload) {
            $order->update_meta_data('_bookingor_temp_payload', $payload);
            $order->save();
        }
    }






    public static function get_wooCommerce_pages()
    {
        if (get_option("bookingor_settings_woocommcerce_payment_page") === "woocommerce-checkout") {
            return wc_get_checkout_url();
        } else {
            return wc_get_cart_url();
        }
    }
    /**
     * Retrieves all WooCommerce products.
     *
     * @return array An array of associative arrays. Each associative array contains the following keys:
     *               id, name, slug, short_description, image, price, currency_symbol
     */
    public static function get_all_wooCommerce_products()
    {
        if (!function_exists('is_plugin_active')) {
            include_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }
        if (is_plugin_active('woocommerce/woocommerce.php')) {
            $args = array(
                'post_type'      => 'product',
                'posts_per_page' => -1,
                'fields'         => 'ids',
            );
            $products = get_posts($args);
            $data = array_map(function ($product_id) {
                $product = wc_get_product($product_id);
                return (object) array(
                    'id'                => $product->get_id(),
                    'name'              => $product->get_name(),
                    'slug'              => $product->get_slug(),
                    'short_description' => $product->get_short_description(),
                    'image'             => $product->get_image_id(),
                    'price'             => $product->get_price(),
                    'currency_symbol'   => get_woocommerce_currency_symbol()
                );
            }, $products);
            return $data;
        } else {
            return array();
        }
    }
    /**
     * Retrieves all WooCommerce products.
     *
     * @return array An array of associative arrays. Each associative array contains the following keys:
     *               id, name, slug, short_description, image, price, currency_symbol
     */
    public function get_all_wooCoomerce_Product_front()
    {
        if (is_plugin_active('woocommerce/woocommerce.php')) {
            $args = array(
                'post_type'         => 'product',
                'posts_per_page'    => -1,
                'fields'            => 'ids',
            );
            $products = get_posts($args);
            $data = array();
            foreach ($products as $product_id) {
                $product = wc_get_product($product_id);
                $data[] = array(
                    'id'                  => $product->get_id(),
                    'name'                => $product->get_name(),
                    'slug'                => $product->get_slug(),
                    'short_description'   => $product->get_short_description(),
                    'image'               => $product->get_image_id(),
                    'price'               => $product->get_price(),
                    'currency_symbol'     => get_woocommerce_currency_symbol()
                );
            }
            $mergedData = array();
            foreach ($data as $array) {
                $mergedData = array_merge($mergedData, $array);
            }
            return $data;
        } else {
            return array();
        }
    }

    public static function bookingor_wc_cart_page()
    {
        // Ensure WooCommerce is available
        if (!function_exists('wc_get_cart_url') || !function_exists('WC')) {
            echo wp_json_encode("WooCommerce is not active");
            wp_die();
        }

        // Ensure cart is loaded in AJAX context
        if (function_exists('wc_load_cart')) {
            wc_load_cart();
        }

        // Get product ID and quantity
        $wc_product_id = isset($_REQUEST['product_id']) ? intval($_REQUEST['product_id']) : 0;
        $qty = isset($_REQUEST['quantity']) ? max(1, intval($_REQUEST['quantity'])) : 1;

        // Accept JSON string for design_final_booking and validate
        $raw = isset($_POST['design_final_booking']) ? wp_unslash($_POST['design_final_booking']) : '';
        $payload = null;
        if (is_string($raw) && $raw !== '') {
            $decoded = json_decode($raw, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $payload = $decoded; // store normalized array in session
            } else {
                // If it's not valid JSON, store the raw string (legacy)
                $payload = $raw;
            }
        }

        // Store in WooCommerce session (preferred)
        if (WC()->session) {
            WC()->session->set('design_final_booking', $payload);
        } else {
            // Fallback to PHP session only if WC session is unavailable
            if (session_status() !== PHP_SESSION_ACTIVE) {
                @session_start();
            }
            $_SESSION['design_final_booking'] = $payload;
        }

        // Add product to cart
        try {
            WC()->cart->add_to_cart($wc_product_id, $qty);
        } catch (\Exception $e) {
            echo wp_json_encode("Failed to add to cart: " . $e->getMessage());
            wp_die();
        }

        // Redirect to cart or checkout page
        $target = get_option("bookingor_settings_woocommcerce_payment_page");
        $redirect_url = ($target === "woocommerce-cart") ? wc_get_cart_url() : wc_get_checkout_url();

        echo wp_json_encode([
            'redirect_url' => $redirect_url,
        ]);
        wp_die();
    }
    /**
     * bookingor_wc_created
     *
     * Save booking data on payment complete
     *
     * @param int $order_id
     *
     * @return void
     */
    public static function bookingor_wc_created($order_id)
    {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        $order_status   = $order->get_status();
        $billing        = $order->get_address('billing');
        $first_name     = $billing['first_name'] ?? '';
        $last_name      = $billing['last_name'] ?? '';
        $email          = $order->get_billing_email();
        $phone          = $billing['phone'] ?? '';

        // Read from order meta first (safest for guests), fallback to sessions
        $design_final_booking_data = $order->get_meta('_bookingor_temp_payload');
        if (empty($design_final_booking_data)) {
            if (function_exists('WC') && WC()->session) {
                $design_final_booking_data = WC()->session->get('design_final_booking');
            }
            if (!$design_final_booking_data && isset($_SESSION['design_final_booking'])) {
                $design_final_booking_data = $_SESSION['design_final_booking'];
            }
        }

        global $wpdb;
        self::$bookingorDb = $wpdb;
        $default_booking_status = get_option('bookingor_settings_default_booking_status');
        $email_check = 'customer_email_' . $default_booking_status;
        $staff_email_check = 'employee_email_' . $default_booking_status;
        $booked_customer       = $wpdb->prefix . self::$dp_prefix . 'booked_appointment';
        $book_appointment      = $wpdb->prefix . self::$dp_prefix . 'confirm_booking_details';
        $customer_details      = $wpdb->prefix . self::$dp_prefix . 'customer_add';
        $customer_payment_data = $wpdb->prefix . self::$dp_prefix . 'customers_payment';
        $notifications         = $wpdb->prefix . self::$dp_prefix . 'notifications';

        $booking_ids = [];

        $existing_booking_ids = $order->get_meta('_bookingor_booking_ids');
        if (!empty($existing_booking_ids)) {
            return;
        }

        if (true) {
            $customer_first_name = $first_name;
            $customer_last_name  = $last_name;
            $customer_email_address = $email;
            $customer_phone      = $phone;
            $customer_payment_design = "woocommerce";

            if ($design_final_booking_data !== null) {
                $js = is_array($design_final_booking_data)
                    ? $design_final_booking_data
                    : json_decode($design_final_booking_data, true);

                if (!is_array($js)) {
                    // If still invalid, stop here
                    if (function_exists('WC') && WC()->session) {
                        WC()->session->__unset('design_final_booking');
                    }
                    if (isset($_SESSION['design_final_booking'])) {
                        unset($_SESSION['design_final_booking']);
                    }
                    return;
                }

                $customer_password = wp_generate_password(12, true);

                if (is_user_logged_in() && (in_array('bookingor_customer', wp_get_current_user()->roles) || in_array('administrator', wp_get_current_user()->roles))) {
                    $current_user = wp_get_current_user();
                    $user_email   = $current_user->user_email;

                    $customer_id = self::$bookingorDb->get_var(
                        $wpdb->prepare(
                            "SELECT customer_id FROM {$wpdb->prefix}bookingor_customer_add WHERE customer_email = %s",
                            $user_email
                        )
                    );

                    if (empty($customer_id)) {
                        self::$bookingorDb->insert(
                            $customer_details,
                            array(
                                'customer_first_name' => $customer_first_name,
                                'customer_last_name'  => $customer_last_name,
                                'customer_email'      => $customer_email_address,
                                'customer_phone'      => $customer_phone,
                            )
                        );
                        $customer_id = $wpdb->insert_id;
                    }

                    if (isset($js['repeat_details']) && !empty($js['repeat_details'])) {
                        foreach ($js['repeat_details'] as $value) {
                            self::$bookingorDb->insert(
                                $booked_customer,
                                array(
                                    'customer_get_id'    => $customer_id,
                                    'service_get_id'     => $js['get_service_id'],
                                    'staff_get_id'       => $js['get_staff_id'],
                                    'category_get_id'    => $js['category_id'],
                                    'location_get_id'    => '',
                                    'people_count'       => $js['selected_max_capacity'],
                                    'start_time'         => HelperControl::convert12To24($js['get_start_time']),
                                    'end_time'           => HelperControl::convert12To24($js['get_end_time']),
                                    'duration_service'   => $js['service_duration'],
                                    'picked_date'        => $value['date'],
                                    'picked_date_end'    => $js['get_time_all'],
                                    'discount_get_price' => '',
                                    'extra_get_price'    => $js['extra_total_price'] ?? '',
                                    'service_get_price'  => $value['repeat_cost'] ?? $value['repeatPrice'] ?? '',
                                    'tax_get_price'      => $js['service_tax'],
                                    'payment_method'     => $customer_payment_design,
                                    'appoint_status'     => $default_booking_status
                                )
                            );
                            $booked_id = $wpdb->insert_id;
                            $booking_ids[] = $booked_id;
                            self::$bookingorDb->insert(
                                $customer_payment_data,
                                array(
                                    'customer_get_id' => $customer_id,
                                    'book_get_id'     => $booked_id,
                                    'payment_method'  => $customer_payment_design,
                                    'payment_status'  => $order_status,
                                    'paid_amount'     => '',
                                )
                            );
                        }
                    }

                    // Main (non-repeat) booking row
                    self::$bookingorDb->insert(
                        $booked_customer,
                        array(
                            'customer_get_id'    => $customer_id,
                            'service_get_id'     => $js['get_service_id'],
                            'staff_get_id'       => $js['get_staff_id'],
                            'category_get_id'    => $js['category_id'],
                            'location_get_id'    => '',
                            'people_count'       => $js['selected_max_capacity'],
                            'start_time'         => HelperControl::convert12To24($js['get_start_time']),
                            'end_time'           => HelperControl::convert12To24($js['get_end_time']),
                            'duration_service'   => $js['service_duration'],
                            'picked_date'        => $js['get_full_date'],
                            'picked_date_end'    => $js['get_time_all'],
                            'discount_get_price' => '',
                            'extra_get_price'    => $js['extra_total_price'] ?? '',
                            'service_get_price'  => $js['service_price'],
                            'tax_get_price'      => $js['service_tax'],
                            'payment_method'     => $customer_payment_design,
                            'appoint_status'     => $default_booking_status
                        )
                    );
                    $booked_id = $wpdb->insert_id;
                    $booking_ids[] = $booked_id;

                    self::$bookingorDb->insert(
                        $customer_payment_data,
                        array(
                            'customer_get_id' => $customer_id,
                            'book_get_id'     => $booked_id,
                            'payment_method'  => $customer_payment_design,
                            'payment_status'  => $order_status,
                            'paid_amount'     => '',
                        )
                    );
                } else {
                    // Not logged in: create booking customer
                    self::$bookingorDb->insert(
                        $customer_details,
                        array(
                            'customer_first_name' => $customer_first_name,
                            'customer_last_name'  => $customer_last_name,
                            'customer_email'      => $customer_email_address,
                            'customer_phone'      => $customer_phone,
                        )
                    );
                    $customer_id = $wpdb->insert_id;

                    // Optional: create WP user
                    if (get_option('bookingor_settings_customer_create_account') === 'on') {
                        $user_id = wp_insert_user(
                            array(
                                'user_login'         => $customer_first_name . '_' . $customer_id,
                                'user_pass'          => $customer_password,
                                'first_name'         => $customer_first_name,
                                'last_name'          => $customer_last_name,
                                'user_email'         => $customer_email_address,
                                'role'               => 'bookingor_customer',
                                'user_status'        => 1,
                                'user_registered'    => current_time('mysql'),
                                'user_activation_key' => wp_generate_password(20, true)
                            )
                        );
                        if (!is_wp_error($user_id)) {
                            add_user_meta($user_id, 'first_name', $customer_first_name);
                            add_user_meta($user_id, 'last_name', $customer_last_name);
                            $subject = 'Your new account password';
                            $message = 'Your password is: ' . $customer_password;
                            if (!empty(get_option("bookingor_settings_email_type"))) {
                                EmailNotification::sendEmail($customer_email_address, $subject, $message);
                            }
                        }
                    }

                    if (isset($js['repeat_details']) && !empty($js['repeat_details'])) {
                        foreach ($js['repeat_details'] as $value) {
                            self::$bookingorDb->insert(
                                $booked_customer,
                                array(
                                    'customer_get_id'    => $customer_id,
                                    'service_get_id'     => $js['get_service_id'],
                                    'staff_get_id'       => $js['get_staff_id'],
                                    'category_get_id'    => $js['category_id'],
                                    'location_get_id'    => '',
                                    'people_count'       => $js['selected_max_capacity'],
                                    'start_time'         => HelperControl::convert12To24($js['get_start_time']),
                                    'end_time'           => HelperControl::convert12To24($js['get_end_time']),
                                    'duration_service'   => $js['service_duration'],
                                    'picked_date'        => $value['date'],
                                    'picked_date_end'    => $js['get_time_all'],
                                    'discount_get_price' => '',
                                    'extra_get_price'    => $js['extra_total_price'] ?? '',
                                    'service_get_price'  => $value['repeatPrice'] ?? $value['repeat_cost'] ?? '',
                                    'tax_get_price'      => $js['service_tax'],
                                    'payment_method'     => $customer_payment_design,
                                    'appoint_status'     => $default_booking_status
                                )
                            );
                            $booked_id = $wpdb->insert_id;
                            $booking_ids[] = $booked_id;
                            self::$bookingorDb->insert(
                                $customer_payment_data,
                                array(
                                    'customer_get_id' => $customer_id,
                                    'book_get_id'     => $booked_id,
                                    'payment_method'  => $customer_payment_design,
                                    'payment_status'  => $order_status,
                                    'paid_amount'     => '',
                                )
                            );
                        }
                    } else {
                        self::$bookingorDb->insert(
                            $booked_customer,
                            array(
                                'customer_get_id'    => $customer_id,
                                'service_get_id'     => $js['get_service_id'],
                                'staff_get_id'       => $js['get_staff_id'],
                                'category_get_id'    => $js['category_id'] ?? '',
                                'location_get_id'    => '',
                                'people_count'       => $js['selected_max_capacity'],
                                'start_time'         => HelperControl::convert12To24($js['get_start_time']),
                                'end_time'           => HelperControl::convert12To24($js['get_end_time']),
                                'duration_service'   => $js['service_duration'],
                                'picked_date'        => $js['get_full_date'],
                                'picked_date_end'    => $js['get_time_all'],
                                'discount_get_price' => '',
                                'extra_get_price'    => $js['extra_total_price'] ?? '',
                                'service_get_price'  => $js['service_price'],
                                'tax_get_price'      => $js['service_tax'],
                                'payment_method'     => $customer_payment_design,
                                'appoint_status'     => $default_booking_status
                            )
                        );
                        $booked_id = $wpdb->insert_id;
                        $booking_ids[] = $booked_id;
                        self::$bookingorDb->insert(
                            $customer_payment_data,
                            array(
                                'customer_get_id' => $customer_id,
                                'book_get_id'     => $booked_id,
                                'payment_method'  => $customer_payment_design,
                                'payment_status'  => $order_status,
                                'paid_amount'     => '',
                            )
                        );
                    }
                }

                if ($booked_id && $customer_id) {
                    self::$bookingorDb->update(
                        $customer_details,
                        array('book_get_id' => $booked_id),
                        array('customer_id' => $customer_id)
                    );
                }

                // FIX: Do not use prepare for table names. Only prepare values.
                $woo_content = self::$bookingorDb->get_row(
                    $wpdb->prepare(
                        "SELECT id, name_action, name, subject, text, send_to, type, paid_amount, tax_charges, coupon_id, book_date, book_time, status
                         FROM {$notifications}
                         WHERE name_action = %s",
                        $email_check
                    )
                );

                $staff_content = self::$bookingorDb->get_row(
                    $wpdb->prepare(
                        "SELECT id, name_action, name, subject, text, send_to, type, paid_amount, tax_charges, coupon_id, book_date, book_time, status
                         FROM {$notifications}
                         WHERE name_action = %s",
                        $staff_email_check
                    )
                );

                if ($booked_id && ($woo_content || $staff_content)) {
                    $bookingData     = HelperControl::get_last_booking_data($booked_id);
                    $categoryString  = $bookingData['categoryString'] ?? [];
                    $serviceString   = $bookingData['serviceString'] ?? [];
                    $staffString     = $bookingData['staffString'] ?? [];
                    $customerString  = $bookingData['customerString'] ?? [];
                    $bookedString    = $bookingData['bookedString'] ?? [];
                    $locationString  = $bookingData['locationString'] ?? [];
                    $businessString  = $bookingData['businessString'] ?? [];

                    if ($woo_content) {
                        $subject = EmailNotification::string_Placeholder_variable(
                            $categoryString,
                            $serviceString,
                            $staffString,
                            $customerString,
                            $bookedString,
                            $locationString,
                            $businessString,
                            $woo_content->subject
                        );
                        $body = EmailNotification::string_Placeholder_variable(
                            $categoryString,
                            $serviceString,
                            $staffString,
                            $customerString,
                            $bookedString,
                            $locationString,
                            $businessString,
                            $woo_content->text
                        );

                        EmailNotification::sendEmail($customer_email_address, $subject, $body);
                    }

                    if ($staff_content) {
                        $staff_email = $bookingData['staffString'][2] ?? $js['get_staff_email'] ?? '';
                        if (!empty($staff_email)) {
                            $subject_staff = EmailNotification::string_Placeholder_variable(
                                $categoryString,
                                $serviceString,
                                $staffString,
                                $customerString,
                                $bookedString,
                                $locationString,
                                $businessString,
                                $staff_content->subject
                            );
                            $body_staff = EmailNotification::string_Placeholder_variable(
                                $categoryString,
                                $serviceString,
                                $staffString,
                                $customerString,
                                $bookedString,
                                $locationString,
                                $businessString,
                                $staff_content->text
                            );

                            EmailNotification::sendEmail($staff_email, $subject_staff, $body_staff);
                        }
                    }
                }

                // Clear only our WC session key (do not destroy global session)
                if (function_exists('WC') && WC()->session) {
                    WC()->session->__unset('design_final_booking');
                }
                if (isset($_SESSION['design_final_booking'])) {
                    unset($_SESSION['design_final_booking']);
                }
            } else {
                // No booking payload – verify nonce if present
                if (isset($_POST['nonce'])) {
                    if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                        $response = [
                            'status' => 'error',
                            'message' => 'Nonce verification failed.'
                        ];
                        // You might want to log or handle this response
                    }
                }
                if (function_exists('WC') && WC()->session) {
                    WC()->session->__unset('design_final_booking');
                }
                if (isset($_SESSION['design_final_booking'])) {
                    unset($_SESSION['design_final_booking']);
                }
            }
        }

        if (!empty($booking_ids)) {
            $order->update_meta_data('_bookingor_booking_ids', $booking_ids);
            $order->save();
        }

        // Final safety: clear session key
        if (function_exists('WC') && WC()->session) {
            WC()->session->__unset('design_final_booking');
        }
        if (isset($_SESSION['design_final_booking'])) {
            unset($_SESSION['design_final_booking']);
        }
    }
}
WooCommercePaymentService::init();
