<?php

namespace Modules\Affiliate\Http\Controllers;


use Brian2694\Toastr\Facades\Toastr;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Modules\Affiliate\Entities\AffiliateCommission;
use Modules\Affiliate\Http\Requests\AffiliateConfigurationRequest;
use Modules\Affiliate\Http\Requests\AffiliateLinkRequest;
use Modules\Affiliate\Repositories\AffiliateRepository;
use Modules\Affiliate\Repositories\AffiliateTransactionRepository;
use Modules\BundleSubscription\Entities\BundleCoursePlan;
use Modules\CourseSetting\Entities\Course;
use Modules\FrontendManage\Entities\FrontPage;
use Modules\Subscription\Entities\CourseSubscription;


class AffiliateController extends Controller
{
    protected $affiliateRepo;

    public function __construct(AffiliateRepository $affiliateRepo)
    {
        $this->affiliateRepo = $affiliateRepo;
    }

    public function index(Request $request)
    {
        if (isAffiliateUser() && !hasAffiliateAccess()) {
            abort('403', trans('affiliate.The request is now pending for admin approval'));
        } elseif (!hasAffiliateAccess() && !isAffiliateUser()) {
            abort('403',trans('affiliate.You are not affiliate user. You need to join affiliate program first.'));
        }
        try {
            $data['bundles'] = [];
            $data['plans'] = [];
            $data['start_date'] = isset($request->startDate) ? $request->startDate : '';
            $data['end_date'] = isset($request->endDate) ? $request->endDate : '';
            $data['user'] = Auth::user();
            $affiliate_wallet = $data['user']->affiliateWallet;
            if ($affiliate_wallet && $affiliate_wallet->paypal_account) {
                $data['paypal_account'] = $affiliate_wallet->paypal_account;
            }
            $data['data'] = $this->affiliateRepo->all();
            $affiliateTransactionRepo = new AffiliateTransactionRepository();
            $data['user_transaction_data'] = $affiliateTransactionRepo->userWiseWithdraw($data['start_date'], $data['end_date']);
            $data['user_income_data'] = $affiliateTransactionRepo->userWiseIncome($data['start_date'], $data['end_date']);

            $commission =AffiliateCommission::select('id','commable_id','commission_for')->get();
             $data['courses'] = Course::select('id','title')
                ->where('status', 1)
                ->whereIn('id',$commission->where('commission_for','course')->pluck('commable_id')->toArray())
                ->get();
            if (isModuleActive('BundleSubscription')) {
                $data['bundles']=BundleCoursePlan::select('id','title')
                    ->whereIn('id',$commission->where('commission_for','bundle')->pluck('commable_id')->toArray())
                    ->where('status', 1)->get();
            }
            if (isModuleActive('Subscription')) {
                $data['plans']=CourseSubscription::select('id','title')
                    ->whereIn('id',$commission->where('commission_for','subscription')->pluck('commable_id')->toArray())
                    ->where('status', 1)->get();
            }
             if ($data['user']->role_id == 3) {
                return view('affiliate::student.student_index', $data);
            }
            return view('affiliate::affiliate.index', $data);
        } catch (Exception $e) {
            Toastr::error($e->getMessage(), trans('common.Error'));
            return redirect()->back();
        }
    }

    public function store(AffiliateLinkRequest $request)
    {
         try {
             if ($request->commission_type == 'common') {
                 $parsedUrl = parse_url($request->url);
                 $host = parse_url(URL::to('/'), PHP_URL_HOST);

                 if (!isset($parsedUrl['host']) || $parsedUrl['host'] !== $host) {
                     Toastr::error(trans('affiliate.Invalid URL'), trans('common.Error'));
                     return back();
                 }
             }


            $this->affiliateRepo->create($request->validated());
            Toastr::success(trans('affiliate.Affiliate Link Generated Successfully'));
            return back();
        } catch (Exception $e) {
            Toastr::error($e->getMessage(), trans('common.Error'));
            return back();
        }
    }

    public function configurationIndex()
    {
        try {
            return view('affiliate::affiliate.configuration');
        } catch (Exception $e) {
            Toastr::error($e->getMessage(), trans('common.Error'));
            return response()->json(['error' => $e->getMessage()], 503);
        }
    }

    public function configurationUpdate(AffiliateConfigurationRequest $request)
    {
        try {
            $this->affiliateRepo->configuration($request->validated());
            Toastr::success(trans('affiliate.Affiliate Configuration Updated Successfully'));

            return back();
        } catch (Exception $e) {
            Toastr::error($e->getMessage(), trans('common.Error'));
            return response()->json(['error' => $e->getMessage()], 503);
        }
    }

    public function addOrUpdatePaypalAccount(Request $request)
    {
        $validate_rules = [
            'paypal_account' => 'required',
        ];
        $request->validate($validate_rules, validationMessage($validate_rules));
        try {
            $this->affiliateRepo->addOrUpdatePaypalAccount($request->all());
            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return back();
        } catch (Exception $e) {
            Toastr::error($e->getMessage(), trans('common.Error'));
            return response()->json(['error' => $e->getMessage()], 503);
        }
    }

    public function frontendEdit()
    {

        try {
            $data['row'] = FrontPage::where('slug', '/affiliate')->first();
            $data['details'] = $data['row']->details;
            $active = request('lang', auth()->user()->language_code);
            app()->setLocale($active);
            return view('aorapagebuilder::pages.design', $data, compact('active'));
        } catch (Exception $e) {
            Toastr::error($e->getMessage(), trans('common.Error'));
            return response()->json(['error' => $e->getMessage()], 503);
        }
    }

    public function frontend()
    {
        $data['row'] = FrontPage::where('slug', '/affiliate')->first();
        $data['details'] = '';
        $details = DB::table('front_pages')->where('slug', '/affiliate')->first()->details ?? '';
        $pos = strpos($details, '{"');
        if ($pos === false) {
            $data['details'] = $details;
        } else {
            $details = (array)json_decode($details);
            if ($details) {
                $data['details'] = $details[array_key_first($details)];
            }
        }
        return view('aorapagebuilder::pages.show', $data);
    }
}
