<?php

namespace App\Console\Commands;

use App\Models\BankMutation;
use App\Models\Deposit;
use App\Models\User;
use App\Models\UserBalanceLog;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Mail;

class DepositCron extends Command {
    protected $signature = 'deposit:cron';
    protected $description = 'Command description';
    public function __construct() {
        parent::__construct();
    }
    public function handle() {
        $deposits = Deposit::where([
            ['status', 'Pending']
        ])->limit('50')->inRandomOrder()->get();
        if ($deposits->count() == 0) return $this->info('Tidak ada deposit pending.');
        foreach ($deposits as $item) {
            if ($item->deposit_method == false) {
                $item->update([
                    'status'     => 'Canceled',
                    'updated_at' => Carbon::now()
                ]);
                $check_user = User::find($item['user_id']);
                if ($check_user == true AND json_decode($check_user->notification)->deposit == '1') {
                    $details = [
                        'name'       => $check_user->full_name,
                        'id'         => $item->id,
                        'method'     => $item->deposit_method ? $item->deposit_method->name.' ('.$item->deposit_method->payment.' - '.$item->deposit_method->type.')' : null,
                        'amount'     => $item->amount,
                        'status'     => 'Canceled',
                        'ip_address' => $item->ip_address,
                    ];
                    $this->send_email_deposit($details, $check_user->email);
                }
                $this->info('Deposit dibatalkan! ID: '.$item->id.'. <br />');
            } else {
                if (diff_date(now(), $item->created_at) < 0) {
                    $item->update([
                        'status'     => 'Canceled',
                        'updated_at' => Carbon::now()
                    ]);
                    $check_user = User::find($item['user_id']);
                    if ($check_user == true AND json_decode($check_user->notification)->deposit == '1') {
                        $email_details = [
                            'content' => [
                                'id'         => $item->id,
                                'method'     => $item->deposit_method ? $item->deposit_method->name.' ('.$item->deposit_method->payment.' - '.$item->deposit_method->type.')' : null,
                                'amount'     => $item->amount,
                                'status'     => 'Canceled',
                                'ip_address' => $item->ip_address,
                            ],
                            'receiver' => [
                                'email' => $check_user->email,
                                'name'  => $check_user->full_name,
                            ]
                        ];
                        send_email($email_details, 'Informasi Deposit - '.website_config('main')->website_name.'', 'user.mail.notification.deposit');
                    }
                    $this->info('Deposit dibatalkan! ID: '.$item->id.'. <br />');
                } else {   
                    if ($item->deposit_method->type == 'Auto' AND !in_array($item->deposit_method->payment, ['Pulsa'])) {
                        $deposit_response = false;
                        $deposit_message = 'Gagal! Tidak ada aksi yang dilakukan.';
                        if ($item->deposit_method->is_tripay == '1' AND $item->reference <> '') {
                            $header_api = ["Authorization: Bearer ".website_config('tripay_payment')->api_key];
                            $post_api = [
                                'reference' => $item->reference
                            ];
                            $curl = tripay_curl('https://tripay.co.id/api/transaction/detail', $header_api, $post_api, 'get');
                            $curl_response = json_decode($curl, true);
                            if (isset($curl_response['success']) AND $curl_response['success'] == false) {
                                $deposit_message = $curl_response['message'];
                            } else {
                                if ($curl_response['data']['status'] == 'PAID') {
                                    $check_user = User::find($item['user_id']);
                                    if ($check_user == false) {
                                        $deposit_message = 'Gagal! Pengguna tidak ditemukan.';
                                    } else {
                                        $deposit_response = true;
                                        $deposit_message = 'Berhasil! ID: '.$item->id.' | Jumlah: Rp '.$item->balance.'';
                                    }
                                }
                            }
                        } elseif ($item->deposit_method->is_midtrans == '1' AND $item->reference <> '') {
                            $header_api = [
                                'Accept: application/json',
                                'Content-Type: application/json',
                                'Authorization: Basic '.base64_encode(website_config('midtrans_payment')->server_key.':').'',
                            ];
                            $post_api = [
                                'reference' => $item->reference
                            ];
                            $curl = midtrans_curl('https://api.midtrans.com/v2/'.$item->reference.'/status', $header_api, $post_api, 'get');
                            $curl_response = json_decode($curl, true);
                            if (!isset($curl_response['transaction_status'])) {
                                $deposit_message = 'Gagal.';
                            } else {
                                if ($curl_response['transaction_status'] == 'settlement') {
                                    $check_user = User::find($item['user_id']);
                                    if ($check_user == false) {
                                        $deposit_message = 'Gagal! Pengguna tidak ditemukan.';
                                    } else {
                                        $deposit_response = true;
                                        $deposit_message = 'Berhasil! ID: '.$item->id.' | Jumlah: Rp '.$item->balance.'';
                                    }
                                } elseif ($curl_response['transaction_status'] == 'expire') {
                                    $item->update([
                                        'status'     => 'Canceled',
                                        'updated_at' => Carbon::now()
                                    ]);
                                    $deposit_message = 'Deposit kadaluarsa.';
                                } elseif ($curl_response['transaction_status'] == 'cancel') {
                                    $item->update([
                                        'status'     => 'Canceled',
                                        'updated_at' => Carbon::now()
                                    ]);
                                    $deposit_message = 'Deposit dibatalkan.';
                                }
                            }
                        } else {
                            $check_mutation = BankMutation::where([
                                ['amount', $item->amount],
                                ['is_read', '0']
                            ])->first();
                            if ($check_mutation == false) {
                                $deposit_message = 'Gagal! Mutasi untuk deposit ini tidak ditemukan.';
                            } else {
                                $check_user = User::find($item['user_id']);
                                if ($check_user == false) {
                                    $deposit_message = 'Gagal! Pengguna tidak ditemukan.';
                                } else {
                                    $check_mutation->update([
                                        'is_read'    => '1',
                                        'updated_at' => Carbon::now()
                                    ]);
                                    $deposit_response = true;
                                    $deposit_message = 'Berhasil! ID: '.$item->id.' | Jumlah: Rp '.$item->balance.'';
                                }
                            }
                        }
                        if ($deposit_response == false) {
                             $this->info($deposit_message);
                        } else {
                            $item->update([
                                'status'     => 'Success',
                                'updated_at' => Carbon::now()
                            ]);
                            $first_balance = $check_user->balance;
                            $last_balance = $check_user->balance + $item->balance;
                            $add_balance = $check_user->update([
                                'balance' => $last_balance,
                            ]);
                            if ($check_user == true AND json_decode($check_user->notification)->deposit == '1') {
                                $email_details = [
                                    'content' => [
                                        'id'         => $item->id,
                                        'method'     => $item->deposit_method ? $item->deposit_method->name.' ('.$item->deposit_method->payment.' - '.$item->deposit_method->type.')' : null,
                                        'amount'     => $item->amount,
                                        'status'     => 'Success',
                                        'ip_address' => $item->ip_address,
                                    ],
                                    'receiver' => [
                                        'email' => $check_user->email,
                                        'name'  => $check_user->full_name,
                                    ]
                                ];
                                send_email($email_details, 'Informasi Deposit - '.website_config('main')->website_name.'', 'user.mail.notification.deposit');
                            }
                            UserBalanceLog::create([
                                'user_id'       => $item->user_id,
                                'type'          => 'Plus',
                                'action'        => 'Deposit',
                                'amount'        => $item->balance,
                                'first_balance' => $first_balance,
                                'last_balance'  => $last_balance,
                                'description'   => 'Deposit #'.$item->id.'.',
                            ]);
                            $this->info($deposit_message);
                        }
                    }
                }
            }
        }
    }
    public function send_email_order($details = [], $to = '') {
        config(['mail.mailers.smtp.username' => website_config('smtp')->username]);
        config(['mail.mailers.smtp.password' => website_config('smtp')->password]);
        config(['mail.mailers.smtp.encryption' => website_config('smtp')->encryption]);
        config(['mail.mailers.smtp.port' => website_config('smtp')->port]);
        config(['mail.mailers.smtp.host' => website_config('smtp')->host]);
        config(['mail.from.address' => website_config('smtp')->from]);
        config(['mail.from.name' => website_config('main')->website_name]);
        try {
            Mail::send('user.mail.notification.order', $details, function($message) use ($details, $to) {
                $message
                 ->to($to, $details['name'])
                 ->from(config('mail.from.address'), config('mail.from.name'))
                 ->subject('Informasi Pesanan - '.website_config('main')->website_name.'');
             });
            return true;
        } catch (Exception $message) {
            return true;
        }
    }
    public function send_email_deposit($details = [], $to = '') {
        config(['mail.mailers.smtp.username' => website_config('smtp')->username]);
        config(['mail.mailers.smtp.password' => website_config('smtp')->password]);
        config(['mail.mailers.smtp.encryption' => website_config('smtp')->encryption]);
        config(['mail.mailers.smtp.port' => website_config('smtp')->port]);
        config(['mail.mailers.smtp.host' => website_config('smtp')->host]);
        config(['mail.from.address' => website_config('smtp')->from]);
        config(['mail.from.name' => website_config('main')->website_name]);
        try {
            Mail::send('user.mail.notification.deposit', $details, function($message) use ($details, $to) {
                $message
                 ->to($to, $details['name'])
                 ->from(config('mail.from.address'), config('mail.from.name'))
                 ->subject('Informasi Deposit - '.website_config('main')->website_name.'');
             });
            return true;
        } catch (Exception $message) {
            return true;
        }
    }
}
