<?php

namespace App\Http\Controllers\Admin;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Models\MobileOperator;
use App\Models\MobileRecharge;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Http\Request;

class MobileRechargeController extends Controller
{
    public function pending()
    {
        $pageTitle       = 'Pending Mobile Recharge';
        $mobileRecharges = $this->mobileRechargeData('pending');
        return view('admin.mobile_recharge.all', compact('pageTitle', 'mobileRecharges'));
    }

    public function approved()
    {
        $pageTitle       = 'Approved Mobile Recharge';
        $mobileRecharges = $this->mobileRechargeData('approved');
        return view('admin.mobile_recharge.all', compact('pageTitle', 'mobileRecharges'));
    }

    public function rejected()
    {
        $pageTitle       = 'Rejected Mobile Recharge';
        $mobileRecharges = $this->mobileRechargeData('rejected');
        return view('admin.mobile_recharge.all', compact('pageTitle', 'mobileRecharges'));
    }

    public function all()
    {
        $pageTitle          = 'All Mobile Recharge';
        $mobileRechargeData = $this->mobileRechargeData(summary: true);
        $mobileRecharges    = $mobileRechargeData['data'];
        $summary            = $mobileRechargeData['summary'];
        $pending            = $summary['pending'];
        $approved           = $summary['approved'];
        $rejected           = $summary['rejected'];
        $all                = $summary['all'];
        return view('admin.mobile_recharge.all', compact('pageTitle', 'mobileRecharges', 'pending', 'approved', 'rejected', 'all'));
    }

    private function mobileRechargeData($scope = null, $summary = false)
    {
        $mobileRecharges = $scope ? MobileRecharge::$scope() : MobileRecharge::query();
        $mobileRecharges = $mobileRecharges->searchable(['user:username', 'mobileOperator:name', 'trx'])->dateFilter()->with('mobileOperator', 'user', 'getTrx');

        if (!$summary) {
            return $mobileRecharges = $mobileRecharges->orderBy('id', 'DESC')->paginate(getPaginate());
        } else {
            $pending  = clone $mobileRecharges;
            $approved = clone $mobileRecharges;
            $rejected = clone $mobileRecharges;

            $pendingSummary  = $pending->pending()->sum('amount');
            $approvedSummary = $approved->approved()->sum('amount');
            $rejectedSummary = $rejected->rejected()->sum('amount');
            $allSummary      = $mobileRecharges->sum('amount');

            return [
                'data'    => $mobileRecharges->orderBy('id', 'desc')->paginate(getPaginate()),
                'summary' => [
                    'pending'  => $pendingSummary,
                    'approved' => $approvedSummary,
                    'rejected' => $rejectedSummary,
                    'all'      => $allSummary,
                ],
            ];
        }
    }

    public function changeStatus(Request $request)
    {
        $request->validate([
            'id'      => 'required',
            'status'  => 'required|in:1,2',
            'message' => 'required_if:status,==,2',
        ]);

        $mobileRecharge = MobileRecharge::where('status', Status::PENDING)->findOrFail($request->id);
        $mobileOperator = $mobileRecharge->mobileOperator;
        $getTrx         = $mobileRecharge->getTrx;
        $user           = User::findOrFail($mobileRecharge->user_id);

        if ($request->status == Status::APPROVED) {
            $mobileRecharge->status = Status::APPROVED;
            $mobileRecharge->save();

            notify($user, 'MOBILE_RECHARGE_APPROVE', [
                'amount'       => showAmount($mobileRecharge->amount, currencyFormat: false),
                'charge'       => showAmount($getTrx->charge, currencyFormat: false),
                'mobile'       => $mobileRecharge->mobile,
                'operator'     => $mobileOperator->name,
                'trx'          => $getTrx->trx,
                'time'         => showDateTime($mobileRecharge->created_at, 'd/M/Y @h:i a'),
                'post_balance' => showAmount($getTrx->post_balance, currencyFormat: false),
            ]);

            referralCommission($user, $mobileRecharge->amount, $getTrx->trx, 'mobile_recharge');

            $notify[] = ['success', 'Mobile recharge has been approved successfully'];
            return back()->withNotify($notify);
        }

        $mobileRecharge->status         = Status::REJECTED;
        $mobileRecharge->admin_feedback = $request->message;
        $mobileRecharge->save();

        $user->balance += $getTrx->amount;
        $user->save();

        $transaction                = new Transaction();
        $transaction->user_id       = $user->id;
        $transaction->user_type     = 'USER';
        $transaction->before_charge = $getTrx->amount;
        $transaction->amount        = $getTrx->amount;
        $transaction->post_balance  = $user->balance;
        $transaction->charge        = 0;
        $transaction->charge_type   = '-';
        $transaction->trx_type      = '+';
        $transaction->remark        = 'reject_mobile_recharge';
        $transaction->details       = 'Rejection of mobile recharge';
        $transaction->receiver_id   = 0;
        $transaction->receiver_type = null;
        $transaction->trx           = getTrx();
        $transaction->save();

        notify($user, 'MOBILE_RECHARGE_REJECT', [
            'amount'       => showAmount($mobileRecharge->amount, currencyFormat: false),
            'charge'       => showAmount($getTrx->charge, currencyFormat: false),
            'mobile'       => $mobileRecharge->mobile,
            'operator'     => $mobileOperator->name,
            'trx'          => $getTrx->trx,
            'reason'       => $request->message,
            'time'         => showDateTime($mobileRecharge->created_at, 'd/M/Y @h:i a'),
            'post_balance' => showAmount($getTrx->post_balance, currencyFormat: false),
        ]);

        $notify[] = ['success', 'Mobile recharge has been rejected successfully'];
        return back()->withNotify($notify);
    }
}
