<?php

namespace App\Http\Controllers\Student;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Wishlist;
use App\Models\Course;
use Auth;


class WishlistController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function wishlists(Request $request)
    {
        $user = Auth::user();
        $wishes = Wishlist::where('register_id',0)->where('user_id','=',$user->id)->pluck('course_id');
        $wishlists = Course::where('register_id',0)->where('status','=',1)->whereIn('id',$wishes)->latest('id')->paginate(8);
        if($request->ajax())
        {
            return view('front.ajax.wishlist',compact('user','wishlists'));            
        }
        return view('student.wishlist',compact('user','wishlists'));
    }

    public function addwish(Request $request,$id)
    {      
        $user = Auth::user();
        $data[0] = 0; 
        $ck = Wishlist::where('register_id',0)->where('user_id','=',$user->id)->where('course_id','=',$id)->get()->count();
        if($ck > 0)
        {
            $data['error'] = __('Already Added To The Wishlist.');
            if($request->ajax())
            {
                return response()->json($data);
            }
            else{
                return redirect()->route('student-wishlists')->with('error',$data['error']);
            } 
        }
        $wish = new Wishlist();
        $wish->user_id = $user->id;
        $wish->course_id = $id;
        $wish->save();
        $data[0] = 1; 
        $data['success'] = __('Successfully Added To The Wishlist.');

        if($request->ajax())
        {
            return response()->json($data);
        }
        else{
            return redirect()->route('student-wishlists')->with('success',$data['success']);
        } 

    }

    public function removewish(Request $request,$id)
    {
        $user = Auth::user();
        $wish = Wishlist::findOrFail($id);
        $wish->delete();        
        $data[0] = 1; 
        $data['success'] = __('Successfully Removed From Wishlist.');
        return response()->json($data);      
    }

}