<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use WC_Order;
use WP_Post;
use wpdb;

class AdminOrderService
{

    public function __construct()
    {
        $this->init();
    }

    public function add_fss_order_table_columns(array $columns): array
    {
        $columns['location'] = 'Locatie';
        $columns['syncStatus'] = 'Status sincronizare Freya';
        $columns['syncError'] = 'Mesaj';
        return $columns;
    }

    /**
     * @param string $column
     * @param int|WC_Order $good_library_design int before Woocommerce 8.0, WC_Order after 8.0, annoyingly
     * @return void
     */
    public function add_fss_order_table_content(string $column, $good_library_design): void
    {
        if (fss_get_woocommerce_major_version() < 8) {
            $order = $good_library_design;
        } else {
            $order = wc_get_order($good_library_design);
        }

        if ($column == 'location') {
            echo $order->get_meta("location_name", true);
        }

        if ($column === 'syncStatus') {
            $stringStatus = $order->get_meta("freya-sync-processed", true);

            if ($stringStatus === 'true') {
                echo "<mark class='order-status status-completed'><span>Sincronizată</span></mark>";
                return;
            }
            if ($stringStatus === 'false') {
                echo "<mark class='order-status status-failed'><span>Eșuată</span></mark>";
                return;
            }
            echo "<mark class='order-status status-processing'><span>Neprocesată</span></mark>";
        }

        if ($column == 'syncError') {
            $message = $order->get_meta("freya-sync-error", true);
            if (!$message) {
                echo "<span class='order-status status-completed fss-status'>Nu sunt erori</span>";
                return;
            }
            echo "<span class='order-status status-failed fss-status'>$message</span>";
        }
    }


    public function manageOrderFilters($postType): void
    {
        /** @var wpdb $wpdb */
        global $wpdb;

        if ($postType == 'shop_order') {
            $locationValues = $wpdb->get_results(
                "SELECT DISTINCT meta_value FROM $wpdb->postmeta pm  WHERE pm.meta_key  = 'location_name'",
                ARRAY_A
            );

            echo '<select name="location">';
            echo '<option value>Arata toate locatiile</option>';
            foreach ($locationValues as $location) {
                $checked = (isset($_GET['location']) && $_GET['location'] === $location['meta_value']) ? 'selected' : '';
                echo '<option value="' . $location['meta_value'] . '" ' . $checked . '>' . $location['meta_value'] . '</option>';
            }
            echo '</select>';

            // Filtru status sincronizare
            $syncStatusValues = $wpdb->get_results(
                "SELECT DISTINCT meta_value FROM $wpdb->postmeta pm  WHERE pm.meta_key  = 'freya-sync-processed' and meta_value <> '' ",
                ARRAY_A
            );
            echo '<select name="">';
            echo '<option value>Arata toate status-urile</option>';
            foreach ($syncStatusValues as $status) {
                $statusChecked = (isset($_GET['syncStatus']) && $_GET['syncStatus'] === $status['meta_value']) ? 'selected' : '';

                if ($status['meta_value'] == 'true') {
                    $label = 'Sincronizat';
                } else {
                    $label = 'Esuat';
                }

                echo '<option value="' . $status['meta_value'] . '" ' . $statusChecked . '>' . $label . '</option>';
            }
            echo '</select>';
        }
    }

    public function after_order_details(WC_Order $order): void
    {
        $error = $order->get_meta('freya-sync-processed');
        if (!isset($error) || $error === "true" || $error === "") {
            return;
        }

?>
        <div id="FS_ORDER_ID" data-id="<?php
                                        echo $order->get_id() ?>" class="hidden"></div>
        <button id="fsResyncOrder" style="margin-top: 10px" class="button button-primary" disabled type="button">
            Resincronizează
            comanda
        </button>
        <div id="fsResyncMessage" class="fss-notice hidden"></div>
<?php
    }

