<?php

namespace Modules\Installment\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\Payment\Entities\Cart;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Support\Renderable;
use Modules\Installment\Entities\InstallmentCart;
use Modules\Installment\Entities\InstallmentPurchasePayment;
use Modules\Installment\Entities\InstallmentPurchaseRequest;

class StudentInstallmentController extends Controller
{
    public function installmentList()
    {
        $all_purchase = InstallmentPurchaseRequest::where('user_id', auth()->user()->id)->with('installmentPayments')->get();
        $user_installment_overview = [];
        $user_installment_overview['open'] = $all_purchase->where('payment_status', 'approved')->count();
        $user_installment_overview['pending_verification'] = $all_purchase->where('payment_status', 'paid')->count();
        $user_installment_overview['complete'] = $all_purchase->where('payment_status', 'complete')->count();
        $user_installment_overview['overdue'] = InstallmentPurchaseRequest::where('user_id', auth()->user()->id)->with('installmentPayments')->whereHas('installmentPayments', function ($q) {
            $q->where('status', '!=', 'paid')->where('due_date', '<', date('Y-m-d'));
        })->count();
        $purchase_requests = InstallmentPurchaseRequest::where('user_id', auth()->user()->id)
            ->with('installmentPayments', 'plan', 'topic')
            ->paginate(10);

        return view(theme('pages.my-installments'), compact('purchase_requests', 'user_installment_overview'));
    }

    public function PurchaseRequestDetails($purchase_id)
    {
        $purchase_request = InstallmentPurchaseRequest::where('id', $purchase_id)->where('user_id', auth()->user()->id)
            ->with('installmentPayments', 'plan', 'topic', 'installmentPayments.step')
            ->first();
        if ($purchase_request) {
            return view(theme('pages.installments-details'), compact('purchase_request'));
        } else {
            return redirect()->route('installment.student_installment.list')->with('error', 'Purchase request not found');
        }
    }

    public function payInstallment($installment_payment_id)
    {
        try {
            DB::beginTransaction();

            $installment_payment = InstallmentPurchasePayment::where('id', $installment_payment_id)->where('status', 'unpaid')
                ->with('installmentPurchaseRequest')
                ->whereHas('installmentPurchaseRequest', function ($query) {
                    $query->where('user_id', auth()->user()->id);
                })
                ->first();
            $user = auth()->user();
            $course = $installment_payment->installmentPurchaseRequest->topic;
            $price = $installment_payment->amount;
            $plan_id = $installment_payment->installmentPurchaseRequest->plan_id;

            $oldCart = Cart::where('user_id', $user->id)->when(isModuleActive('Appointment'), function ($query) {
                $query->whereNotNull('course_id');
            })->first();
            $exist = Cart::where('course_id', $course->id)->first();
            if ($exist) {
                Toastr::error(_trans('frontend.Course already added in your cart'), trans('common.Failed'));
                return redirect()->route('CheckOut');
            }

            if (isset($oldCart)) {

                $cart = new Cart();
                $cart->user_id = $user->id;
                $cart->instructor_id = $course->user_id;
                $cart->course_id = $course->id;
                $cart->tracking = $oldCart->tracking;
                $cart->price = $price;
                $cart->is_installment = 1;
                $cart->purchase_id = $installment_payment->installmentPurchaseRequest->id;
                $cart->plan_id = $plan_id;
                $cart->installment_type = 'installment';
                $cart->save();
            } else {
                $cart = new Cart();
                $cart->user_id = $user->id;
                $cart->instructor_id = $course->user_id;
                $cart->course_id = $course->id;
                $cart->tracking = getTrx();
                $cart->price = $price;
                $cart->is_installment = 1;
                $cart->purchase_id = $installment_payment->installmentPurchaseRequest->id;
                $cart->plan_id = $plan_id;
                $cart->installment_type = 'installment';
                $cart->save();
            }
            $installment_cart = new InstallmentCart();
            $installment_cart->user_id = $user->id;
            $installment_cart->instructor_id = $course->user_id;
            $installment_cart->course_id = $course->id;
            $installment_cart->tracking = $cart->tracking;
            $installment_cart->price = $cart->price;
            $installment_cart->purchase_id = $installment_payment->installmentPurchaseRequest->id;
            $installment_cart->save();

            DB::commit();
            Toastr::success(trans('frontend.Course Installment added in your cart'), trans('common.Success'));
            return redirect()->route('CheckOut');
        } catch (\Throwable $e) {
            DB::rollBack();
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }
}
