<?php

namespace App\Http\Controllers;

use App\Models\Home;
use App\Models\AboutUs;
use App\Models\AboutUsMessage;
use App\Models\Academic;
use App\Models\applynowInfo;
use App\Models\Facility;
use App\Models\Facilitymember;
use App\Models\StudentLife;
use App\Models\StudentLifeEvents;
use App\Models\Gallery;
use App\Models\NewsEvent;
use App\Models\NewEventContain;
use App\Models\Program;
use App\Models\Semester;
use App\Models\Subject;
use App\Models\Alumni;
use App\Models\AlumniMember;
use App\Models\Zone;
use App\Models\IndividualZone;
use App\Models\Library;
use App\Models\Game;
use App\Models\OnlineResources;
use App\Models\RequestInfo;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index()
    {
        $home = Home::first();
        $about = AboutUs::first();
        $gallery = Gallery::all();
        $newEventContain = NewEventContain::all();
        $program = Program::all();
        return view('Pages.home',compact('home','about','gallery','newEventContain','program'));
    }
     public function about(){
        $about = AboutUs::first();
        $AboutUsMessage = AboutUsMessage::all();
        return view('Pages.aboutUs',compact('about','AboutUsMessage'));
    }
    public function academic(){
        $academic = Academic::first();
        $programs = Program::take($academic->programs_count)->get();
        return view('Pages.academic',compact('academic','programs'));
    }
    public function applynowInfo(){
        $applynowInfo = applynowInfo::first();
        return view('Pages.applynowInfo',compact('applynowInfo'));
    }
   public function facility(){
    $facility = Facility::first();
    $facilitymember = Facilitymember::all();
    return view('Pages.faculties',compact('facility','facilitymember'));
   }
   public function studentLife(){
    $studentLife = StudentLife::first();
    $studentLifeEvents = StudentLifeEvents::all();
    return view('Pages.studentLife',compact('studentLife','studentLifeEvents'));
   }
   public function gallery(){
    $gallery = Gallery::first();
    return view('Pages.gallery',compact('gallery'));
   }
   public function news(){
    $news = NewsEvent::first();
    $newEventContain = NewEventContain::take($news->news_count)->get();
    return view('Pages.news_events',compact('news','newEventContain'));
   }
   public function alumni(){
    $alumni = Alumni::first();
    $alumniMember = AlumniMember::all();
    return view('Pages.alumni',compact('alumni','alumniMember'));
   }
   public function club(){
    $zone = Zone::first();
    $individualZone = IndividualZone::all();
    return view('Pages.club',compact('zone','individualZone'));
   }
   public function library(){
    $library = Library::first();
    $onlineResources = OnlineResources::all();
    return view('Pages.library',compact('library','onlineResources'));
   }
   public function requestinfo(){
    $requestinfo = RequestInfo::first();
    return view('Pages.requestinfo',compact('requestinfo'));
   }
   public function search(Request $request)
    {
        $search = $request->search;
        $result = NewsEvent::where('title','like','%'.$search.'%')->get();
        $games = Game::where('title','like','%'.$search.'%')->get();
        $individualZone = IndividualZone::where('title','like','%'.$search.'%')->get();
        $onlineResource = OnlineResources::where('title','like','%'.$search.'%')->get();

        return view('Pages.search',compact('result','games','individualZone','onlineResource'));
    }
    public function IndividualNews($id){
        $newEventContain = NewEventContain::where('id',$id)->first();
        return view('Pages.individualnews',compact('newEventContain'));
    }
    public function IndividualGame($id){
        $game = Game::with('individualZone')->where('id',$id)->first();
        return view('Pages.individualGame',compact('game'));
    }
    public function IndividualZone($id){
        $individualZone = IndividualZone::where('id',$id)->first();
        return view('Pages.individualZone',compact('individualZone'));
    }
    public function Program($id){
        $program = Program::findOrFail($id);
        $semesters = $program->semesters()->with('subjects')->get();
        $subjects = Subject::whereIn('semester_id', $semesters->pluck('id'))->get();

        return view('Pages.program', compact('program', 'semesters', 'subjects'));
    }

    // Search and filter online resources
    public function searchOnlineResources(Request $request)
    {
        $query = OnlineResources::query()
            ->with(['program', 'semester', 'subject']);

        // Search functionality
        if ($request->has('search') && !empty($request->search)) {
            $searchTerm = $request->search;
            $query->where(function($q) use ($searchTerm) {
                $q->where('file_name', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('file_category', 'LIKE', "%{$searchTerm}%")
                  ->orWhereHas('program', function($programQuery) use ($searchTerm) {
                      $programQuery->where('main_title', 'LIKE', "%{$searchTerm}%");
                  })
                  ->orWhereHas('semester', function($semesterQuery) use ($searchTerm) {
                      $semesterQuery->where('name', 'LIKE', "%{$searchTerm}%");
                  })
                  ->orWhereHas('subject', function($subjectQuery) use ($searchTerm) {
                      $subjectQuery->where('name', 'LIKE', "%{$searchTerm}%");
                  });
            });
        }

        // Filter functionality
        if ($request->has('filter') && !empty($request->filter)) {
            switch ($request->filter) {
                case 'latest':
                    $query->orderBy('file_released_date', 'desc');
                    break;
                case 'oldest':
                    $query->orderBy('file_released_date', 'asc');
                    break;
                case 'most_downloaded':
                    $query->orderBy('file_download_count', 'desc');
                    break;
                case 'least_downloaded':
                    $query->orderBy('file_download_count', 'asc');
                    break;
                default:
                    $query->orderBy('created_at', 'desc');
            }
        } else {
            $query->orderBy('created_at', 'desc');
        }

        $resources = $query->get();

        return response()->json([
            'success' => true,
            'data' => $resources,
            'count' => $resources->count()
        ]);
    }

    // Download online resource and increment download count
    public function downloadOnlineResource($id)
    {
        $resource = OnlineResources::findOrFail($id);

        // Increment download count
        $resource->increment('file_download_count');

        // Get file path
        $filePath = storage_path('app/public/' . $resource->file);

        // Check if file exists
        if (!file_exists($filePath)) {
            abort(404, 'File not found');
        }

        // Get file extension and mime type
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        $mimeType = mime_content_type($filePath);

        // Return file download response
        return response()->download($filePath, $resource->file_name . '.' . $extension, [
            'Content-Type' => $mimeType,
            'Content-Disposition' => 'attachment; filename="' . $resource->file_name . '.' . $extension . '"'
        ]);
    }
    public function getOnlineResourceCount($id)
    {
        $resource = OnlineResources::findOrFail($id);
        return response()->json(['count' => $resource->file_download_count]);
    }
}
