<?php

namespace Modules\Installment\Http\Controllers;

use App\Traits\SendNotification;
use Brian2694\Toastr\Facades\Toastr;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\CourseSetting\Entities\Course;
use Modules\CourseSetting\Entities\CourseEnrolled;
use Modules\Installment\Entities\InstallmentPurchaseRequest;
use Modules\Payment\Entities\Checkout;
use Yajra\DataTables\Facades\DataTables;

class InstallmentAdminPurchaseController extends Controller
{
    use SendNotification;

    public function tableColumns()
    {
        return [
            _trans('installment.SL'),
            _trans('installment.User'),
            _trans('installment.Plan'),
            _trans('installment.Topic'),
            _trans('installment.Purchase Date'),
            _trans('installment.Total Amount'),
            _trans('installment.Upfront'),
            _trans('installment.Installment'),
            _trans('installment.Overdue'),
            _trans('installment.Overdue Amount'),
            _trans('installment.Remaining Days'),
            _trans('installment.Status'),
            _trans('installment.Action'),
        ];
    }

    public function index()
    {
        $data = [];
        $data['title'] = _trans('installment.Installment Purchase List');
        $data['purchase_requests'] = InstallmentPurchaseRequest::where('payment_status', '!=', 'incomplete')->with('installmentPayments', 'plan', 'topic')->get();
        $data['table_columns'] = $this->tableColumns();
        return view('installment::purchase.index', compact('data'));
    }

    public function purchaseAjax()
    {
        $query = InstallmentPurchaseRequest::query();
        $query->with(['installmentPayments', 'plan', 'topic']);
        $query->latest();


        return Datatables::of($query)
            ->addIndexColumn()
            ->addColumn('name', function ($query) {
                return @$query->user->name;
            })
            ->editColumn('plan', function ($query) {
                return @$query->plan->getTranslation('title', auth()->user()->language_code);
            })
            ->editColumn('topic', function ($query) {
                return @$query->topic->getTranslation('title', auth()->user()->language_code);
            })
            ->editColumn('purchase_date', function ($query) {
                return showDate(@$query->purchase_date);
            })
            ->editColumn('total_amount', function ($query) {
                return getPriceFormat(@$query->total_amount);
            })
            ->editColumn('upfront', function ($query) {
                $purchase_upfront = $query->installmentPayments->where('type', 'upfront')->first();
                return getPriceFormat(@$purchase_upfront->amount) . ' (' . $purchase_upfront->percentage . '%)';
            })
            ->editColumn('installment', function ($query) {
                $purchase_installments = $query->installmentPayments->where('type', '!=', 'upfront');
                $installment_count = $purchase_installments->count();
                $installment_amount = $purchase_installments->sum('amount');
                return getPriceFormat(@$installment_amount) . " (" . $installment_count . ' ' . _trans('installment.Part') . ")";

            })
            ->editColumn('overdue', function ($query) {
                $overdue = $query->overdueInstallment();
                return $overdue->count();
            })
            ->editColumn('overdue_amount', function ($query) {
                $overdue = $query->overdueInstallment();
                return $overdue->count() > 0 ? getPriceFormat(@$overdue->sum('amount')) : 'N/A';
            })
            ->editColumn('remaining_days', function ($query) {
                return $query->installmentRemainingDays();
            })
            ->editColumn('status', function ($query) {
                $status = '';
                if ($query->payment_status == 'paid') {
                    $status = _trans("installment.Waiting for approval");
                } elseif ($query->payment_status == 'approved') {
                    $status = _trans('installment.Open');
                } elseif ($query->payment_status == 'complete') {
                    $status = _trans('installment.Complete');
                } else {
                    $status = _trans('installment.Rejected');
                }
                return $status;
            })
            ->editColumn('action', function ($query) {
                return view('installment::purchase.action_menu', compact('query'));
            })->rawColumns(['name'])
            ->make(true);
    }

