<?php

namespace App\Console\Commands;

use App\Models\MiddlewareContent;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use GuzzleHttp\Exception\RequestException;


class CallIntegrationAPI extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'integration:call';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Call /api/integration/{id} for records with status=1';

    /**
     * Execute the console command.
     */

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Get the start time
        $startTime = now();

        $client = new Client();

        // Define the maximum duration (1 minute)
        $maxDuration = now()->addMinute();

        // Get records from MiddlewareContent with status = 1, sorted by asc
        $limit = env('MW_CONTENT_LIMIT');
        $records = MiddlewareContent::where('status', 1)->orderBy('id', 'asc')->limit($limit)->get();

        foreach ($records as $record) {
            if (now()->gte($maxDuration)) {
                \Log::info('1 minute limit reached.');
                break;
            }
            $id = $record->id;

            // $headers = [
            //     'Accept' => 'application/json',
            //     'Content-Type' => 'application/json',
            //     'X-Custom-Header' => '$2a$12$fwR2SjLn5d0Y9qbDHac2eOaQeOE.D7DRWMmWSJh6d5pY3Nkq5ByAe'
            // ];

            try {
                $response = $client->get('https://foodics.sadaynaal.com/api/integration/' . $id);

                // Handle successful response here.
                // $statusCode = $response->getStatusCode();
                $body = $response->getBody()->getContents();
                $data = json_decode($body, true);

                \Log::info(json_encode(['id' => $id, 'response' => $data]));

                // Perform actions with $data.
            } catch (RequestException $e) {
                // Handle request exceptions (e.g., network errors, 4xx or 5xx status codes).
                $response = $e->getResponse();
                $statusCode = $response->getStatusCode();
                $errorBody = $response->getBody()->getContents();
                // Handle the error as needed.

                \Log::info(json_encode(['id' => $id, 'response' => $errorBody]));
            } catch (Exception $e) {
                // Handle other exceptions.
                // For example, if there's an issue with the request code.
                // Handle other exceptions as needed.
            }
        }

        $this->info('Integration API calls completed.');
    }
}
