<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Course;
use Illuminate\Http\Request;
use Devrabiul\ToastMagic\Facades\ToastMagic;
use Illuminate\Support\Facades\DB;

class CourseController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $courses = Course::latest()->paginate(25);
        return view('backend.courses.index', compact('courses'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('backend.courses.add');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'image' => 'required|image|max:5000',
        ]);

        Course::create([
            'name' => $request->name,
            'description' => $request->description,
            'btn_link' => $request->btn_link,
            'image' => uploadImg($request->file('image'), 'courses'),
            'work_submit' => $request->work_submit,
            'commission' => $request->commission,
        ]);

        ToastMagic::success("New course has been created");
        return redirect()->back();
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Course $course)
    {
        return view('backend.courses.edit', compact('course'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Course $course)
    {
        $request->validate([
            'name' => 'required|max:255',
            'image' => 'nullable|image|max:5000',
        ]);

        $course->update([
            'name' => $request->name,
            'description' => $request->description,
            'btn_link' => $request->btn_link,
            'image' => updateImg($request->file('image'), 'courses', $course->image),
            'work_submit' => $request->work_submit,
            'commission' => $request->commission,
        ]);

        ToastMagic::success("Course has been updated");
        return redirect()->route('admin.courses.index');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Course $course)
    {
        DB::transaction(function() use($course){
            $course->home_works()->update([
                'course_id' => null
                ]);
            $course->delete();
        });
        ToastMagic::success("Course has been deleted");
        return redirect()->back();   
    }
}