Your IP : 3.133.133.251


Current Path : /home/lentoinv/api.lentoria.com/app/Http/Controllers/
Upload File :
Current File : //home/lentoinv/api.lentoria.com/app/Http/Controllers/SectionController.php

<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\Lecture;
use App\Models\Section;
use App\Models\UserLectureProgress;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class SectionController extends Controller
{
    public function createSection(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'course_id' => 'required|exists:courses,id',
            'title' => 'required|string|max:100',
            'gain' => 'required|string',
        ]);
        if ($validation->fails()) {
            return response(['errors' => $validation->errors()->all()], 422);
        }
        $total_section = Section::where(['course_id' => $request->course_id])->count() + 1;
        $section = Section::create([
            'course_id' => $request->course_id,
            'title' => $request->title,
            'course_gain' => $request->gain,
            'order' => $total_section
        ]);
        return response(['message' => 'Section created successfully', 'id' => $section->id], 200);
    }

    public function getSections($course_id)
    {
        $course = Course::find($course_id);
        $sections = Section::where('course_id', $course_id)
            ->with('lectures')
            ->orderby('order', 'ASC')
            ->get();
        $sections = $sections->map(function ($s) {
            $s->lectures = $s->lectures->map(function ($l) {
                $l->main_content = html_entity_decode($l->main_content);
                return $l;
            });
            return $s;
        });
        return response(['data' => $sections], 200);
    }

    public function getSection($id)
    {
        $section = Section::find($id);

        return response(['data' => $section], 200);
    }

    public function getSectionsBySlug($slug)
    {
        $course = Course::query()->where('slug', $slug)
            ->select('id', 'course_type')->first();
        $cid = $course->id;
        $userId = auth()->id();
        $courseType = $course->course_type;
        $section = Section::query()
            ->where('course_id', $cid)->with('lectures:id,description,image,main_content,duration,section_id,title')
            ->withCount('lectures')->orderBy('order', 'ASC')
            ->get();

        $progress = null;
        if ($courseType == 3) {
            $progress = $this->unlockNextLecture($userId, $cid);
        } // Unlock the next lecture for the user

        $section = $section->map(static function ($s) use ($progress) {
            $s->lectures = $s->lectures->map(static function ($l, $index) use ($progress) {
                $l->main_content = html_entity_decode($l->main_content);
                $l->is_locked = true; // Initialize as locked

                if ($progress) {
                    $unlockedLectureIds = $progress->unlocked_lecture_ids;

                    if (in_array($l->id, $unlockedLectureIds)) {
                        $l->is_locked = false; // Lecture is unlocked
                    }
                }

                return $l;
            });

            return $s;
        });

        return response(['data' => $section], 200);
    }

    public function unlockNextLecture($userId, $courseId)
    {
        // Retrieve the user's lecture progress record
        $progress = UserLectureProgress::where('user_id', $userId)
            ->where('course_id', $courseId)
            ->first();

        // If the progress record doesn't exist, create a new one
        if (!$progress) {
            $progress = new UserLectureProgress();
            $progress->user_id = $userId;
            $progress->course_id = $courseId;

            // Unlock the first lecture in the first section of the course
            $firstSection = Section::where('course_id', $courseId)
                ->orderBy('order', 'ASC')
                ->first();

            if ($firstSection) {
                $firstLecture = $firstSection->lectures()->orderBy('order', 'ASC')->first();

                if ($firstLecture) {
                    $progress->unlocked_lecture_ids = [$firstLecture->id];
                    $progress->last_unlock_date = Carbon::now();
                }
            }

            $progress->save();
        } else {
            // Get the unlocked lecture IDs and last unlock date
            $unlockedLectureIds = $progress->unlocked_lecture_ids;
            $lastUnlockDate = Carbon::parse($progress->last_unlock_date);

            // Check if a lecture can be unlocked today based on the last unlock date
            $currentDate = Carbon::now()->format('Y-m-d');
            $canUnlockToday = $lastUnlockDate === null || $lastUnlockDate->format('Y-m-d') !== $currentDate;

            if ($canUnlockToday) {
                // Check if any lecture has been unlocked
                if (empty($unlockedLectureIds)) {
                    // Unlock the first lecture in the first section of the course
                    $firstSection = Section::where('course_id', $courseId)
                        ->orderBy('order', 'ASC')
                        ->first();

                    if ($firstSection) {
                        $firstLecture = $firstSection->lectures()->orderBy('order', 'ASC')->first();

                        if ($firstLecture) {
                            $progress->unlocked_lecture_ids = [$firstLecture->id];
                            $progress->last_unlock_date = Carbon::now();
                        }
                    }
                } else {
                    // Get the last unlocked lecture ID
                    $lastUnlockedLectureId = end($unlockedLectureIds);
                    $lastUnlockedLecture = Lecture::find($lastUnlockedLectureId);

                    if ($lastUnlockedLecture) {
                        // Check if there are locked lectures within the same section
                        $lockedLecturesInSection = $lastUnlockedLecture->section->lectures()
                            ->whereNotIn('id', $unlockedLectureIds)
                            ->orderBy('order', 'ASC')
                            ->get();

                        if ($lockedLecturesInSection->isNotEmpty()) {
                            // Unlock the next locked lecture within the section
                            $nextLockedLecture = $lockedLecturesInSection->first();
                            $unlockedLectureIds[] = $nextLockedLecture->id;
                            $progress->last_unlock_date = Carbon::now();
                        } else {
                            // Get the next section
                            $nextSection = $lastUnlockedLecture->section->nextSection();

                            if ($nextSection) {
                                $firstLecture = $nextSection->lectures()->orderBy('order', 'ASC')->first();

                                if ($firstLecture) {
                                    $unlockedLectureIds = [...$unlockedLectureIds, $firstLecture->id];
                                    $progress->last_unlock_date = Carbon::now();
                                }
                            }
                        }
                    }
                }

                // Update the progress record
                $progress->unlocked_lecture_ids = $unlockedLectureIds;
                $progress->save();
            }
        }

        return $progress;
    }

    public function getSectionWithLectures()
    {
        $sections = Section::with(['lectures:id,title'])->get();

        return response(['data' => $sections], 200);
    }

    public function updateSection(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'course_id' => 'required|exists:courses,id',
            'title' => 'required|string|max:100',
            'gain' => 'required|string',
        ]);
        if ($validation->fails()) {
            return response(['errors' => $validation->errors()->all()], 422);
        }
        Section::find($request->id)->update([
            'course_id' => $request->course_id,
            'title' => $request->title,
            'course_gain' => $request->gain,
        ]);

        return response(['message' => 'Section has been updated successfully'], 200);
    }

    function orderSection(Request $request)
    {
        $val = Validator::make($request->all(), [
            'id' => 'required|exists:sections,id',
            'action' => 'required'
        ]);
        if ($val->fails()) {
            return response(['errors' => $val->errors()->all()], 422);
        }
        $section = Section::find($request->id);
        $action = $request->action;
        $current_section_order = $section->order;

        $before_current = ($action == 'up') ? Section::where(['course_id' => $section->course_id, ['order', '<', $section->order]])
            ->orderBy('order', 'desc')->first() :
            Section::where(['course_id' => $section->course_id, ['order', '>', $section->order]])
                ->orderBy('order', 'asc')->first();

        if (!$before_current) {
            return response([
                'message' => 'This item cannot be ordered'
            ], 422);
        }

        $section->update([
            'order' => $before_current->order
        ]);

        $before_current->update([
            'order' => $current_section_order
        ]);

        return response([
            'message' => 'Section has be ordered sucessfully'
        ], 200);
    }
}

?>