<?php

namespace App\Jobs;

use App\Models\Checkout;
use App\Models\OrderMeta;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CreateWooCommerceOrder implements ShouldQueue
{
    use Queueable;
    private $orderData;
    private $user;
    /**
     * Create a new job instance.
     */
    public function __construct(array $orderData, $user)
    {
        $this->orderData = $orderData;
        $this->user = $user;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $apiUrl = config('services.woocommerce.url');
        $consumerKey =  config('services.woocommerce.consumer_key');
        $consumerSecret = config('services.woocommerce.consumer_secret');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->orderData));
        curl_setopt($ch, CURLOPT_USERPWD, $consumerKey . ":" . $consumerSecret);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            Log::info('Error:' . curl_error($ch));
        } else {
            $responseArray = json_decode($response, true);
            if (isset($responseArray['id'])) {
                $orderId = $responseArray['id'];
                $orderId = $response['id'];
                $options = DB::select("SELECT option_value FROM wp_options WHERE option_name= 'wt_last_order_number'");
                $currentValue = (int)$options[0]->option_value;
                $newValue = $currentValue + 1;
                DB::update("UPDATE wp_options SET option_value = ? WHERE option_name = 'wt_last_order_number'", [$newValue]);
                $stateType = $this->user->mmtax;
                if ($stateType == 'EX') {
                    $metaValueST = 'EX';
                } elseif ($this->orderData['shipping']['state'] == 'IL') {
                    $metaValueST =  'IL';
                } else {
                    $metaValueST =  'OS';
                }
                $metaData = [
                    ['post_id' => $orderId, 'meta_key' => 'mm_field_TXC', 'meta_value' => $metaValueST],
                    ['post_id' => $orderId, 'meta_key' => '_order_number', 'meta_value' => $newValue],
                ];
                foreach ($metaData as $meta) {
                    OrderMeta::insert($meta);
                }
                

                $checkout = Checkout::where('user_id', $this->user->ID)->first();
                $checkout->delete();
            }
            else {
                Log::error('Order creation failed: ' . $response);
            }
        }
        curl_close($ch);
    }
}
