<?php

namespace app\event;

use DateTime;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use support\Redis;
use think\facade\Db as ThinkDb;
use Webman\Event\Event;
use Workerman\Crontab\Crontab;

class ShopifyOrders
{
    const event = 'shopify:orders:event';
    const event_customer = 'shopify:customers:event';
    const SHOPIFY_API_URL = 'https://{storeName}.myshopify.com/admin/api/2024-07/orders.json';
    const SHOPIFY_API_URL_CUSTOMER = 'https://{storeName}.myshopify.com/admin/api/2024-07/customers.json';


    public function fetchCustomerIds($options = [])
    {
        $client  = new Client();
        $headers = [
            'X-Shopify-Access-Token' => $options['token']
        ];

        $customerIds = [];
        $orderIdsNotOrderCount = $orderIdsOrderCountOne = $orderIdsOrderCountOther = [];
        $pageInfo = "";

        while (true) {
            $params = [];
            if ($pageInfo !== "") {
                $params = [
                    'limit' => 200,
                    'page_info' => $pageInfo
                ];
            } else {
                $params = [
                    'limit' => 200,
                    'fields' => 'id,orders_count,total_spent,last_order_id,created_at',
//                    'created_at_min' => '2025-02-1T00:00:00-08:00',
//                    'created_at_max' => '2025-02-13T23:59:59-08:00',
                    'ids' => $options['aaa']
//                    'created_at_min' => '2025-02-14T00:00:00+00:00',
//                    'created_at_max' => '2025-02-14T23:59:59+00:00'
                ];
//
//                $createdAtMin = new DateTime($params['created_at_min']);
//                $createdAtMax = new DateTime($params['created_at_max']);
            }

//            dump($params,$headers);
            dump(str_replace("{storeName}", $options['storeName'], self::SHOPIFY_API_URL_CUSTOMER));

            try {
                $response = $client->get(str_replace("{storeName}", $options['storeName'], self::SHOPIFY_API_URL_CUSTOMER), [
                    'headers' => $headers,
                    'query' => $params
                ]);

                $data = json_decode($response->getBody(), true);

//                dump($data);

                // Loop through the orders and collect the order IDs
                foreach ($data['customers'] as $customer) {
                    $customerIds[]    = (string)$customer['id'];

//                    echo $order['id'] . PHP_EOL;  // Log order ID
                    // 将日期时间字符串转换为 DateTime 对象
                    $customerCreatedAt  = new DateTime($customer['created_at']);
                    $customerOrderCount = max($customer['orders_count'], 0);

                    // 判断 $orderCreatedAt 是否在 $createdAtMin 和 $createdAtMax 之间
//                    if ($customerOrderCount >= $createdAtMin && $orderCustomerCreatedAt <= $createdAtMax) {
//                        $orderIdsCreatedAt[] = (string)$order['id'];
//                    } else {
//                        $orderIdsNotCreatedAt[] = (string)$order['id'];
//                    }
//                    dump($customer['id'],$customerOrderCount);
                    if ($customerOrderCount == 0) {
                        $orderIdsNotOrderCount[] = (string)$customer['id'];
                    } else if ($customerOrderCount == 1) {
                        $orderIdsOrderCountOne[] = (string)$customer['id'];
                    } else {
                        $orderIdsOrderCountOther[] = (string)$customer['id'];
                    }

//                    if($order['customer'][''])
//                    $orderDatass[$customer['id']] = [
//                        'id' => $order['id'],
//                        'cus' => $order['customer']
//                    ];

                }
                $customerIds = array_unique($customerIds);
                dump('Total number of customer IDs: ' . count($customerIds));
                dump('customer IDs: ' . implode(',', $customerIds));

//                dump('Total number of orderIdsCreatedAt IDs: ' . count($orderIdsCreatedAt));
//                 dump('orderIdsCreatedAt IDs: ' . implode(',', $orderIdsCreatedAt));
//                dump('Total number of orderIdsNotCreatedAt IDs: ' . count($orderIdsNotCreatedAt));
//                dump('orderIdsNotCreatedAt IDs: ' . implode(',', $orderIdsNotCreatedAt));
                dump('Total number of customerIdsNotOrderCount IDs: ' . count($orderIdsNotOrderCount));
                dump('customerIdsNotOrderCount IDs: ' . implode(',', $orderIdsNotOrderCount));
                dump('Total number of customerIdsOrderCountOne IDs: ' . count($orderIdsOrderCountOne));
                dump('customerIdsOrderCountOne IDs: ' . implode(',', $orderIdsOrderCountOne));
                dump('Total number of customerOrderCountOther IDs: ' . count($orderIdsOrderCountOther));
                dump('customerOrderCountOther IDs: ' . implode(',', $orderIdsOrderCountOther));
// dump($orderDatass);
                // Check if there's a next page
                if (isset($response->getHeader('link')[0]) && strpos($response->getHeader('link')[0], 'rel="next"')) {
                    preg_match('/page_info=([^&]*)/', $response->getHeader('link')[0], $matches);
                    $pageInfo = $matches[1];
                } else {
                    break;  // Exit loop if no more pages
                }
            } catch (GuzzleException $e) {
                echo 'Error fetching Shopify orders: ' . $e->getMessage() . PHP_EOL;
                break;
            }
        }

//        echo 'Total number of order IDs: ' . count($orderIds) . PHP_EOL;
//        dump('Total number of order IDs: ' . count($orderIds));
//        dump('Order IDs: ' . implode(',', $orderIds));
        return ;
    }

//    const SHOPIFY_API_URL = 'https://fefc94-67.myshopify.com/admin/api/2024-07/orders.json';

