<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\User;
use App\Models\UserBalanceLog;
use Illuminate\Console\Command;

class RefundCron extends Command {
    protected $signature = 'refund:cron';
    protected $description = 'Command description';
    public function __construct() {
        parent::__construct();
    }
    public function handle() {
        $orders = Order::whereIn('status', ['Error', 'Partial'])->where('is_refund', '0')->limit('50')->inRandomOrder()->get();
        if ($orders->count() == 0) return $this->info('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.'.';
            }
        }
    }
}
