<?php

namespace App\Http\Controllers;

use App\Models\Routine;
use App\Models\Classes;
use App\Models\Teacher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class RoutineController extends Controller
{
    /**
     * Display routine management page
     */
    public function index()
    {
        $classes = Classes::where('status', 1)->get();
        $teachers = Teacher::active()->get();
        $days = Routine::getDays();
        $periods = Routine::getPeriods();

        return view('routines.index', compact('classes', 'teachers', 'days', 'periods'));
    }
    /**
 * Class wise result entry page
 */
public function classResult(Request $request)
{
    // URL থেকে প্যারামিটার নিন
    $classId = $request->class_id;
    $examType = $request->exam_type;
    $examYear = $request->exam_year;
    
    // যদি প্যারামিটার না থাকে, তাহলে ফর্ম দেখান
    if (!$classId || !$examType || !$examYear) {
        $classes = \App\Models\Classes::where('status', 1)->get();
        $examTypes = \App\Models\Result::getExamTypes();
        return view('results.select-class', compact('classes', 'examTypes'));
    }
    
    $class = \App\Models\Classes::findOrFail($classId);
    $students = \App\Models\Student::where('class_id', $classId)
                          ->where('status', 1)
                          ->orderBy('roll_number')
                          ->get();

    $subjects = \App\Models\Result::getSubjects($classId);
    
    $existingResults = \App\Models\Result::where('class_id', $classId)
                                 ->where('exam_type', $examType)
                                 ->where('exam_year', $examYear)
                                 ->exists();

    return view('results.class-entry', compact('class', 'students', 'subjects', 'examType', 'examYear', 'existingResults'));
}

    /**
     * Get routine by class and section
     */
    public function getRoutine(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required|exists:classes,id',
            'section' => 'required|string|max:10'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $routine = [];
        $days = Routine::getDays();
        
        foreach (array_keys($days) as $day) {
            $routine[$day] = Routine::with('teacher')
                                   ->where('class_id', $request->class_id)
                                   ->where('section', $request->section)
                                   ->where('day_of_week', $day)
                                   ->orderBy('period')
                                   ->get();
        }

        return response()->json($routine);
    }

    /**
     * Store routine entry
     */
    /**
 * Store routine entry
 */
public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'class_id' => 'required|exists:classes,id',
        'section' => 'required|string|max:10',
        'day_of_week' => 'required|in:saturday,sunday,monday,tuesday,wednesday,thursday,friday',
        'period' => 'required|integer|min:1|max:8',
        'start_time' => 'required|date_format:H:i',
        'end_time' => 'required|date_format:H:i|after:start_time',
        'subject' => 'required_if:is_break,0|string|max:255',
        'teacher_id' => 'required_if:is_break,0|exists:teachers,id',
        'room_number' => 'nullable|string|max:50',
        'is_break' => 'boolean',
        'break_name' => 'required_if:is_break,1|string|max:255'
    ]);

    if ($validator->fails()) {
        return redirect()->back()
                       ->withErrors($validator)
                       ->withInput();
    }

    // Check for conflicts
    if (!$request->is_break) {
        $teacherAvailable = Routine::checkTeacherAvailability(
            $request->teacher_id,
            $request->day_of_week,
            $request->start_time,
            $request->end_time
        );

        if (!$teacherAvailable) {
            return redirect()->back()
                           ->with('error', 'এই সময়ে শিক্ষক ইতিমধ্যে অন্য ক্লাসে ব্যস্ত আছেন')
                           ->withInput();
        }
    }

    try {
        Routine::create($request->all());

        return redirect()->route('routines.index')
                       ->with('success', 'রুটিন সফলভাবে সংরক্ষণ করা হয়েছে');

    } catch (\Exception $e) {
        return redirect()->back()
                       ->with('error', 'রুটিন সংরক্ষণে সমস্যা হয়েছে')
                       ->withInput();
    }
}

    /**
     * Update routine entry
     */
    public function update(Request $request, $id)
    {
        $routine = Routine::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i|after:start_time',
            'subject' => 'required_if:is_break,0|string|max:255',
            'teacher_id' => 'required_if:is_break,0|exists:teachers,id',
            'room_number' => 'nullable|string|max:50',
            'break_name' => 'required_if:is_break,1|string|max:255'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // Check for conflicts
        if (!$request->is_break && $request->teacher_id != $routine->teacher_id) {
            $teacherAvailable = Routine::checkTeacherAvailability(
                $request->teacher_id,
                $routine->day_of_week,
                $request->start_time,
                $request->end_time,
                $id
            );

            if (!$teacherAvailable) {
                return response()->json([
                    'error' => 'এই সময়ে শিক্ষক ইতিমধ্যে অন্য ক্লাসে ব্যস্ত আছেন'
                ], 422);
            }
        }

        try {
            $routine->update($request->all());

            return response()->json([
                'success' => true,
                'message' => 'রুটিন আপডেট করা হয়েছে'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'error' => 'রুটিন আপডেটে সমস্যা হয়েছে'
            ], 500);
        }
    }

    /**
     * Delete routine entry
     */
    public function destroy($id)
    {
        try {
            $routine = Routine::findOrFail($id);
            $routine->delete();

            return response()->json([
                'success' => true,
                'message' => 'রুটিন মুছে ফেলা হয়েছে'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'error' => 'রুটিন মুছতে সমস্যা হয়েছে'
            ], 500);
        }
    }

    /**
     * Bulk update routine
     */
    public function bulkUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required|exists:classes,id',
            'section' => 'required|string|max:10',
            'routines' => 'required|array',
            'routines.*.day' => 'required|string',
            'routines.*.periods' => 'required|array'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        DB::beginTransaction();

        try {
            // Delete existing routines for this class/section
            Routine::where('class_id', $request->class_id)
                   ->where('section', $request->section)
                   ->delete();

            // Create new routines
            foreach ($request->routines as $dayData) {
                foreach ($dayData['periods'] as $periodData) {
                    if (!empty($periodData['subject']) || !empty($periodData['is_break'])) {
                        Routine::create([
                            'class_id' => $request->class_id,
                            'section' => $request->section,
                            'day_of_week' => $dayData['day'],
                            'period' => $periodData['period'],
                            'start_time' => $periodData['start_time'],
                            'end_time' => $periodData['end_time'],
                            'subject' => $periodData['subject'] ?? null,
                            'teacher_id' => $periodData['teacher_id'] ?? null,
                            'room_number' => $periodData['room_number'] ?? null,
                            'is_break' => $periodData['is_break'] ?? false,
                            'break_name' => $periodData['break_name'] ?? null
                        ]);
                    }
                }
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'রুটিন সফলভাবে আপডেট করা হয়েছে'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Routine bulk update failed: ' . $e->getMessage());

            return response()->json([
                'error' => 'রুটিন আপডেটে সমস্যা হয়েছে'
            ], 500);
        }
    }

    /**
     * Generate routine template
     */
    public function generateTemplate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required|exists:classes,id',
            'section' => 'required|string|max:10',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i|after:start_time',
            'period_duration' => 'required|integer|min:30|max:60',
            'break_after' => 'required|integer|min:1|max:4',
            'break_duration' => 'required|integer|min:10|max:30'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                           ->withErrors($validator)
                           ->withInput();
        }

        // Calculate periods
        $totalMinutes = now()->parse($request->start_time)
                           ->diffInMinutes(now()->parse($request->end_time));
        
        $periods = [];
        $currentTime = now()->parse($request->start_time);
        $periodCount = 1;

        while ($currentTime < now()->parse($request->end_time)) {
            $periodEnd = $currentTime->copy()->addMinutes($request->period_duration);
            
            if ($periodCount == $request->break_after) {
                // Break period
                $breakEnd = $periodEnd->copy()->addMinutes($request->break_duration);
                
                $periods[] = [
                    'period' => $periodCount,
                    'start_time' => $currentTime->format('H:i'),
                    'end_time' => $periodEnd->format('H:i'),
                    'is_break' => true,
                    'break_name' => 'বিরতি'
                ];
                
                $currentTime = $breakEnd;
            } else {
                // Regular period
                $periods[] = [
                    'period' => $periodCount,
                    'start_time' => $currentTime->format('H:i'),
                    'end_time' => $periodEnd->format('H:i'),
                    'is_break' => false
                ];
                
                $currentTime = $periodEnd;
            }
            
            $periodCount++;
        }

        return view('routines.template', compact('periods', 'request'));
    }

    /**
     * Print routine
     */
    public function printRoutine($classId, $section)
    {
        $class = Classes::findOrFail($classId);
        $days = Routine::getDays();
        
        $routine = [];
        foreach (array_keys($days) as $day) {
            $routine[$day] = Routine::with('teacher')
                                   ->where('class_id', $classId)
                                   ->where('section', $section)
                                   ->where('day_of_week', $day)
                                   ->orderBy('period')
                                   ->get();
        }

        return view('routines.print', compact('class', 'section', 'routine', 'days'));
    }

    /**
     * Export routine as PDF
     */
    public function exportPdf($classId, $section)
    {
        $class = Classes::findOrFail($classId);
        $days = Routine::getDays();
        
        $routine = [];
        foreach (array_keys($days) as $day) {
            $routine[$day] = Routine::with('teacher')
                                   ->where('class_id', $classId)
                                   ->where('section', $section)
                                   ->where('day_of_week', $day)
                                   ->orderBy('period')
                                   ->get();
        }

        $pdf = Pdf::loadView('routines.pdf', compact('class', 'section', 'routine', 'days'));
        
        return $pdf->download('routine_' . $class->class_name . '_' . $section . '.pdf');
    }

    /**
     * Teacher wise routine
     */
    public function teacherRoutine($teacherId)
    {
        $teacher = Teacher::findOrFail($teacherId);
        $days = Routine::getDays();
        
        $routine = [];
        foreach (array_keys($days) as $day) {
            $routine[$day] = Routine::with('class')
                                   ->where('teacher_id', $teacherId)
                                   ->where('day_of_week', $day)
                                   ->orderBy('start_time')
                                   ->get();
        }

        return view('routines.teacher', compact('teacher', 'routine', 'days'));
    }

    /**
     * Classroom routine
     */
    public function roomRoutine($roomNumber)
    {
        $days = Routine::getDays();
        
        $routine = [];
        foreach (array_keys($days) as $day) {
            $routine[$day] = Routine::with('class', 'teacher')
                                   ->where('room_number', $roomNumber)
                                   ->where('day_of_week', $day)
                                   ->orderBy('start_time')
                                   ->get();
        }

        return view('routines.room', compact('roomNumber', 'routine', 'days'));
    }
}