    public function fetchOrderIds($options = [])
    {
        $client  = new Client();
        $headers = [
            'X-Shopify-Access-Token' => $options['token']
        ];

        $orderIds = [];
        $pageInfo = "";

        while (true) {
            $params = [];
            if ($pageInfo !== "") {
                $params = [
                    'limit' => 200,
                    'page_info' => $pageInfo
                ];
            } else {
                $params = [
                    'limit' => 200,
                    'status' => 'any',
                    'fields' => 'id,customer',
                    'created_at_min' => '2025-02-13T00:00:00-08:00',
                    'created_at_max' => '2025-02-13T23:59:59-08:00'
//                    'created_at_min' => '2025-02-14T00:00:00+00:00',
//                    'created_at_max' => '2025-02-14T23:59:59+00:00'
                ];

                $createdAtMin = new DateTime($params['created_at_min']);
                $createdAtMax = new DateTime($params['created_at_max']);
            }

//            dump($params,$headers);
            dump(str_replace("{storeName}", $options['storeName'], self::SHOPIFY_API_URL));

            try {
                $response = $client->get(str_replace("{storeName}", $options['storeName'], self::SHOPIFY_API_URL), [
                    'headers' => $headers,
                    'query' => $params
                ]);

                $data = json_decode($response->getBody(), true);

//                dump($data);

                // Loop through the orders and collect the order IDs
                foreach ($data['orders'] as $order) {
                    $orderIds[]    = (string)$order['id'];
                    $customerIds[] = (string)$order['customer']['id'];

//                    echo $order['id'] . PHP_EOL;  // Log order ID
                    // 将日期时间字符串转换为 DateTime 对象
//                    $orderCustomerCreatedAt = new DateTime($order['customer']['created_at']);
//                    $orderCustomerOrderCount = $order['customer']['orders_count']?? 0;

                    // 判断 $orderCreatedAt 是否在 $createdAtMin 和 $createdAtMax 之间
//                    if ($orderCustomerCreatedAt >= $createdAtMin && $orderCustomerCreatedAt <= $createdAtMax) {
//                        $orderIdsCreatedAt[] = (string)$order['id'];
//                    } else {
//                        $orderIdsNotCreatedAt[] = (string)$order['id'];
//                    }
//                    if($orderCustomerOrderCount == 0){
//                        $orderIdsNotOrderCount[] = (string)$order['id'];
//                    }else if($orderCustomerOrderCount == 1){
//                        $orderIdsOrderCountOne[] = (string)$order['id'];
//                    }else{
//                         $orderIdsOrderCountOther[] = (string)$order['id'];
//                    }

//                    if($order['customer'][''])
//                    $orderDatass[$order['id']] = [
//                        'id' => $order['id'],
//                        'cus' => $order['customer']
//                    ];

                }
                $customerIds = array_unique($customerIds);
                $customerIdsStr = implode(',', $customerIds);

                dump('Total number of customer IDs: ' . count($customerIds));
                dump('customer IDs: ' . $customerIdsStr);
                dump('Total number of order IDs: ' . count($orderIds));
                dump('Order IDs: ' . implode(',', $orderIds));
                Event::emit(ShopifyOrders::event_customer, ['storeName' => 'fefc94-67', 'token' => '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','aaa' => $customerIdsStr]);
//                dump('Total number of orderIdsCreatedAt IDs: ' . count($orderIdsCreatedAt));
//                 dump('orderIdsCreatedAt IDs: ' . implode(',', $orderIdsCreatedAt));
//                dump('Total number of orderIdsNotCreatedAt IDs: ' . count($orderIdsNotCreatedAt));
//                dump('orderIdsNotCreatedAt IDs: ' . implode(',', $orderIdsNotCreatedAt));
//                dump('orderIdsNotOrderCount IDs: ' . implode(',', $orderIdsNotOrderCount));
//                dump('orderIdsOrderCountOne IDs: ' . implode(',', $orderIdsOrderCountOne));
//                dump('orderIdsOrderCountOther IDs: ' . implode(',', $orderIdsOrderCountOther));
// dump($orderDatass);
                // Check if there's a next page
                if (isset($response->getHeader('link')[0]) && strpos($response->getHeader('link')[0], 'rel="next"')) {
                    preg_match('/page_info=([^&]*)/', $response->getHeader('link')[0], $matches);
                    $pageInfo = $matches[1];
                } else {
                    break;  // Exit loop if no more pages
                }
            } catch (GuzzleException $e) {
                echo 'Error fetching Shopify orders: ' . $e->getMessage() . PHP_EOL;
                break;
            }
        }

//        echo 'Total number of order IDs: ' . count($orderIds) . PHP_EOL;
//        dump('Total number of order IDs: ' . count($orderIds));
//        dump('Order IDs: ' . implode(',', $orderIds));
        return $orderIds;
    }

