<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\Courses;
use App\Models\Admin\Subjects;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class SubjectsController extends Controller
{
    // public function checkSubjectLink($url, $encrypted_id = "")
    // {
    //     $url = str_replace(['/', ' '], '-', $url);
    //     $url = preg_replace('/[^a-z0-9-]+/', '-', $url);
    //     $url = trim($url, '-');
    //     $url = preg_replace('/-+/', '-', $url);
    //     $original_link = $url;

    //     $id = (isset($encrypted_id) && !empty($encrypted_id)) ? Crypt::decrypt($encrypted_id) : 0;
    //     $suffix = 1;
    //     do {
    //         $count = $id != 0 ? Subjects::where('subject_url', $url)->where('id', '!=', $id)->count() : Subjects::where('subject_url', $url)->count();

    //         if ($count > 0) {
    //             $url = $original_link . '-' . $suffix;
    //             $suffix++;
    //         } else {
    //             break;
    //         }
    //     } while (true);

    //     return $url;
    // }

    public function manageSubjects()
    {
        // $courses = Courses::select('id', 'course_code', 'course_name')
        //     ->where('status', 'active')
        //     ->get()
        //     ->map(function ($course) {

        //         $course->subjects = Subjects::select('id', 'position_order', 'subject_name', 'subject_code', 'status')
        //             ->whereJsonContains('course_ids', $course->id)
        //             ->orderBy('position_order', 'asc')
        //             ->get()
        //             ->map(function ($subject) {
        //                 $subject->encrypted_id = Crypt::encrypt($subject->id);
        //                 return $subject;
        //             });

        //         return $course;
        //     });
        $subjects = Subjects::select('id', 'course_ids', 'position_order', 'subject_name', 'subject_code', 'status')
            ->orderBy('position_order', 'asc')
            ->get();
        foreach ($subjects as $subject) {
            $subject->encrypted_id = Crypt::encrypt($subject->id);
            // $subject->courses = Courses::select('id', 'course_code', 'course_name')->whereIn('id', $subject->course_ids)->where('status', 'active')->get();
        }

        $main_page = '';    // assignments_management
        $currentPage = "manage_subjects";
        $model = Crypt::encrypt('Subjects');

        return view(
            'admin.manage_subjects',
            compact('subjects', 'model', 'main_page', 'currentPage')
        );
    }

    public function addSubject(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                'course_ids' => 'required|array',
                'subject_name' => 'required|string',
                'subject_code' => 'required|string',
            ], [
                'course_ids.required' => 'Please provide the Category.',
                'subject_name.required' => 'Please provide a Subject Name.',
                'subject_name.string' => 'Subject Name must be a string.',
                'subject_code.required' => 'Please provide Subject Code.',
                'subject_code.string' => 'Subject Code must be a string.',
            ]);

            $order = Subjects::max('position_order');
            $position_order = ($order !== null) ? $order + 1 : 1;

            $course_ids = array_map(function ($id) {
                return Crypt::decrypt($id);
            }, $request->course_ids ?? []);

            $subject = [
                'course_ids' => $course_ids,
                'position_order' => $position_order,
                'subject_name' => $request->subject_name,
                'subject_code' => $request->subject_code,
                'course_year' => $request->course_year,
                'semesters' => $request->semesters,
            ];

            if (Subjects::create($subject)) {
                $request->session()->flash('success', 'Subject is inserted Successfully!');
                return redirect()->route('manage.subjects');
            } else {
                $request->session()->flash('error', 'Insertion Error!');
                return redirect()->route('add.subject');
            }
        } else {
            $all_subject_courses = Courses::all();
            foreach ($all_subject_courses as $course) {
                $course->encrypted_id = Crypt::encrypt($course->id);
            }

            $main_page = '';    // assignments_management
            $currentPage = "manage_subjects";
            return view('admin.subject-ops', compact('all_subject_courses', 'main_page', 'currentPage'));
        }
    }

    public function editSubject(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                'course_ids' => 'required|array',
                'subject_name' => 'required|string',
                'subject_code' => 'required|string',
            ], [
                'course_ids.required' => 'Please provide the Category.',
                'subject_name.required' => 'Please provide a Subject Name.',
                'subject_name.string' => 'Subject Name must be a string.',
                'subject_code.required' => 'Please provide Subject Code.',
                'subject_code.string' => 'Subject Code must be a string.',
            ]);

            $course_ids = array_map(function ($id) {
                return Crypt::decrypt($id);
            }, $request->course_ids ?? []);

            $id = Crypt::decrypt($request->subject);
            $subject = Subjects::findOrFail($id);
            $subject->course_ids = $course_ids;
            $subject->subject_name = $request->subject_name;
            $subject->subject_code = $request->subject_code;
            $subject->course_year = $request->course_year;
            $subject->semesters = $request->semesters;

            if ($subject->save()) {
                $request->session()->flash('success', 'Subject is updated Successfully!');
                return redirect()->route('manage.subjects');
            } else {
                $request->session()->flash('error', 'Updation Error!');
                return redirect()->route('edit.subject', ["subject" => $request->subject]);
            }
        } else {
            $all_subject_courses = Courses::all();
            foreach ($all_subject_courses as $course) {
                $course->encrypted_id = Crypt::encrypt($course->id);
            }

            $id = Crypt::decrypt($request->subject);
            $subject = Subjects::findOrFail($id);
            $subject->encrypted_id = $request->subject;

            $main_page = '';    // assignments_management
            $currentPage = "manage_subjects";
            return view('admin.subject-ops', compact('all_subject_courses', 'subject', 'main_page', 'currentPage'));
        }
    }
}
