<?php

namespace App\Http\Controllers;

use App\Models\Classe;
use App\Models\Section;
use App\Models\Staff_member;
use App\Models\Subject;
use App\Models\teacher_timetable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;

class TeacherTimeTableController extends Controller
{
    public function timetable()
    {
        // $teachers = Teacher::all(); // Assuming you have a Teacher model
        // $timetables = Timetable::with('teacher', 'class', 'subject')->get(); // Assuming you have a Timetable model
        $teachers = Staff_member::where('status', 'active')->whereHas('job_position', function ($query) {
           // $query->where('title', 'Teacher');
        })->get();
        $classes = Classe::all();
        $subjects = Subject::all();
        $sections = Section::all();
        // $timetable = Teacher_timetable::with('staff_member')->first();
        $timetables = Staff_member::where('status', 'active')->with([
            'teacher_timetables',
            'teacher_timetables.subjects',
            'teacher_timetables.classes',
            'teacher_timetables.sections'
        ])->whereHas('job_position', function ($query) {
           // $query->where('title', 'Teacher');
        })->get();
        return view('timeTable.teacherTimeTbl', compact('teachers', 'timetables', 'classes', 'subjects', 'sections'));
    }

    public function pdfTeacherTimetable(Request $request)
    {
        $teacherId = $request->input('teacher_id');

        $query = Staff_member::where('status', 'active')
            ->with([
                'teacher_timetables',
                'teacher_timetables.subjects',
                'teacher_timetables.classes',
                'teacher_timetables.sections'
            ]);

        if ($teacherId) {
            $query->where('id', $teacherId);
        }

        $timetables = $query->get();

        $pdf = Pdf::loadView('timeTable.pdfTeacherTimetable', [
            'timetables' => $timetables,
        ]);

        return $pdf->download('teacher_timetable.pdf');
    }


    public function store(Request $request)
    {
        $request->validate([
            'teacher_id' => 'required|exists:staff_members,id',
            'class_id' => 'required|exists:classes,id',
            'section_id' => 'required|exists:sections,id',
            'subject_id' => 'required|exists:subjects,id',
            'start_time' => 'required',
            'end_time' => 'required',
        ]);

        // Check for teacher availability
        $teacherConflict = teacher_timetable::where('teacher_id', $request->teacher_id)
            ->where(function ($query) use ($request) {
                $query->whereBetween('start_time', [$request->start_time, $request->end_time])
                    ->orWhereBetween('end_time', [$request->start_time, $request->end_time])
                    ->orWhere(function ($q) use ($request) {
                        $q->where('start_time', '<=', $request->start_time)
                            ->where('end_time', '>=', $request->end_time);
                    });
            })
            ->exists();

        if ($teacherConflict) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'This teacher already has a class scheduled during this time slot.');
        }

        // Check for class-section availability
        $classConflict = Teacher_timetable::where('class_id', $request->class_id)
            ->where('section_id', $request->section_id)
            ->where(function ($query) use ($request) {
                $query->whereBetween('start_time', [$request->start_time, $request->end_time])
                    ->orWhereBetween('end_time', [$request->start_time, $request->end_time])
                    ->orWhere(function ($q) use ($request) {
                        $q->where('start_time', '<=', $request->start_time)
                            ->where('end_time', '>=', $request->end_time);
                    });
            })
            ->exists();

        if ($classConflict) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'This class-section already has a scheduled class during this time.');
        }

        DB::beginTransaction();

        try {
            $teacherTimetable = new Teacher_timetable();
            $teacherTimetable->teacher_id = $request->input('teacher_id');
            $teacherTimetable->class_id = $request->input('class_id');
            $teacherTimetable->section_id = $request->input('section_id');
            $teacherTimetable->subject_id = $request->input('subject_id');
            $teacherTimetable->start_time = $request->input('start_time');
            $teacherTimetable->end_time = $request->input('end_time');
            $teacherTimetable->save();

            DB::commit();

            return redirect()->back()->with('success', 'Teacher timetable added successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()
                ->withInput()
                ->with('error', 'Failed to add timetable: ' . $e->getMessage());
        }
    }
}