    public function PurchaseRequestChangeStatus(Request $request)
    {
        try {
            $purchase = InstallmentPurchaseRequest::where('id', $request->purchase_id)->with('installment_cart', 'installmentAttachment')->first();
            $checkout = Checkout::where('tracking', $purchase->tracking)->first();
            $user = $purchase->user;


            if ($request->status == 'approved') {
                $checkout->status = 1;
                $checkout->save();

                $purchase->payment_status = 'approved';
                $purchase->save();

                $checkout_data = $purchase->checkout_data;
                $discount = $checkout_data['payment_discount'];
                $cart = (object)$checkout_data['payment_cart'];
                $carts = (object)$checkout_data['payment_carts'];
                $courseType = (object)$checkout_data['payment_courseType'];
                $gateWayName = $checkout_data['payment_gateWayName'];

                $payment_controller = new \App\Http\Controllers\PaymentController();
                $payment_controller->defaultPayment($checkout, $user, $discount, $cart, $carts, $courseType, $gateWayName);

                $purchase_verification_files = $purchase->installmentAttachment;
                if ($purchase_verification_files != null) {
                    $user->installment_verified = 1;
                    $user->save();
                }
                $this->sendNotification('Installment_Request_Approved', $purchase->user, [
                    'name' => $purchase->user->name,
                    'course' => $purchase->topic->title,
                    'plan' => $purchase->plan->title,
                    'course_link' => courseDetailsUrl(@$purchase->topic->id, @$purchase->topic->type, @$purchase->topic->slug),
                ]);
            }


            Toastr::success(_trans('installment.Purchase request status updated'), trans('common.Success'));
            return redirect()->route('installment.purchase.list');
        } catch (Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function PurchaseRequestRejectRequest(Request $request)
    {
        try {
            DB::beginTransaction();
            $purchase = InstallmentPurchaseRequest::where('id', $request->request_id)->with('installment_cart')->first();

            $paid_amount = $purchase->installmentPayments->where('status', 'paid')->sum('amount');


            $course = Course::where('id', $purchase->topic_id)->first();
            $user_percentage = $course->userTotalPercentage($purchase->user_id, $course->id);
            $max_percentage = Settings('topic_complete_max_limit') ? Settings('topic_complete_max_limit') : 30;
            if ($user_percentage < $max_percentage) {
                $student = $purchase->user;
                $student->balance = $student->balance + $paid_amount;
                $student->save();
            }

            $purchase->installmentPayments()->delete();
            $purchase->installment_cart()->delete();
            $purchase->delete();

            $course_enroll = CourseEnrolled::where('user_id', $purchase->user_id)->where('course_id', $purchase->topic_id)->first();
            if ($course_enroll) {
                $course_enroll->delete();
            }

            $this->sendNotification('Installment_Request_Reject', $purchase->user, [
                'name' => $purchase->user->name,
                'course' => $purchase->topic->title,
                'plan' => $purchase->plan->title,
                'course_link' => courseDetailsUrl(@$purchase->topic->id, @$purchase->topic->type, @$purchase->topic->slug),
            ]);


            DB::commit();
            Toastr::success(_trans('installment.Purchase request rejected'), trans('common.Success'));
            return redirect()->route('installment.purchase.list');
        } catch (\Throwable $e) {
            DB::rollBack();
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function PurchaseRequestDetails($purchase_id)
    {
        $data = [];
        $data['purchase'] = InstallmentPurchaseRequest::where('id', $purchase_id)->with('installmentPayments', 'plan', 'topic', 'installmentAttachment')->firstOrFail();
        $data['top_title'] = _trans('installment.Installment Overview') . '-' . $data['purchase']->user->name;
        $data['title'] = _trans('installment.Installment Purchase Details');
        $data['all_purchase'] = InstallmentPurchaseRequest::where('user_id', $data['purchase']->user_id)->with('installmentPayments', 'plan', 'topic')->get();
        $data['user_installment_overview'] = [];
        $data['user_installment_overview']['open'] = $data['all_purchase']->where('payment_status', 'approved')->count();
        $data['user_installment_overview']['pending_verification'] = $data['all_purchase']->where('payment_status', 'paid')->count();
        $data['user_installment_overview']['complete'] = $data['all_purchase']->where('payment_status', 'complete')->count();
        $data['user_installment_overview']['overdue'] = InstallmentPurchaseRequest::where('user_id', $data['purchase']->user_id)->with('installmentPayments', 'plan', 'topic')->whereHas('installmentPayments', function ($q) {
            $q->where('status', '!=', 'paid')->where('due_date', '<', date('Y-m-d'));
        })->count();
        return view('installment::purchase.details', compact('data'));
    }


}
