<?php

namespace App\Http\Controllers\Admin\Service;

use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Models\ServiceCategory;
use App\Models\ServiceProvider;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;

class GetController extends Controller {
    public function getForm(Service $target, Request $request) {
		if ($request->ajax() == false) abort('404');
        if ($target == true) $components['target'] = $target;
		$components['providers'] = ServiceProvider::where('status', '1')->latest('id')->get();
        return view('admin.service.get.form', $components);
    }
    public function postForm(Service $target, PostRequest $request) {
		if ($request->ajax() == false) abort('404');
        if (Auth::guard('admin')->user()->level == 'Admin') {
			return response()->json([
				'status'  => false, 
				'type'    => 'alert',
                'message' => 'Aksi tidak diperbolehkan.'
			]);
        }
		// $input_data = [
        //     'provider_id'         => ($request->provider_id),
        //     'provider_service_id' => ($request->provider_service_id),
		// ];
        $message = '<br />';
        $checkProvider = ServiceProvider::find($request->provider_id);
        if ($checkProvider->name <> 'MANUAL') {
            $provider_config = json_decode($checkProvider->service_config, true);
            $parameter_values = [
                'provider_id'     => $checkProvider->provider_id,
                'provider_key'    => $checkProvider->provider_key,
                'provider_secret' => $checkProvider->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]; 
                }
            }
            try {
                $curl = Http::withoutVerifying()->asForm()->post($provider_config['endpoint'], $post_api);
                $curl_response = $curl->json();
                // $curl = post_curl($provider_config['endpoint'], $post_api);
                // $curl_response = json_decode($curl, true);
                if ($curl->ok() == true) {
                    $services = '$curl_response'.$provider_config['looping'].'';
                    eval('$services = '.$services.';');
                    foreach ($services as $service) {
                        foreach ($provider_config['response'] as $key => $value) {
                            try {
                                $key = '$service'.$value.'';
                                eval('$key = '.$key.';');
                            } catch (Exception $error) {
                                return response()->json([
                                    'status'  => false, 
                                    'type'    => 'alert',
                                    'message' => $error->getMessage()
                                ]);
                            }
                        }
                        $id = '$service'.$provider_config['response']['id'].'';
                        eval('$id = '.$id.';');
                        $servicesArray[] = $service;
                    }
                } else {
                    return response()->json([
                        'status'  => false, 
                        'type'    => 'alert',
                        'message' => 'Coba lagi nanti.'
                    ]);
                }
                if (count($servicesArray) == 0) {
                    return response()->json([
                        'status'  => false, 
                        'type'    => 'alert',
                        'message' => 'Tidak ada layanan tersedia.'
                    ]);
                }
                foreach ($servicesArray as $service) {
                    $check_service = Service::where([
                        ['provider_service_id', ($service['id'] ?? $service['service'])],
                        ['provider_id', $checkProvider->id]
                    ])->first();
                    if ($check_service == false) {
                        if (isset($id)) unset($id);
                        $id = '$service'.$provider_config['response']['id'].'';
                        eval('$id = '.$id.';');
                        if (isset($name)) unset($name);
                        $name = '$service'.$provider_config['response']['name'].'';
                        eval('$name = '.$name.';');
                        if ($provider_config['response']['category'] <> null) {
                            if (isset($category)) unset($category);
                            $category = '$service'.$provider_config['response']['category'].'';
                            eval('$category = '.$category.';');
                        }
                        if ($provider_config['response']['description'] <> null) {
                            if (isset($description)) unset($description);
                            $description = '$service'.$provider_config['response']['description'].'';
                            eval('$description = '.$description.';');
                        }
                        if (isset($price)) unset($price);
                        $price = '$service'.$provider_config['response']['price'].'';
                        eval('$price = '.$price.';');
                        if (isset($min)) unset($min);
                        $min = '$service'.$provider_config['response']['min'].'';
                        eval('$min = '.$min.';');
                        if (isset($max)) unset($max);
                        $max = '$service'.$provider_config['response']['max'].'';
                        eval('$max = '.$max.';');
                        if (isset($type)) unset($type);
                        $type = '$service'.$provider_config['response']['type'].'';
                        eval('$type = '.$type.';');
                        if (isset($refill)) unset($refill);
                        $refill = '$service'.$provider_config['response']['refill'].'';
                        eval('$refill = '.$refill.';');
                        $input_data['provider_id'] = $checkProvider->id;
                        $input_data['provider_service_id'] = ($service['id'] ?? $service['service']);
                        $input_data['category_id'] = $category;
                        if ($input_data['category_id'] == '') continue;
                        $category = ServiceCategory::where('name', $input_data['category_id'])->first();
                        if ($category == true) $input_data['category_id'] = $category->id;
                        if ($category == false) {
                            $insert_category = ServiceCategory::create([
                                'name' => $input_data['category_id']
                            ]);
                            $input_data['category_id'] = $insert_category->id;
                        }
                        $input_data['name'] = $name;
                        $input_data['name'] = strtr($input_data['name'], array(
                            ' ??' => '',
                        ));
                        $input_data['min'] = $min;
                        $input_data['max'] = $max;
                        $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 ($provider_config['response']['description'] <> '') {
                            $input_data['description'] = $description;
                        } else {
                            $input_data['description'] = '-';
                        }
                        $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';
                            }
                        }
                        $input_data['settings'] = json_encode([
                            'update_service'  => '1',
                            'name' 			  => '1',
                            'min_max' 		  => '1',
                            'price_profit' 	  => '1',
                            'reseller_price_profit' => '1',
                            'profit' 		  => '1',
                            'description'     => '1',
                            'custom_comments' => '1',
                            'refill_support'  => '1',
                            'status'  		  => '1',
                        ]);
                        $insert_data = Service::create($input_data);
                        $message .= '<span class="text-success">- '.($service['id'] ?? $service['service']).' = Berhasil (ID Layanan: '.($service['id'] ?? $service['service']).').</span><br />';
                    }
                }
            } catch (Exception $error) {
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => $error->getMessage()
                ]);
            }
        }
        return response()->json([
            'status'  => false, 
            'type'    => 'info',
            'message' => $message
        ]);
	}
}


class PostRequest extends FormRequest {
    protected function getValidatorInstance() {
		$instance = parent::getValidatorInstance();
        if ($instance->fails() == true) {
			foreach (json_decode($instance->errors(), true) as $item) {
				$message = '<br />';
				$message .= $item[0].'';
				$message_array[] = $message;
			}
			throw new HttpResponseException(response()->json([
				'status'  => false, 
				'type'    => 'alert',
				'message' => 'Mohon periksa input. '.implode('', $message_array).''
			]));
		}
        return parent::getValidatorInstance();
    }
    public function rules() {
        return [
            'provider_id'         => 'required|numeric|exists:service_providers,id',
        ];
    }
    public function attributes() {
		return [
            'provider_id'         => 'Penyedia',
		];
    }
}