<?php

namespace App\Models;

use App\Http\Controllers\API\HomeAPIController;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MiddlewareContent extends Model
{
    use HasFactory;

    public $table = 'middleware_content';

    public $fillable = [
        'type',
        'method',
        'body',
        'response',
        'status',
        'company_id',
        'brand_id',
        'user_id',
        'batch'
    ];

    public static function sendPendingApis()
    {
        $controller = new HomeAPIController();

        // get requests
        $get_request = MiddlewareContent::find(56373);
        // dd($get_request->body);

        // get request body from DB
        $body = json_decode(trim($get_request->body), true);
        if (!MiddlewareContent::isRealTimeBatch($get_request->batch)) {
            if (isset($body['check_param'])) {
                $record = FoodicsMapping::where([
                    'chefadmin_id' => $body['check_param'],
                    'status' => 1
                ])->first();
                if (!empty($record)) {
                    $updateRecord = 1;
                    (explode('_', $get_request->type)[0] == 'create') ? $get_request->type = str_replace("create", "update", $get_request->type) : $updateRecord = 0;
                    if ($updateRecord) {
                        MiddlewareContent::where('id', $get_request->id)->update(['type' => $get_request->type]);
                    }
                }
            }
        }
        // dd($get_request->type);

        // Filter with mapping payload
        $result = $controller->handlePayload($body, $get_request->type);
        dd(json_decode($result));
        // Create guzzle client for api
        $client = new Client();

        $response_id = '123';
        foreach ($result as $res_step) {
            //handle dependent params in url
            if ($res_step['dependent']) {
                $url = preg_replace('/:([a-zA-Z0-9_]+)/', '$$', $res_step['url']);
                // dd($url);
                $dependent_params = explode(',', $res_step['dependent_params']);
                foreach ($dependent_params as $ind => $param) {
                    if ($param == 'response_id') {
                        $url = str_replace('$$', $response_id, $url, 1);
                    }
                }
            }
            if ($res_step['repetitive']) {
                foreach ($res_step['body'] as $step) {
                    try {
                        $response = $client->request($res_step->method, $res_step->url);

                        // Get the response body as a string
                        $body = $response->getBody()->getContents();

                        // Process the response data
                        // ...

                        // Optionally, you can check the response status code
                        $statusCode = $response->getStatusCode();
                        if ($statusCode === 200) {
                            // The request was successful
                        } else {
                            // Handle other status codes
                        }
                    } catch (\GuzzleHttp\Exception\RequestException $e) {
                        // Handle exceptions (e.g., network errors, 404 not found, etc.)
                        // You can access error information like $e->getMessage(), $e->getCode(), $e->getResponse()...
                    }
                }
            } else {
                try {
                    $response = $client->request($res_step->method, $res_step->url);

                    // Get the response body as a string
                    $body = $response->getBody()->getContents();

                    // Process the response data
                    // ...

                    // Optionally, you can check the response status code
                    $statusCode = $response->getStatusCode();
                    if ($statusCode === 200) {
                        // The request was successful
                    } else {
                        // Handle other status codes
                    }
                } catch (\GuzzleHttp\Exception\RequestException $e) {
                    // Handle exceptions (e.g., network errors, 404 not found, etc.)
                    // You can access error information like $e->getMessage(), $e->getCode(), $e->getResponse()...
                }
            }
        }
    }
    public static function isRealTimeBatch($batch_id)
    {
        return (explode('_', $batch_id)[0] == 'rt') ? true : false;
    }
}
