<?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 manageOrderColumns($columns)
    {
        $columns['location'] = 'Locatie';
        $columns['syncStatus'] = 'Status sincronizare Freya';
        $columns['syncError'] = 'Mesaj';
        return $columns;
    }

    public function manageOrderColumnsValue($column): void
    {
        /** @var WP_Post $post */
        global $post;

        if ($column == 'location') {
            echo get_post_meta($post->ID, 'location_name', true);
        }

        if ($column == 'syncStatus') {
            $stringStatus = get_post_meta($post->ID, '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 = get_post_meta($post->ID, '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;
        }

//        wp_enqueue_script('fss-order-ajax', fsPluginUrl . "assets/js/order-update.js", ["jquery", "json2"]);
//        wp_localize_script('fss-order-ajax', 'fssSettings', [
//            'apiUrl' => fsServiceUrl(true),
//            'ajaxUrl' => admin_url('admin-ajax.php'),
//            'orderId' => $order->get_id(),
//            'locationUid' => get_option('fs_option_settings')['fsDefaultLocationUid']
//        ]);

        ?>
        <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'];
        update_post_meta($order_id, 'freya-sync-error', "Se resincronizează...");
        update_post_meta($order_id, 'location_name', $res->payload->name);
        update_post_meta($order_id, 'location_uid', $res->payload->uid);
        update_post_meta($order_id, 'freya-sync-processed', "");
        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
    {
        // Add custom columns
        add_filter('manage_edit-shop_order_columns', [$this, 'manageOrderColumns'], 9999);

        // Get data for custom columns
        add_action('manage_shop_order_posts_custom_column', [$this, 'manageOrderColumnsValue']);

        // 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']);
    }
}