    public function handleQueryFilters($query): void
    {
        global $pagenow;

        if ($query->is_admin && $pagenow == 'edit.php' && isset($_GET['location']) && $_GET['location'] != '' && $_GET['post_type'] === 'shop_order') {
            $meta_key_query = array(
                array(
                    'key' => 'location_name',
                    'value' => esc_attr($_GET['location']),
                )
            );
            $query->set('meta_query', $meta_key_query);
        }

        if ($query->is_admin && $pagenow == 'edit.php' && isset($_GET['syncStatus']) && $_GET['syncStatus'] != '' && $_GET['post_type'] === 'shop_order') {
            $meta_key_query = array(
                array(
                    'key' => 'freya-sync-processed',
                    'value' => esc_attr($_GET['syncStatus']),
                )
            );
            $query->set('meta_query', $meta_key_query);
        }
    }

    public function resyncOrder(): void
    {
        check_ajax_referer('wp_rest', 'nonce');
        if (!isset($_POST['order_id']) || !isset($_POST['location_uid'])) {
            wp_send_json_error(null, 400);
            return;
        }

        $res = makeHttpGet('api/wp/getLocation?uid=' . $_POST['location_uid']);

        if (!$res->status) {
            wp_send_json_error($res->message, $res->statusCode ?? 500);
            return;
        }
        $order_id = $_POST['order_id'];
        $order = wc_get_order($order_id);
        if (!$order) {
            wp_send_json_error();
        }
        $order->update_meta_data("freya-sync-error", "Se resincronizează...");
        $order->update_meta_data("location_name", $res->payload->name);
        $order->update_meta_data("location_uid", $res->payload->uid);
        $order->update_meta_data("freya-sync-processed", "");
        $order->save_meta_data();
        wp_send_json_success();
    }

    /**
     * @ajax
     *
     * @return void
     */
    public function get_order_for_resync(): void
    {
        check_ajax_referer('wp_rest', 'nonce');
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            wp_send_json_error(null, 404);
            return;
        }
        if (!$_REQUEST['id']) {
            wp_send_json_error(null, 404);
            return;
        }

        $order = wc_get_order($_REQUEST['id']);
        if (!$order) {
            wp_send_json_error(null, 404);
            return;
        }

        $ret = [
            'locationUid' => $order->get_meta('location_uid'),
            'needsResync' => $order->get_meta('freya-sync-processed') === 'false',
        ];

        wp_send_json_success($ret);
    }

    public function init(): void
    {
        $woocommerce_major = fss_get_woocommerce_major_version();

        if ($woocommerce_major < 8) {
            $screen_id = "edit-shop_order";
        } else {
            $screen_id = "woocommerce_page_wc-orders";
        }
        // Add custom columns
        add_filter("manage_{$screen_id}_columns", [$this, 'add_fss_order_table_columns'], 10, 2);

        if ($woocommerce_major < 8) {
            $screen_id = "shop_order_posts";
        } else {
            $screen_id = "woocommerce_page_wc-orders";
        }
        // Get data for custom columns
        add_action("manage_{$screen_id}_custom_column", [$this, 'add_fss_order_table_content'], 10, 2);

        // Add filters for custom columns
        add_action('restrict_manage_posts', [$this, 'manageOrderFilters']);

        // Apply filters for custom columns
        add_action('pre_get_posts', [$this, 'handleQueryFilters']);

        // Add resync button to orders
        add_action('woocommerce_admin_order_data_after_order_details', [$this, 'after_order_details'], 20, 3);

        add_action('wp_ajax_nopriv_fss_resync_order', [$this, 'resyncOrder'], 1);
        add_action('wp_ajax_fss_resync_order', [$this, 'resyncOrder'], 1);

        add_action('wp_ajax_nopriv_fss_get_order_location', [$this, 'get_order_for_resync']);
        add_action('wp_ajax_fss_get_order_location', [$this, 'get_order_for_resync']);
    }
}
