<?php

namespace App\Jobs;

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\Http;
use Illuminate\Support\Facades\Log;
use stdClass;

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

    public function __construct()
    {
        //
    }

    public function handle(): void
    {
        $marketResultSetService = new MarketResultSetService();
        $url = env('AUTO_RESULT_D360_API_MH');
        try {

            $http_request = Http::withHeaders([
                "Content-Type" => "application/json",
            ])->timeout(60)
                ->post($url);
            $response = $http_request->json();

            if ($http_request->ok()) {

                if ($response['error']) {
                    Log::info('Auto result API error: ' . $response['message']);
                    return;
                }

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

                $old_results = $response['old_results'];
                $today_results = $response['today_results'];
                $all_results = array_merge($today_results, $old_results);

                foreach ($all_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;
                    $closeResultFound = isset($apiClosePana) && $apiClosePana !== null;

                    $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);
                    }

                    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: ' . $response['message']);
            }
        } catch (\Throwable $th) {
            // Log the exception and return it
            Log::error('Error in Auto Result API:', ['error' => $th->getMessage()]);
        }
    }
}
