<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CoursePart;
use App\Models\Course;
use App\Models\CourseSubject;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Brian2694\Toastr\Facades\Toastr;

class AdminCoursePartController extends Controller
{
    //Course View
    public function AdminCoursePartView()
    {
        Session::put('admin_page', 'admin_course_part_view');
        $course_part = CoursePart::select('course_id')->groupBy('course_id')->get();
        $course_view = Course::latest()->get();
        return view('admin.course.course_part', compact('course_part', 'course_view'));
    }

    //Course Add
    public function AdminCoursePartStore(Request $request)
    {
        $request->validate([
            'course_id' => 'max:255|required|unique:course_parts,course_part',
            'course_part' => 'max:255|required',
        ]);
        $course_part_store = new CoursePart();
        $course_part_store->course_id = $request->course_id;
        $course_part_store->course_part_slug = Str::slug($request->course_part);
        $course_part_store->course_part = $request->course_part;
        $course_part_store->save();
        Toastr::success('Course Part Created Successfully');
        return redirect()->back();
    }

    //Course Edit
    public function AdminCoursePartUpdate(Request $request, $id)
    {
        $request->validate([
            'course_id' => 'max:255|required|unique:course_parts,course_part',
            'course_part' => 'max:255|required',
        ]);
        $course_part_store = CoursePart::find($id);
        $course_part_store->course_id = $request->course_id;
        $course_part_store->course_part_slug = Str::slug($request->course_part);
        $course_part_store->course_part = $request->course_part;
        $course_part_store->save();
        Toastr::success('Course Part Updated Successfully');
        return redirect()->back();
    }


    public function AdminCoursePartEdit($id)
    {
        $course_details = CoursePart::where('course_id',$id)->get();
        $course_view = Course::latest()->get();
        return view('admin.course.course_part_edit', compact('course_details','course_view'));
    }
    //Course Add
    public function AdminCoursePartDelete($id)
    {
        if (CourseSubject::where('course_id', $id)->count() >0) {
            Toastr::warning('Course Part canot be delete');
            return redirect()->back();
        } else {
            $course_delete = CoursePart::find($id);
            $course_delete->delete();
            Toastr::success('Course Part Deleted Successfully');
            return redirect()->back();
        }
        
    }
}
