<?php

namespace App\Http\Controllers\User;

use App\DataTables\User\OrderRefillDataTable;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderRefill;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderRefillController extends Controller {
    public function create(Order $target, Request $request) {
        if ($target->user_id <> Auth::user()->id) {
            return redirect()->back() ->with('result', [
                'alert'   => 'danger', 
                'title'   => 'Gagal', 
                'message' => 'Aksi tidak diperbolehkan.'
            ]);
        }
        if ($target->service_provider == true AND $target->service_provider->is_refill_support == '1' AND $target->service->is_refill_support == '1') {
            if ($target->status == 'Success' AND diff_date(now(), $target->created_at) > -30) {
                $check_data = OrderRefill::where([
                    ['user_id', $target->user_id],
                    ['order_id', $target->id],
                    ['status', 'Pending']
                ])->first();
                if ($check_data == true) {
                    return redirect()->back() ->with('result', [
                        'alert'   => 'danger', 
                        'title'   => 'Gagal', 
                        'message' => 'Anda masih memiliki Riwayat Refill berstatus Pending untuk Pesanan ini.'
                    ]);
                }
                $refill_response = false;
                $refill_id = '';
                if ($target->service_provider->name <> 'MANUAL') {
                    $provider_config = json_decode($target->service_provider->refill_config, true);
                    $parameter_values = [
                        'order_id'        => $target->provider_order_id,
                        'provider_id'     => $target->service_provider->provider_id,
                        'provider_key'    => $target->service_provider->provider_key,
                        'provider_secret' => $target->service_provider->provider_secret,
                    ];
                    foreach ($provider_config['request'] as $key => $value) {
                        if ($key == 'action') {
                            $post_api['action'] = $value;
                        } else {
                            $post_api[$value] = $parameter_values[$key]; 
                        }
                    }
                    try {
                        $curl = post_curl($provider_config['endpoint'], $post_api);
                        $curl_response = json_decode($curl, true);
                        if ($curl <> false) {
                            $get_refill_id = deltonsz($curl_response, to_array(json_decode($provider_config['response']['refill_id'])));
                            if (!is_array($get_refill_id)) {
                                $refill_response = true;
                                $refill_id = $get_refill_id;
                            }
                        } else {
                            return redirect()->back() ->with('result', [
                                'alert'   => 'danger', 
                                'title'   => 'Gagal', 
                                'message' => 'Pesanan gagal direfill.'
                            ]);
                        }
                    } catch (Exception $error) {
                        return redirect()->back() ->with('result', [
                            'alert'   => 'danger', 
                            'title'   => 'Gagal', 
                            'message' => 'Pesanan gagal direfill.'
                        ]);
                    }
                }
                if ($refill_response == false) {
                    return redirect()->back() ->with('result', [
                        'alert'   => 'danger', 
                        'title'   => 'Gagal', 
                        'message' => 'Pesanan gagal direfill.'
                    ]);
                } else {
                    $insert_data = OrderRefill::create([
                        'user_id'            => $target->user_id,
                        'order_id'           => $target->id,
                        'service_id'         => $target->service_id,
                        'provider_refill_id' => $refill_id
                    ]);
                    return redirect()->back() ->with('result', [
                        'alert'   => 'success', 
                        'title'   => 'Berhasil', 
                        'message' => 'Pesanan berhasil direfill.'
                    ]);
                }
            } else {
                return redirect()->back() ->with('result', [
                    'alert'   => 'danger', 
                    'title'   => 'Gagal', 
                    'message' => 'Aksi tidak diperbolehkan.'
                ]);
            }
        } else {
            return redirect()->back() ->with('result', [
                'alert'   => 'danger', 
                'title'   => 'Gagal', 
                'message' => 'Aksi tidak diperbolehkan.'
            ]);
        }
    }
    public function history(OrderRefillDataTable $dataTable) {
        $components['breadcrumb'] = (object) [
			'first' => 'Refill Pesanan',
			'second' => 'Refill'
		];
        $components['services'] = OrderRefill::where('user_id', Auth::user()->id)->distinct()->latest('service_id')->get(['service_id']);
        $components['statuses'] = ['Pending', 'Processing', 'Success', 'Error'];
        $components['created_at'] = OrderRefill::where('user_id', Auth::user()->id)->selectRaw('DATE(created_at) AS created_at')->distinct()->latest('created_at')->get();
        return $dataTable->render('user.order.refill_history', $components);
    }
    public function detail(OrderRefill $target, Request $request) {
		if ($request->ajax() == false) abort('404');
        return view('user.order.refill_detail', compact('target'));
    }
}
