<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Models\UserCourse;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function index()
    {
        $userId = Auth::id();

        // Obtener los cursos en el carrito del usuario
        $coursesInCart = UserCourse::with('course')->where('user_id', $userId)->where('status_id', 1)->get()->pluck('course');

        return view('pages.student.myCart', ['courses' => $coursesInCart]);
    }

    public function destroy($courseId) {

        $userId = Auth::id();

        $courseHasLike = UserCourse::where('user_id', $userId)->where('course_id', $courseId)->where('favorite', 1)->first();

        if ($courseHasLike) {

            UserCourse::where('user_id', $userId)->where('course_id', $courseId)->update(['status_id' => NULL]);

        } else {

            UserCourse::where('user_id', $userId)->where('course_id', $courseId)->where('status_id', 1)->delete();

        }

        return redirect()->back();

    }

    public function store($courseId, $price) {

        $userId = Auth::id();

        $now = Carbon::now();

        $courseExists = UserCourse::where('user_id', $userId)->where('course_id', $courseId)->first();

        if ($courseExists) {

            UserCourse::where('user_id', $userId)->where('course_id', $courseId)->update(['status_id' => 1, 'receipt_id' => NULL, 'price_paid' => $price, 'created_at' => $now, 'updated_at' => $now]);

        } else {

            UserCourse::create(['user_id' => $userId, 'course_id' => $courseId, 'status_id' => 1, 'receipt_id' => NULL, 'price_paid' => $price, 'created_at' => $now, 'updated_at' => $now]);

        }


        return redirect()->back()->with('success', 'Curso añadido al carrito.');

    }

}