<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str; // ✅ Required for slug

use App\Models\HomeContent;
use App\Models\AboutContent;
use App\Models\Service;
use App\Models\Specialty;
use App\Models\Faq;
use App\Models\AboutPage;

use App\Models\Setting;
use App\Models\Teacher;

use App\Models\Contact;
use App\Models\Course;
use App\Models\CourseCategory;
use App\Models\Testimonial;
use App\Models\BlogComment;
use App\Models\BlogPost;
use App\Models\BlogCategory;

class FrontController extends Controller
{
    public function index(){
        $homeContents = HomeContent::where('is_active', true)->latest()->first();
        $settings = Setting::getSettings();
       $aboutContents = AboutContent::where('is_active', true)->latest()->first();
$services = Service::where('is_active', true)->latest()->take(6)->get();
$nadee = Service::where('is_active', true)->latest()->take(9)->get();

$specialty = Specialty::where('is_active', true)->latest()->take(6)->get();
$testimonials = Testimonial::where('is_active', true)->latest()->take(6)->get();
    $blog = BlogPost::latest()->take(6)->get();

    $faqs = Faq::latest()->take(6)->get();

        $topCourses = Course::orderBy('total_students', 'desc')->take(3)->get();

    // Aggregate total students for all courses
    $totalStudents = Course::sum('total_students');

 $featuredCourses = Course::where('is_active', true)
                            ->where('is_featured', true)
                            ->latest()
                            ->take(6)
                            ->get();
$averageRating = Course::avg('ratings'); 
$averageSuccessRate = round(($averageRating / 5) * 100);

   $categories = CourseCategory::where('is_active', true)
        ->withCount('courses')
        ->orderBy('sort_order', 'asc')
        ->get();

        $teachers = Teacher::withCount('courses')
    ->where('is_active', true)
    ->where('is_featured', true)
    ->get();

$latestBlogs = BlogPost::with('category')
    ->where('robots', 'index, follow') // optional
    ->latest()
    ->take(6)
    ->get();

        return view('index', compact('homeContents', 'settings', 'aboutContents', 'services','specialty','testimonials','nadee','blog','faqs', 'topCourses', 'totalStudents', 'averageSuccessRate','featuredCourses','categories', 'teachers', 'latestBlogs')); 
    }
    
    public function services(){
        $services = Service::where('is_active', true)->latest()->get();
        $settings = Setting::getSettings();
        return view('services', compact('services', 'settings')); 
    }

        public function faq(){
     $faqs = Faq::all();

        return view('faq', compact('faqs')); 
    }
    
    public function specialties(){
        $specialties = Specialty::where('is_active', true)->latest()->get();
        $settings = Setting::getSettings();
        return view('specialties', compact('specialties', 'settings')); 
    }
    
    public function blogs(){
        $settings = Setting::getSettings();
            $blog = BlogPost::latest()->take(10)->get();
$blog = BlogPost::latest()->paginate(10);

        return view('blogs', compact('settings','blog')); 
    }
    
    public function contact(){
        $settings = Setting::getSettings();
        return view('contact', compact('settings')); 
    }
    
    public function about(){
$about = AboutPage::where('is_active', true)->first();
        
        if (!$about) {
            abort(404);
        }        $settings = Setting::getSettings();

        return view('about', compact('about', 'settings')); 
    }
    
    public function storeContact(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:255',
            'subject' => 'nullable|string|max:255',
            'message' => 'required|string',
        ]);

        Contact::create($request->all());

        return redirect()->back()->with('success', 'Thank you for your message. We will get back to you soon!')->withFragment('contact-form');
    }



public function serviceDetail($slug)
{
    $service = Service::where('slug', $slug)->firstOrFail();
    $relatedServices = Service::where('id', '!=', $service->id)->take(5)->get();
    $serviceall =Service::all();

    return view('service-detail', compact('service','relatedServices','serviceall'));
}

