<?php

namespace App\Http\Controllers\Admin;

use App\Constants\Status;
use App\Exports\AdminRewardExport;
use App\Http\Controllers\Controller;
use App\Models\Level;
use App\Models\Reward;
use App\Models\Transaction;
use App\Models\User;
use App\Models\UserNotification;
use Illuminate\Http\Request;
use App\Rules\FileTypeValidate;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;

class RewardController extends Controller
{
    public function index()
    {
        $pageTitle = 'All Rewards List';
        $status = Reward::distinct('status')->orderBy('status')->get('status');
        $ranks = Reward::distinct('rank')->orderBy('rank')->get('rank');
        $total_rewards_ammount = Reward::where('status', 1)->sum('prize');
        $total_members = Reward::count('id');
        $rewards = Reward::searchable(['user:username,system_id'])
            ->dateFilter('created_at')
            ->filter(['status', 'rank'])
            ->with('user')
            ->paginate(getPaginate());

        return view('admin.reward.index', compact('pageTitle', 'rewards', 'status', 'ranks', 'total_rewards_ammount', 'total_members'));
    }

    public function status(Request $request, $id)
    {
        $reward = Reward::findOrFail($id);

        if ($request->status == Status::Approved) {
            DB::transaction(function () use ($reward, $request) {
                $user = $reward->user;
                $user->increment('balance', $request->payable);
                $trx = @$request->trx ?: getTrx();

                $user_data = User::where('id', $user->id)->first();
                if ($user_data->debt_cleared_at === null) {
                    if ($user_data->balance > $user_data->current_debt_value) {
                        $user_data->debt_cleared_at = now();
                        $user_data->save();
                        $this->createDebtFeeUserNotification($user_data, 'Your Debt has been cleared ');
                    }
                }

                $transaction = Transaction::create([
                    'trx' => $trx,
                    'trx_type' => '+',
                    'charge' => $request->charge,
                    'user_id' => $user->id,
                    'amount' => $request->payable,
                    'remark' => Status::CommissionReward,
                    'payment_mode' => $request->payment_mode,
                    'post_balance' => $user->balance,
                    'details' => "Commission Reward for reaching level {$reward->rank}",
                    'status' => Status::Approved,
                ]);

                $reward->trx = $trx;
                $reward->save();

                return $transaction;
            });
        } elseif ($request->status == Status::Rejected) {
            $reward->reject_reason = $request->reject_reason;
        } else {
            return back()->withNotify([['error', 'Status not supported!']]);
        }

        $reward->status = $request->status;
        $reward->status_changed_at = Carbon::now();
        $reward->save();

        return back()->withNotify([['success', 'Status changed successfully!']]);
    }

    public function exportRewardExcel(Request $request)
    {
        $fileName = 'Reward-Report- ' . date('Y-m-d') . '.csv';
        return Excel::download(new AdminRewardExport(), $fileName);
    }

    public function generateRewardPdf(Request $request)
    {
        $rewards = Reward::searchable(['user:id,username,system_id'])
            ->dateFilter('created_at')
            ->filter(['status', 'rank'])
            ->with(['user', 'transaction'])
            ->get();

        $pdf = PDF::loadView($this->activeTemplate . 'user.pdf_blades.rewards_pdf', compact('rewards'));
        $filename = 'Rewards-report-' . date('Y-m-d') . '.pdf';
        return $pdf->download($filename);
    }

    private function createDebtFeeUserNotification( User $user_data, $message)
    {
        $userNotification = new UserNotification();
        $userNotification->user_id = $user_data->id;
        $userNotification->title = $user_data->username . ' ' . $message;
        $userNotification->click_url = urlPath('user.notification');
        $userNotification->save();
    }
}
