<?php

namespace App\Jobs;

use App\Models\AppData;
use App\Models\DesawarMarket;
use App\Models\Market;
use App\Models\MarketResult;
use App\Services\DesawarResultSetService;
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 AutoResultDesawarMarketD360 implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct()
    {
        //
    }

    public function handle(): void
    {
        $desawarResultSetService = new DesawarResultSetService();
        $url = env('AUTO_RESULT_D360_API_DL');
        $date = Carbon::today()->toDateString();
        $dbMarkets = DesawarMarket::where("auto_result", 1)->get();

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

                $today_results = $response['today_results'];
                $old_results = $response['old_results'];

                $all_results = array_merge($today_results, $old_results);

                foreach ($all_results as $apiMarket) {
                    $apiMarketName = trim($apiMarket['market_name']);
                    $apiDate = Carbon::parse($apiMarket['aankdo_date'])->toDateString();
                    $jodi = $apiMarket['jodi'];

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

                    // Now check if result already exists for apiDate, if not then proceed
                    $checkResult = $dbMarket->results()->where('result_date', $apiDate)->first();
                    if ($checkResult === NULL) {
                        Log::info('DESAWAR: auto result api result set: ' . $dbMarket->name);

                        $request = new stdClass();
                        $request->date = $date;
                        $request->market = $dbMarket->id;
                        $request->digit = $jodi;
                        $desawarResultSetService->setResult($request, true);
                    }
                }
            } else {
                Log::info('Auto result API error: ' . $response['message']);
            }
        } catch (\Throwable $th) {
            Log::error('Error in Auto Result API:', ['error' => $th->getMessage()]);
        }
    }
}
