<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use WC_Order;

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 (!is_int($good_library_design)) {
            $order = $good_library_design;
        } else {
            $order = wc_get_order($good_library_design);
        }

        if (!$order || is_bool($order)) {
            return;
        }

        switch ($column) {
            case 'location':
                echo $order->get_meta("location_name");
                break;
            case 'syncStatus': {
                    $stringStatus = $order->get_meta("freya-sync-processed");

                    switch ($stringStatus) {
                        case 'true':
                            echo "<mark class='order-status status-completed'><span>Sincronizată</span></mark>";
                            break;
                        case 'false':
                            echo "<mark class='order-status status-failed'><span>Eșuată</span></mark>";
                            break;
                        case 'old':
                            echo "<mark class='order-status status-processing'><span>Comandă veche</span></mark>";
                            break;
                        default:
                            echo "<mark class='order-status status-processing'><span>Neprocesată</span></mark>";
                            break;
                    }

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


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

    //     /** @var "yes"|"no" $hasHpos */
    //     $hasHpos = get_option('woocommerce_custom_orders_table_enabled', "no");

    //     if ($postType !== "shop_order") {
    //         return;
    //     }
    //     dd($postType);

    //     $tableName = $hasHpos === 'yes'
    //         ? "{$wpdb->prefix}wc_orders_meta"
    //         : $wpdb->postmeta;

    //     $locationValues = $wpdb->get_results(
    //         "SELECT DISTINCT meta_value FROM $tableName 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 $tableName pm WHERE pm.meta_key = 'freya-sync-processed' and pm.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
    {
?>
        <div id="FS_ORDER_ID"
            data-id="<?php echo $order->get_id() ?>"></div>
    <?php
        $this->add_resync_message($order);
        $this->add_order_location($order);
    }

    public function email_order_details(WC_Order $order, bool $sent_to_admin, string $plain_text, $email): void
    {
        if (!$sent_to_admin) {
            return;
        }

        $this->add_order_location($order);
    }

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

    ?>
        <p id="FS_ORDER_ID" data-id="<?php
                                        echo $order->get_id() ?>" class="hidden"></p>
        <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
    }

    private function add_order_location(WC_Order $order): void
    {
        $location = $order->get_meta('location_name');

        if (is_null($location) || strlen($location) === 0) {
            return;
        }

    ?>
        <p style="margin-top: 1rem">Locația de servire: <strong><?php echo $location ?></strong></p>
<?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);

        // 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('woocommerce_email_order_details', [$this, 'email_order_details', 20, 4]);

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