<?php

namespace App\Http\Controllers\Cronjob;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\User;
use App\Models\UserBalanceLog;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class OrderController extends Controller {
    public function refund() {
        $orders = Order::whereIn('status', ['Error', 'Partial'])->where('is_refund', '0')->limit('50')->inRandomOrder()->get();
        if ($orders->count() == 0) return print_r('Tidak ada pesanan yang gagal.');
        foreach ($orders as $value) {
            $amount_refund = ($value['price'] / $value['quantity']) * $value['remains'];
            $minus_profit = ($value['profit'] / $value['quantity']) * $value['remains'];
            if ($value['remains'] == 0 OR $value['remains'] > $value['quantity']) {
                $amount_refund = $value['price'];
                $minus_profit = $value['profit'];
            }
            $update_data = Order::where('id', $value['id'])->update([
                'profit'     => $value['profit'] - $minus_profit,
                'is_refund'  => '1',
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            $check_user = User::find($value['user_id']);
            if ($check_user == true) {
                $first_balance = $check_user->balance;
                $last_balance = $check_user->balance + $amount_refund;
                $add_balance = $check_user->update([
                    'balance' => $last_balance,
                ]);
                $balance_logs = UserBalanceLog::create([
                    'user_id'       => $value['user_id'],
                    'type'          => 'Plus',
                    'action'        => 'Refund',
                    'amount'        => $amount_refund,
                    'first_balance' => $first_balance,
                    'last_balance'  => $last_balance,
                    'description'   => 'Pengembalian Dana Pesanan #'.$value['id'].'.',
                ]);
                print 'Berhasil, ID: '.$value['id'].' | Jumlah: Rp '.$amount_refund.'.';
            }
        }
    }
    public function status() {
        $orders = Order::whereIn('status', ['Pending', 'Processing'])->limit('150')->inRandomOrder()->get();
        if ($orders->count() == 0) return print_r('Tidak ada pesanan yang harus diperbarui.');
        foreach ($orders as $order) {
            if ($order->service_provider == false) continue;
            $order_response = false;
            $order_status = $order->status;
            $order_remains = $order->remains;
            $order_start_count = $order->start_count;
            if ($order->service_provider->name <> 'MANUAL') {
                $provider_config = json_decode($order->service_provider->status_config, true);
                $parameter_values = [
                    'order_id'        => $order->provider_order_id,
                    'provider_id'     => $order->service_provider->provider_id,
                    'provider_key'    => $order->service_provider->provider_key,
                    'provider_secret' => $order->service_provider->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]; 
                    }
                }
                if (isset($statuses)) unset($statuses);
                foreach ($provider_config['status_value'] as $key => $value) {
                    $statuses[strtolower($value)] = $key;
                }
                try {
                    $curl = Http::withoutVerifying()->asForm()->post($provider_config['endpoint'], $post_api);
                    $curl_response = $curl->json();
                    if ($curl->ok() == true) {
                        $order_response = true;
                        $status = '$curl_response'.$provider_config['response']['status'].'';
                        eval('$status = '.$status.';');
                        $start_count = '$curl_response'.$provider_config['response']['start_count'].'';
                        eval('$start_count = '.$start_count.';');
                        $remains = '$curl_response'.$provider_config['response']['remains'].'';
                        eval('$remains = '.$remains.';');
                        $order_status = is_string($status) ? (isset($statuses[strtolower($status)]) ? $statuses[strtolower($status)] : $order->status) : $order->status;
                        $order_start_count = is_numeric($start_count) ? $start_count : $order->start_count;
                        $order_remains = is_numeric($remains) ? $remains : $order->remains;
                    } 
                } catch (Exception $error) {
                    $order_response = false;
                    print_r('Berhasil, ID: '.$order->id.' | Status: '.$order_status.'.');
                }
            }
            if ($order_response == false) {
                print_r($curl_response);
                print_r('Berhasil, ID: '.$order->id.' | Status: '.$order_status.'.');
            } else {
                $order_status = ucfirst($order_status);
                $check_user = User::find($order['user_id']);
                if ($check_user == true AND json_decode($check_user->notification)->order == '1' AND $order_status <> $order->status) {
                    $email_details = [
                        'content' => [
                            'id'         => $order->id,
                            'service'    => $order->service ? $order->service->name : null,
                            'target'     => $order->target,
                            'quantity'   => $order->quantity,
                            'price'      => $order->price,
                            'status'     => $order_status,
                            'source'     => $order->is_api == '1' ? 'API' : 'WEB',
                            'ip_address' => $order->ip_address,
                        ],
                        'receiver' => [
                            'email' => $check_user->email,
                            'name'  => $check_user->full_name,
                        ]
                    ];
                    send_email($email_details, 'Informasi Pesanan - '.website_config('main')->website_name.'', 'user.mail.notification.order');
                }
                $update_data = Order::where('id', $order->id)->update([
                    'status'              => $order_status,
                    'start_count'         => $order_start_count,
                    'remains'             => $order_remains,
                    'provider_status_log' => $curl,
                    'updated_at'          => date('Y-m-d H:i:s'),
                ]);
                print_r('Berhasil, ID: '.$order->id.' | Status: '.$order_status.'.');
            }
        }
    }
}
