<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Transaction;
use App\Models\UserCoinBalance;
use Carbon\Carbon;

class CronController extends Controller {
    public function returnAmount() {
        $general            = gs();
        $general->last_cron = Carbon::now()->toDateTimeString();
        $general->save();

        $orders = Order::approved()
            ->with('user', 'miner')
            ->whereHas('user')
            ->where('period_remain', '>=', 1)
            ->where('last_paid', '<=', Carbon::now()->subHours(24)->toDateTimeString())
            ->get();

        foreach ($orders as $order) {
            $returnAmount = rand($order->min_return_per_day * 100000000, $order->max_return_per_day * 100000000) / 100000000;

            $ucb          = UserCoinBalance::where('user_id', $order->user_id)->where('miner_id', $order->miner_id)->first();
            if (!$ucb) {
                continue;
            }

            $ucb->balance += $returnAmount;
            $ucb->save();

            $order->period_remain -= 1;
            $order->last_paid = Carbon::now();
            $order->save();

            $trx = getTrx();

            $transaction               = new Transaction();
            $transaction->user_id      = $order->user_id;
            $transaction->amount       = $returnAmount;
            $transaction->post_balance = getAmount($ucb->balance);
            $transaction->charge       = 0;
            $transaction->trx_type     = '+';
            $transaction->details      = 'Daily return amount for the plan ' . $order->plan_details->title;
            $transaction->trx          = $trx;
            $transaction->currency     = $order->miner->coin_code;
            $transaction->remark       = 'return_amount';
            $transaction->save();

            $maintenanceCost = $returnAmount * $order->maintenance_cost / 100;
            $ucb->balance -= $maintenanceCost;

            $ucb->save();

            $transaction               = new Transaction();
            $transaction->user_id      = $order->user_id;
            $transaction->amount       = $maintenanceCost;
            $transaction->post_balance = getAmount($ucb->balance);
            $transaction->charge       = 0;
            $transaction->trx_type     = '-';
            $transaction->details      = 'Deducted as maintenance charge';
            $transaction->trx          = $trx;
            $transaction->currency     = $order->miner->coin_code;
            $transaction->remark       = 'maintenance_cost';
            $transaction->save();
        }

        return 'Cron executed successfully';
    }
}
