<?php

namespace App\Http\Controllers\Cronjob;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Service;
use App\Models\ServiceProvider;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Http;

class ServiceController extends Controller {
    public function update() {
        $serviceProviders = ServiceProvider::where('status', '1')->get();
        if ($serviceProviders->count() == 0) return print_r('Tidak ada penyedia');
        foreach ($serviceProviders as $serviceProvider) {
            $service = Service::where([
                ['provider_id', $serviceProvider->id],
            ])->count();
            if ($service == 0) continue;
            if ($serviceProvider->name <> 'MANUAL') {
                $provider_config = json_decode($serviceProvider->service_config, true);
                $parameter_values = [
                    'provider_id'     => $serviceProvider->provider_id,
                    'provider_key'    => $serviceProvider->provider_key,
                    'provider_secret' => $serviceProvider->provider_secret,
                ];
                if (isset($post_api)) unset($post_api);
                foreach ($provider_config['request'] as $key => $value) {
                    if ($key == 'action') {
                        $post_api['action'] = $value;
                    } else {
                        if ($value <> '') $post_api[$value] = $parameter_values[$key]; 
                    }
                }
                $curl = Http::withoutVerifying()->asForm()->post($provider_config['endpoint'], $post_api);
                $curl_response = $curl->json();
                if ($curl->ok() == true) {
                    $getServices = '$curl_response'.$provider_config['looping'].'';
                    eval('$getServices = '.$getServices.';');
                    foreach ($getServices as $getService) {
                        foreach ($provider_config['response'] as $key => $value) {
                            try {
                                $key = '$getService'.$value.'';
                                eval('$key = '.$key.';');
                            } catch (Exception $error) {
                                return response()->json([
                                    'status'  => false, 
                                    'type'    => 'alert',
                                    'message' => $error->getMessage()
                                ]);
                            }
                        }
                        $id = '$getService'.$provider_config['response']['id'].'';
                        eval('$id = '.$id.';');
                        $checkService = Service::where([
                            ['provider_id', $serviceProvider->id],
                            ['provider_service_id', $id]
                        ])->first();
                        if ($checkService == true) {
                            // $servicesArray[$id] = $getService;
                            if (json_decode($checkService->settings, true)['update_service'] == '1') {
                                if (json_decode($checkService->settings, true)['name'] == '1') {
                                    if (isset($name)) unset($name);
                                    $name = '$getService'.$provider_config['response']['name'].'';
                                    eval('$name = '.$name.';');
                                    $input_data['name'] = $name;
                                    $input_data['name'] = strtr($input_data['name'], array(
                                        ' MDN' => 'FP',
                                        ' MP' => 'FP',
                                    ));
                                }
                                if (json_decode($checkService->settings, true)['min_max'] == '1') {
                                    if (isset($min)) unset($min);
                                    $min = '$getService'.$provider_config['response']['min'].'';
                                    eval('$min = '.$min.';');
                                    if (isset($max)) unset($max);
                                    $max = '$getService'.$provider_config['response']['max'].'';
                                    eval('$max = '.$max.';');
                                    $input_data['min'] = $min;
                                    $input_data['max'] = $max;
                                }
                                if (json_decode($checkService->settings, true)['price_profit'] == '1') {
                                    if (isset($price)) unset($price);
                                    $price = '$getService'.$provider_config['response']['price'].'';
                                    eval('$price = '.$price.';');
                                    $input_data['price'] = $price;
                                    if ($provider_config['currency'] == 'USD') {
                                        $client = new Client();
                                        $currency = json_decode($client->request('GET', 'https://open.er-api.com/v6/latest/USD')->getBody()->getContents(), true);
                                        $input_data['price'] = $input_data['price'] * $currency['rates']['IDR'];
                                    }
                                    if ($provider_config['price_setting']['operator'] == '*') $input_data['price'] = ceil($input_data['price'] * $provider_config['price_setting']['value']);
                                    if ($provider_config['price_setting']['operator'] == '/') $input_data['price'] = ceil($input_data['price'] / $provider_config['price_setting']['value']);
                                    if ($provider_config['price_setting']['operator'] == '+') $input_data['price'] = ceil($input_data['price'] + $provider_config['price_setting']['value']);
                                    if ($provider_config['price_setting']['operator'] == '-') $input_data['price'] = ceil($input_data['price'] - $provider_config['price_setting']['value']);

                                    if ($provider_config['profit_setting']['operator'] == '*') $input_data['profit'] = ceil($input_data['price'] * $provider_config['profit_setting']['value']);
                                    if ($provider_config['profit_setting']['operator'] == '+') $input_data['profit'] = ceil(0 + $provider_config['profit_setting']['value']);
                                    if ($provider_config['profit_setting']['operator'] == '-') $input_data['profit'] = ceil(0 - $provider_config['profit_setting']['value']);
                                    if ($provider_config['profit_setting']['operator'] == '%') $input_data['profit'] = ceil($input_data['price'] * ($provider_config['profit_setting']['value']/100));
                                    $input_data['price'] = $input_data['price'] + $input_data['profit'];
                                }
                                if (json_decode($checkService->settings, true)['description'] == '1') {
                                    if ($provider_config['response']['description'] <> '') {
                                        if (isset($description)) unset($description);
                                        $description = '$getService'.$provider_config['response']['description'].'';
                                        eval('$description = '.$description.';');
                                        $input_data['description'] = $description;
                                    }
                                }
                                if (isset($type)) unset($type);
                                $type = '$getService'.$provider_config['response']['type'].'';
                                eval('$type = '.$type.';');
                                if (isset($refill)) unset($refill);
                                $refill = '$getService'.$provider_config['response']['refill'].'';
                                eval('$refill = '.$refill.';');
                                $input_data['type'] = 'Default';
                                if ($provider_config['other_value']['custom_comments'] <> '' AND $type == $provider_config['other_value']['custom_comments']) {
                                    $input_data['type'] = 'Custom Comments';
                                }
                                if ($provider_config['other_value']['comment_likes'] <> '' AND $type == $provider_config['other_value']['comment_likes']) {
                                    $input_data['type'] = 'Comment Likes';
                                }
                                if ($provider_config['other_value']['is_refill_support'] <> '') {
                                    if ($provider_config['other_value']['is_refill_support'] == 'true') {
                                        $input_data['is_refill_support'] = $refill == true ? '1' : '0';
                                    }
                                }
                                if (json_decode($checkService->settings, true)['status'] == '1') {
                                    $input_data['status'] = '1';
                                }
                                $update_service = $checkService->update($input_data);
                                if ($update_service == true) {
                                    print_r('Berhasil, ID: '.$checkService->id.' | Layanan: '.$checkService->name.' | Harga: '.$checkService->price.'');
                                    print_r('<br />');
                                } else {
                                    print_r('Gagal, ID: '.$checkService->id.' | Layanan: '.$checkService->name.' | Harga: '.$checkService->price.'');
                                    print_r('<br />');
                                }
                            }
                        }
                    }
                }
            }
        }
        // print("<pre>".print_r($servicesArray,true)."</pre>");
    }
}