public function sepcialtyDetail($slug)
{
    $specialslug = Specialty::where('slug', $slug)->firstOrFail();
    $relatedSpecialty = Specialty::where('id', '!=', $specialslug->id)->take(5)->get();
    $specialtyall =Specialty::all();

    return view('specialty-detail', compact('specialslug','relatedSpecialty','specialtyall'));
}




   public function details($slug)
    {
        $post = BlogPost::where('slug', $slug)->first();
        $comments = BlogComment::where('post_id', $post->id)->whereNull('parent_id')->get();
    $totalComments = $post->comments->count() ;
   $recentPosts = BlogPost::latest()->take(5)->get();
    $blogCategories = BlogCategory::latest()->take(5)->get();
      $seoData = [
            'title' => $post->meta_title ?? $post->title,
            'description' => $post->meta_description ?? $post->short_description,
            'keywords' => $post->meta_keywords,
            'og_title' => $post->og_title ?? $post->meta_title ?? $post->title,
            'og_description' => $post->og_description ?? $post->meta_description ?? $post->short_description,
            'og_image' => $post->og_image ? asset('blogs/og/' . $post->og_image) : ($post->image ? asset('blogs/' . $post->image) : null),
            'canonical_url' => $post->canonical_url ?? url()->current(),
            'robots' => $post->robots
        ];
        return view('blog-detail', compact('post', 'comments', 'totalComments', 'recentPosts', 'blogCategories','seoData'));
    }

    public function postsByTag($tag)
{
    // Find posts where 'tags' column contains this tag
    $posts = BlogPost::where('tags', 'LIKE', "%$tag%")->get();

    return view('posts-by-tag', compact('posts', 'tag'));
}

public function categoryPosts($id)
{
    $category = BlogCategory::findOrFail($id);
    $posts = BlogPost::where('category_id', $id)->latest()->paginate(10);

    return view('category', compact('category', 'posts'));
}
 public function teacher()
{
    $teachers = Teacher::where('is_active', true)
                      ->withCount('courses')
                      ->latest()
                      ->paginate(10);
    
    // $settings = \App\Models\Setting::first(); // Ya jo bhi settings model hai
    
    // $seoData = [
    //     'title' => 'Our Instructors - ' . ($settings->site_name ?? 'AyzMedFlow'),
    //     'description' => 'Meet our team of experienced and qualified instructors dedicated to providing quality education.',
    //     'keywords' => 'instructors, teachers, faculty, educators, experts',
    //     'og_title' => 'Our Instructors - ' . ($settings->site_name ?? 'AyzMedFlow')
    // ];

    return view('teacher', compact('teachers'));
}
    





   public function teacherDetails(Teacher $teacher)
    {
        // Check if teacher is active
        if (!$teacher->is_active) {
            abort(404);
        }

        $settings = Setting::first();
        
        // Load teacher with courses
    
    $teacher = Teacher::where('id', $teacher->id)
                      ->with('courses')
                      ->withCount('courses')
                      ->firstOrFail();

        // Related teachers (same specialization)
        $relatedTeachers = Teacher::where('is_active', true)
                                 ->where('specialization', $teacher->specialization)
                                 ->where('id', '!=', $teacher->id)
                                 ->withCount('courses')
                                 ->take(3)
                                 ->get();

        // $seoData = [
        //     'title' => $teacher->meta_title ?? $teacher->name . ' - Instructor',
        //     'description' => $teacher->meta_description ?? $teacher->bio,
        //     'keywords' => $teacher->meta_keywords ?? $teacher->specialization . ', instructor, teacher',
        //     'og_title' => $teacher->meta_title ?? $teacher->name . ' - Instructor',
        //     'og_description' => $teacher->meta_description ?? $teacher->bio,
        //     'og_image' => $teacher->profile_image ? asset($teacher->profile_image) : asset('assets/images/default-teacher.jpg'),
        //     'canonical_url' => route('teacher.details', $teacher->slug)
        // ];

        return view('teacherdetails', compact('teacher', 'relatedTeachers','teacher'));
    }






}
