<?php

namespace App\Http\Controllers;

use App\Models\Receipt;
use App\Models\Subscription;
use App\Models\SubscriptionProduct;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SubscriptionController extends Controller
{
    public function index() {

        // Recogemos todas las suscripciones disponibles en la base de datos
        // y las pasamos a la vista
        $subscriptions = SubscriptionProduct::all();
        // dd($subscriptions);

        $userSubscriptionProductIds = Auth::user()
        ->subscriptions()
        ->pluck('subscription_product_id')
        ->toArray();
        

        return view('pages.subscription.index', compact('subscriptions','userSubscriptionProductIds'));
    }

    public function cancelSubscription($id) {

        try {

            DB::beginTransaction();

            $userId = Auth::id();

            $subscription = Subscription::where('user_id', $userId)->where('subscription_product_id', $id)->first();

            Subscription::where('user_id', $userId)->where('subscription_product_id', $id)->delete();
            
            Receipt::where('id', $subscription->receipt_id)->delete();

            DB::commit();

            return redirect()->back()->with('success', 'Subscription cancelled successfully.');

        } catch (\Exception $e) {

            DB::rollBack();

            return redirect()->back()->with('error', 'Error cancelling subscription: ' . $e->getMessage());
        }
    }

}