<?php

namespace App\Jobs;

use App\Helpers\MatkaHookHelper;
use App\Models\AppData;
use App\Models\Market;
use App\Models\MarketResult;
use App\Services\MarketResultSetService;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use stdClass;

class AutoResultMarketNew implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct()
    {
        //
    }

    public function handle(): void
    {
        $marketResultSetService = new MarketResultSetService();
        $client = new Client();
        $url = env('AUTO_RESULT_NEW_API');
        $appData = AppData::first();
        // $apiToken = $appData->new_matka_api_token == NULL ? env('AUTO_RESULT_NEW_API_TOKEN') : $appData->new_matka_api_token;

        $apiToken = MatkaHookHelper::getMatkHookToken();

        try {
            // Preparing the request payload
            $data = [
                'username' => env('AUTO_RESULT_NEW_API_USERNAME'),
                'API_token' => $apiToken,
                'markte_name' => '',
                'date' => Carbon::today()->toDateString(),
            ];

            // Sending POST request with the data as form-data
            $response = $client->post($url, [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ],
                'form_params' => $data, // Use form_params for form-data
            ]);

            if ($response->getStatusCode() === 200) {
                $result = json_decode($response->getBody()->getContents());

                if ($result->status) {
                    //updateNewTokeninDb
                    $newToken = $result->refresh_token;
                    $appData->new_matka_api_token = $newToken;
                    $appData->save();

                    $dbMarkets = Market::where("auto_result", 1)->get();

                    $old_results = $result->old_result;
                    $today_results = $result->today_result;
                    // $today_results = $old_results;

                    foreach ($today_results as $apiMarket) {
                        $apiMarketName = $apiMarket->market_name;
                        $apiDate = Carbon::parse($apiMarket->aankdo_date)->toDateString();
                        $apiOpenPana = $apiMarket->aankdo_open;
                        $apiOpenDigit = $apiMarket->figure_open;
                        $apiClosePana = $apiMarket->aankdo_close;
                        $apiCloseDigit = $apiMarket->figure_close;

                        $dbMarket = $dbMarkets->where('api_key_name', $apiMarketName)->first();
                        if (!$dbMarket) {
                            Log::info('Market not found in the database:', ['Market Name' => $apiMarketName]);
                            continue;
                        }

                        $openResultFound = (isset($apiOpenPana) && $apiOpenPana != null) ? true : false;
                        $closeResultFound = (isset($apiClosePana) && $apiClosePana != null) ? true : false;

                        //now check if result already exist for apiDate, if not then proceed
                        $checkResult = $dbMarket->results()->where('result_date', $apiDate)->first();
                        if (($checkResult == NULL || $checkResult->open_pana == NULL) && $openResultFound) {
                            $request = new stdClass();
                            $request->date = $apiDate;
                            $request->market = $dbMarket->id;
                            $request->session = "open";
                            $request->pana = $apiOpenPana;
                            $request->digit = $apiOpenDigit;
                            $marketResultSetService->setResult($request, true);
                        }

                        $checkResult = $dbMarket->results()->where('result_date', $apiDate)->first();
                        if (($checkResult != NULL && $checkResult->close_pana == NULL) && $closeResultFound) {
                            $request = new stdClass();
                            $request->date = $apiDate;
                            $request->market = $dbMarket->id;
                            $request->session = "close";
                            $request->pana = $apiClosePana;
                            $request->digit = $apiCloseDigit;
                            $marketResultSetService->setResult($request, true);
                        }
                    }

                    foreach ($old_results as $apiMarket) {
                        $apiMarketName = $apiMarket->market_name;
                        $apiDate = Carbon::parse($apiMarket->aankdo_date)->toDateString();
                        $apiOpenPana = $apiMarket->aankdo_open;
                        $apiOpenDigit = $apiMarket->figure_open;
                        $apiClosePana = $apiMarket->aankdo_close;
                        $apiCloseDigit = $apiMarket->figure_close;

                        $dbMarket = $dbMarkets->where('api_key_name', $apiMarketName)->first();
                        if (!$dbMarket) {
                            Log::info('Market not found in the database:', ['Market Name' => $apiMarketName]);
                            continue;
                        }

                        $openResultFound = (isset($apiOpenPana) && $apiOpenPana != null) ? true : false;
                        $closeResultFound = (isset($apiClosePana) && $apiClosePana != null) ? true : false;

                        //now check if result already exist for apiDate, if not then proceed
                        $checkResult = $dbMarket->results()->where('result_date', $apiDate)->first();
                        if (($checkResult == NULL || $checkResult->open_pana == NULL) && $openResultFound) {
                            $request = new stdClass();
                            $request->date = $apiDate;
                            $request->market = $dbMarket->id;
                            $request->session = "open";
                            $request->pana = $apiOpenPana;
                            $request->digit = $apiOpenDigit;
                            $marketResultSetService->setResult($request, true);
                        }

                        $checkResult = $dbMarket->results()->where('result_date', $apiDate)->first();
                        if (($checkResult != NULL && $checkResult->close_pana == NULL) && $closeResultFound) {
                            $request = new stdClass();
                            $request->date = $apiDate;
                            $request->market = $dbMarket->id;
                            $request->session = "close";
                            $request->pana = $apiClosePana;
                            $request->digit = $apiCloseDigit;
                            $marketResultSetService->setResult($request, true);
                        }
                    }
                } else {
                    Log::info('Auto result API error: ' . $result->message);
                }
            }
        } catch (\Throwable $th) {
            // Log the exception and return it
            Log::error('Error in Auto Result API:', ['error' => $th->getMessage()]);
        }
    }
}
