<?php

namespace App\Http\Controllers\FrontControllers;

use App\Http\Controllers\Controller;
use App\Repositories\StripeRepository;
use App\Repositories\StripeRepositoryEloquent;
use App\Traits\PHPCustomMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DonationController extends Controller
{
    use PHPCustomMail;
    private $stripeRepo;
    public function __construct(StripeRepositoryEloquent $stripeRepository)
    {
        $this->stripeRepo = $stripeRepository;
    }
    public function store(Request $request)
    {
        try {
            session()->put('donationData', $request->all());
            $amount = $request->amount;
            return view('front.payment', compact('amount'));
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function payment(Request $request)
    {
        try {
            $request->validate([
                'payment_method_id' => 'required'
            ]);
            $stripeToken = $this->stripeRepo
                ->checkFrontStripeToken($request->input('payment_method_id'));

            DB::beginTransaction();
            $charge = $this->stripeRepo->frontCharge($stripeToken, $request->amount);
            if ($charge) {
                $email = "test@mailinator.com";
                $amount = $request->amount;
                $view = view('user.email.donation', compact(['amount', 'email']))->render();
                $data = [
                    'from' => 'loppandrea83@gmail.com',
                    'to' => auth()->user()->email,
                    'subject' => 'Donation',
                    'body' => $view,
                ];
                $this->customMail($data['from'], $data['to'], $data['subject'], $data['body']);
                return redirect()->route('front.success')->with('success', 'Subscription successfully processed.');
            }
        } catch (\Exception $e) {
            dd($e->getMessage());
            return redirect()->route('success')->with('error', 'Payment failed. Please try again.');
        }
    }

    public function paymentFront(){
        return view('front.payment');
    }

}
