<?php

namespace App\Http\Controllers\Admin;

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

class CoursesController extends Controller
{
    public function checkCourseLink($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 ? Courses::where('course_url', $url)->where('id', '!=', $id)->count() : Courses::where('course_url', $url)->count();

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

        return $url;
    }

    public function manageCourses()
    {
        $categories = Categories::with([
            'courses' => function ($q) {
                $q->select('id', 'category_id', 'position_order', 'course_code', 'course_name', 'course_short_title', 'course_headline', 'course_duration', 'course_icon', 'status')
                    ->orderBy('position_order');
            }
        ])->select('id', 'category_label')->where('status', 'active')->get();

        foreach ($categories as $category) {
            foreach ($category->courses as $course) {
                $course->encrypted_id = Crypt::encrypt($course->id);
            }
        }

        $main_page = '';    // assignments_management
        $currentPage = "manage_courses";
        $model = Crypt::encrypt('Courses');

        return view(
            'admin.manage_courses',
            compact('categories', 'model', 'main_page', 'currentPage')
        );
    }

    public function addCourse(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                'category_id' => 'required|string',
                'course_name' => 'required|string',
                'course_short_title' => 'required|string',
                'course_headline' => 'required|string',
                'course_url' => 'required|string',
                'course_code' => 'required|string',
                'course_duration' => 'nullable|integer',
            ], [
                'category_id.required' => 'Please provide the Category.',
                'course_name.required' => 'Please provide a Course Name.',
                'course_name.string' => 'Course Name must be a string.',
                'course_short_title.required' => 'Please provide Course Short Title.',
                'course_short_title.string' => 'Course Short Title must be a string.',
                'course_headline.required' => 'Please provide Course Headline.',
                'course_headline.string' => 'Course Headline must be a string.',
                'course_url.required' => 'Please provide Course URL.',
                'course_url.string' => 'Course URL must be a string.',
                'course_code.required' => 'Please provide Course Code.',
                'course_code.string' => 'Course Code must be a string.',
            ]);

            $category_id = Crypt::decrypt($request->category_id);

            $order = Courses::where('category_id', $category_id)->max('position_order');
            $position_order = ($order !== null) ? $order + 1 : 1;

            if (!empty($request->course_url)) {
                $link = strtolower($request->course_url);
            } else {
                $link = strtolower($request->course_name);
            }
            $course_url = $this->checkCourseLink($link);

            $course = [
                'category_id' => $category_id,
                'position_order' => $position_order,
                'course_name' => $request->course_name,
                'course_url' => $course_url,
                'course_short_title' => $request->course_short_title,
                'course_code' => $request->course_code,
                'course_duration' => $request->course_duration,
                'short_description' => htmlspecialchars($request->short_description, ENT_QUOTES),
                'course_icon' => $request->course_icon,
                'course_headline' => $request->course_headline,
                'breadcrumb_headline' => $request->breadcrumb_headline,
                'description' => htmlspecialchars($request->description, ENT_QUOTES),
                'meta_title' => $request->meta_title,
                'meta_keyword' => $request->meta_keyword,
                'meta_description' => htmlspecialchars($request->meta_description, ENT_QUOTES),
                'course_headline_guess_papers' => $request->course_headline_guess_papers,
                'breadcrumb_headline_guess_papers' => $request->breadcrumb_headline_guess_papers,
                'description_guess_papers' => htmlspecialchars($request->description_guess_papers, ENT_QUOTES),
                'meta_title_guess_papers' => $request->meta_title_guess_papers,
                'meta_keyword_guess_papers' => $request->meta_keyword_guess_papers,
                'meta_description_guess_papers' => htmlspecialchars($request->meta_description_guess_papers, ENT_QUOTES),
                'course_headline_projects' => $request->course_headline_projects,
                'breadcrumb_headline_projects' => $request->breadcrumb_headline_projects,
                'description_projects' => htmlspecialchars($request->description_projects, ENT_QUOTES),
                'meta_title_projects' => $request->meta_title_projects,
                'meta_keyword_projects' => $request->meta_keyword_projects,
                'meta_description_projects' => htmlspecialchars($request->meta_description_projects, ENT_QUOTES)
            ];

            if (Courses::create($course)) {
                $request->session()->flash('success', 'Course is inserted Successfully!');
                return redirect()->route('manage.courses');
            } else {
                $request->session()->flash('error', 'Insertion Error!');
                return redirect()->route('add.course');
            }
        } else {
            $all_categories = Categories::select('id', 'category_generated_id', 'category_label')->where('status', 'active')->get();
            foreach ($all_categories as $category) {
                $category->encrypted_id = Crypt::encrypt($category->id);
            }

            $main_page = '';    // assignments_management
            $currentPage = "manage_courses";
            return view('admin.course-ops', ["all_categories" => $all_categories, 'main_page' => $main_page, 'currentPage' => $currentPage]);
        }
    }

    public function editCourse(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                'category_id' => 'required|string',
                'course_name' => 'required|string',
                'course_short_title' => 'required|string',
                'course_headline' => 'required|string',
                'course_url' => 'required|string',
                'course_code' => 'required|string',
                'course_duration' => 'nullable|integer',
            ], [
                'category_id.required' => 'Please provide the Category.',
                'course_name.required' => 'Please provide a Course Name.',
                'course_name.string' => 'Course Name must be a string.',
                'course_short_title.required' => 'Please provide Course Short Title.',
                'course_short_title.string' => 'Course Short Title must be a string.',
                'course_headline.required' => 'Please provide Course Headline.',
                'course_headline.string' => 'Course Headline must be a string.',
                'course_url.required' => 'Please provide Course URL.',
                'course_url.string' => 'Course URL must be a string.',
                'course_code.required' => 'Please provide Course Code.',
                'course_code.string' => 'Course Code must be a string.',
            ]);

            if (!empty($request->course_url)) {
                $link = strtolower($request->course_url);
            } else {
                $link = strtolower($request->course_name);
            }
            $course_url = $this->checkCourseLink($link, $request->course);

            $id = Crypt::decrypt($request->course);
            $course = Courses::findOrFail($id);
            $course->category_id = Crypt::decrypt($request->category_id);
            $course->course_name = $request->course_name;
            $course->course_url = $course_url;
            $course->course_short_title = $request->course_short_title;
            $course->course_code = $request->course_code;
            $course->course_duration = $request->course_duration;
            $course->short_description = htmlspecialchars($request->short_description, ENT_QUOTES);
            $course->course_icon = $request->course_icon;
            $course->course_headline = $request->course_headline;
            $course->breadcrumb_headline = $request->breadcrumb_headline;
            $course->description = htmlspecialchars($request->description, ENT_QUOTES);
            $course->meta_title = $request->meta_title;
            $course->meta_keyword = $request->meta_keyword;
            $course->meta_description = htmlspecialchars($request->meta_description, ENT_QUOTES);
            $course->course_headline_guess_papers = $request->course_headline_guess_papers;
            $course->breadcrumb_headline_guess_papers = $request->breadcrumb_headline_guess_papers;
            $course->description_guess_papers = htmlspecialchars($request->description_guess_papers, ENT_QUOTES);
            $course->meta_title_guess_papers = $request->meta_title_guess_papers;
            $course->meta_keyword_guess_papers = $request->meta_keyword_guess_papers;
            $course->meta_description_guess_papers = htmlspecialchars($request->meta_description_guess_papers, ENT_QUOTES);
            $course->course_headline_projects = $request->course_headline_projects;
            $course->breadcrumb_headline_projects = $request->breadcrumb_headline_projects;
            $course->description_projects = htmlspecialchars($request->description_projects, ENT_QUOTES);
            $course->meta_title_projects = $request->meta_title_projects;
            $course->meta_keyword_projects = $request->meta_keyword_projects;
            $course->meta_description_projects = htmlspecialchars($request->meta_description_projects, ENT_QUOTES);

            if ($course->save()) {
                $request->session()->flash('success', 'Course is updated Successfully!');
                return redirect()->route('manage.courses');
            } else {
                $request->session()->flash('error', 'Updation Error!');
                return redirect()->route('edit.course', ["course" => $request->course]);
            }
        } else {
            $all_categories = Categories::select('id', 'category_generated_id', 'category_label')->where('status', 'active')->get();
            foreach ($all_categories as $category) {
                $category->encrypted_id = Crypt::encrypt($category->id);
            }

            $id = Crypt::decrypt($request->course);
            $course = Courses::where('id', $id)->firstOrFail();
            $course->encrypted_id = $request->course;

            $main_page = '';    // assignments_management
            $currentPage = "manage_courses";
            return view('admin.course-ops', ["all_categories" => $all_categories, "course" => $course, 'main_page' => $main_page, 'currentPage' => $currentPage]);
        }
    }

    public function updateCoursesPositionUrl()
    {
        // Get all courses ordered by category + current position (or id fallback)
        $all_courses = Courses::orderBy('category_id')
            ->orderBy('position_order')
            ->orderBy('id')
            ->get();

        $categoryCounters = [];

        foreach ($all_courses as $course) {

            // Build / ensure unique URL
            $id = Crypt::encrypt($course->id);
            $link = strtolower($course->course_name);
            $course_url = $this->checkCourseLink($link, $id);

            // Initialize counter for this category
            if (!isset($categoryCounters[$course->category_id])) {
                $categoryCounters[$course->category_id] = 1;
            } else {
                $categoryCounters[$course->category_id]++;
            }

            // Update DB using REAL id
            Courses::where('id', $course->id)->update([
                'course_url'      => $course_url,
                'position_order'  => $categoryCounters[$course->category_id],
            ]);
        }
    }


    // public function getAllCategoriesAndCount($type)
    // {
    //     $all_categories = Categories::select('id', 'category_headline', 'category_url')->where(['reference_type' => $type, "status" => 'active'])->orderBy('position_order')->get();
    //     foreach ($all_categories as $category) {
    //         $category->blog_count = Blogs::where('category_id', $category->id)->count();
    //     }

    //     return $all_categories;
    // }

    // public function uploadBlogImages(Request $request) {
    //     if(session()->has('user')) {
    //         $locations = [];

    //         if ($request->hasFile('file')) {
    //             print_r($request->file('file'));
    //             foreach ($request->file('file') as $file) {
    //                 $path = $file->store('admin-assets/images/blog-textareas/', 'public');
    //                 $locations[] = Storage::url($path);
    //             }

    //             return response()->json(['locations' => $locations]);
    //         }

    //         return response()->json(['error' => 'No files uploaded'], 400);
    //     }
    //     else {
    //         return redirect()->route('login');
    //     }
    // }


    // public function editBlogContent(Request $request) {
    //     if(session()->has('user')) {
    //         if($request->isMethod('post')) {
    //             $request->validate([
    //                 'content_headline' => 'required|string',
    //             ], [
    //                 'content_headline.required' => 'Please provide a headline for the blog content.',
    //                 'content_headline.string' => 'Blog-Content headline must be a string.',
    //             ]);

    //             $id = 1;
    //             $blog_content = BlogContent::findOrFail($id);
    //             // $blog_content->position_order = $request->position_order;
    //             $blog_content->content_headline = $request->content_headline;
    //             $blog_content->description = htmlspecialchars($request->description, ENT_QUOTES);

    //             if(!empty($request->file('content_image'))) {
    //                 if(!empty($blog_content->content_image)) {
    //                     Storage::disk('public')->delete($blog_content->content_image);
    //                 }
    //                 $path = $request->file('content_image')->store('admin-assets/images/blogs/', 'public');
    //                 $blog_content->content_image = $path;
    //             }

    //             if($blog_content->save()) {
    //                 $request->session()->flash('success', 'Blog-Content is updated Successfully!');
    //                 return redirect()->route('edit.blog.content');
    //             }
    //             else {
    //                 $request->session()->flash('error', 'Updation Error!');
    //                 return redirect()->route('edit.blog.content');
    //             }
    //         }
    //         else {
    //             $id = 1;
    //             $blog_content = BlogContent::findOrFail($id);

    //             $main_page = 'blogs_management';
    //             $currentPage = "blog_content";
    //             return view('admin.blog_content-ops', ["blog_content" => $blog_content, 'main_page' => $main_page, 'currentPage' => $currentPage]);
    //         }
    //     }
    //     else {
    //         return redirect()->route('login');
    //     }
    // }
}