    // Method to save order data into bps.shopify_orders
    private function saveShopifyOrder($orderData)
    {
        // Define the table name dynamically
        $tableName = 'bps.shopify_orders';
        $tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'bps' . $tableName;

        // Prepare data for insertion
        $data = [
            'id' => $orderData['id'],
            'admin_graphql_api_id' => $orderData['admin_graphql_api_id'],
            'browser_ip' => $orderData['browser_ip'],
            'buyer_accepts_marketing' => $orderData['buyer_accepts_marketing'],
            'cancel_reason' => $orderData['cancel_reason'],
            'cancelled_at' => $orderData['cancelled_at'],
            'created_at' => $orderData['created_at'],
            'currency' => $orderData['currency'],
            'current_subtotal_price' => $orderData['current_subtotal_price'],
            'current_total_discounts' => $orderData['current_total_discounts'],
            'current_total_price' => $orderData['current_total_price'],
            'customer_email' => $orderData['customer_email'],
            'customer_name' => $orderData['customer_name'],
            'customer_phone' => $orderData['customer_phone']
        ];

        // SQL statement for inserting or updating order data
        $sql = "
            INSERT INTO {$tableName} (
                id,
                admin_graphql_api_id,
                browser_ip,
                buyer_accepts_marketing,
                cancel_reason,
                cancelled_at,
                created_at,
                currency,
                current_subtotal_price,
                current_total_discounts,
                current_total_price,
                customer_email,
                customer_name,
                customer_phone
            )
            VALUES (
                :id,
                :admin_graphql_api_id,
                :browser_ip,
                :buyer_accepts_marketing,
                :cancel_reason,
                :cancelled_at,
                :created_at,
                :currency,
                :current_subtotal_price,
                :current_total_discounts,
                :current_total_price,
                :customer_email,
                :customer_name,
                :customer_phone
            )
            ON CONFLICT (id)
            DO UPDATE SET
                admin_graphql_api_id = EXCLUDED.admin_graphql_api_id,
                browser_ip = EXCLUDED.browser_ip,
                buyer_accepts_marketing = EXCLUDED.buyer_accepts_marketing,
                cancel_reason = EXCLUDED.cancel_reason,
                cancelled_at = EXCLUDED.cancelled_at,
                created_at = EXCLUDED.created_at,
                currency = EXCLUDED.currency,
                current_subtotal_price = EXCLUDED.current_subtotal_price,
                current_total_discounts = EXCLUDED.current_total_discounts,
                current_total_price = EXCLUDED.current_total_price,
                customer_email = EXCLUDED.customer_email,
                customer_name = EXCLUDED.customer_name,
                customer_phone = EXCLUDED.customer_phone
        ";

        // Execute the SQL query
        ThinkDb::execute($sql, $data);
    }
}