<?php

namespace App\Http\Controllers\Student;
use PDF;
use Carbon\Carbon;
use App\Models\Result\Grade;
use Illuminate\Http\Request;
use App\Models\Result\MarkHead;
use App\Models\Hsc\GroupSubject;
use Illuminate\Support\Facades\DB;
use App\Exports\StudentsInfoExport;
use App\Imports\StudentsInfoImport;
use App\Models\Student\StudentInfo;
use App\Http\Controllers\Controller;
use App\Models\HrPayroll\Occupation;
use App\Services\StudentInfoService;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;
use App\Http\Requests\StudentInfoRequest;
use App\Models\Academic\SubjectsAssign;
use App\Models\Guardian\GuardianRelation;

class StudentInfoController extends Controller
{

    protected $studentInfoService;

    public function __construct(StudentInfoService $studentInfoService)
    {
        $this->studentInfoService = $studentInfoService;
    }

    public function view(Request $request, $student_id){
        $this->authorize('student.student-list.view');

        $occupations = Occupation::pluck('name', 'id');
        $guardian_relations = GuardianRelation::pluck('name', 'id');
        $studentInfo = StudentInfo::with([
            'shift', 'studentClass', 'section', 'group',
            'studentHostel.hostel', 'studentHostel.hostelFloor',
            'studentHostel.hostelRoom.roomType', 'studentTransport.transportRoute',
            'studentTransport.stoppage', 'siblings','guardianInfo','branch'
        ])->where('student_id_no', $student_id)->first();   

        $fees = $this->studentInfoService->getStudentFees($studentInfo->student_id_no,$studentInfo->branch_id,$studentInfo->id, $studentInfo->student_class_id);
        $examMarks = $this->studentInfoService->getStudentResults($studentInfo->id);
        $attendanceStatsCount = $this->studentInfoService->attendanceStatsCount($studentInfo->id);
        $markHeads = MarkHead::all();
        
        // Fetch attendance data for the student
        $attendanceData = DB::table('student_attendances')
        ->select('student_id', DB::raw('DAY(created_at) as day'), DB::raw('MONTH(created_at) as month'), 'is_present', 'is_absent', 'is_late')
        ->where('student_id', $studentInfo->id)
        ->whereYear('created_at', now()->year) // Filter for the current year
        ->get();

        // Organize the data by month and day
        $attendanceByDay = [];
        foreach ($attendanceData as $attendance) {
            $attendanceByDay[$attendance->month][$attendance->day] = [
                'is_present' => $attendance->is_present,
                'is_absent' => $attendance->is_absent,
                'is_late' => $attendance->is_late
            ];
        }
        $grades =  Grade::all();
   
        return view('pages.students.student_infos.student-all-info', compact('studentInfo', 'occupations', 'guardian_relations','fees','examMarks','grades','markHeads','attendanceStatsCount','attendanceByDay'));
    }


    public function calculateAge($birthdate)
    {
        // Parse the birthdate
        $birthdate = Carbon::createFromFormat('d-m-Y', $birthdate);
        
        // Get the current date (now)
        $now = Carbon::now();
        
        // Calculate the difference
        $age = $birthdate->diff($now);
        
        // Return formatted age
        return $age->format('%y Years, %m Months, %d Days');
    }




    public function show(Request $request)
    {
        $occupations = Occupation::pluck('name', 'id');
        $guardian_relations = GuardianRelation::pluck('name', 'id');
        $studentInfo = StudentInfo::with([
            'shift', 'studentClass', 'section', 'group',
            'studentHostel.hostel', 'studentHostel.hostelFloor',
            'studentHostel.hostelRoom.roomType', 'studentTransport.transportRoute',
            'studentTransport.stoppage', 'siblings'
        ])->where('id', $request->student_id)->first();
        return view('pages.students.student_infos.show', compact('studentInfo', 'occupations', 'guardian_relations'));
    }

    public function index(Request $request)
    {
        // DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        // DB::table('invoices')->truncate(); // child table
        // DB::table('student_infos')->truncate(); // parent table
        // DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        $data = $this->studentInfoService->getRelatedData();
        if ($request->ajax()) {
            if (!empty($request->query())) {
                $students = $this->studentInfoService->getStudents($request->query());
            } else {
                $students = collect();
            }
            return DataTables::of($students)->make(true);
        }

        if (!empty($request->query())) {
            $data['students'] = $this->studentInfoService->getStudents($request->query());
        } else {
            $data['students'] = collect();
        }
        // dd($data, $request->all());
        return view('pages.students.student_infos.index')->with($data);
    }

    //===============Auto Complete Search===================//
    public function searchStudent(Request $request)
    {
        $students = $this->studentInfoService->searchStudent($request->get('query'));
       
        return response()->json($students);
    }


    public function create()
    {
        $this->authorize('student.student-list.create');
        
        $data = $this->studentInfoService->getFormData();
        $data['compulsory_subjects'] = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $data['subjects'] = SubjectsAssign::where('student_class_id', 13)->get();
        // dd($data);
        return view('pages.students.student_infos.create')->with($data);
    }

    public function store(StudentInfoRequest $request)
    {
        $this->authorize('student.student-list.create');
        try {
            $this->studentInfoService->createStudentInfo($request);
            return redirect()->route('student_info.index')->with('success', 'Student information created successfully.');
        } catch (\Exception $e) {
            return back()->withErrors($e->getMessage())->withInput();
        }
    }


    public function edit(StudentInfo $studentInfo)
    {
        $this->authorize('student.student-list.edit');
        $data = $this->studentInfoService->getFormData();
        unset($data['student_id_no']);
        $studentInfo->load('siblings');
        $data['studentInfo'] = $studentInfo;
        $data['compulsory_subjects'] = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $data['subjects'] = SubjectsAssign::where('student_class_id', 13)->get();

        $electiveSubjects = $studentInfo->StudentInfoSubjectClass()->where('subject_type', 'elective')->get();
        $data['studentElectiveSubjects'] = $electiveSubjects->pluck('subject_id')->toArray();

        $data['optionalSubject'] = $studentInfo->StudentInfoSubjectClass()->where('subject_type', 'optional')->first();
        // dd($data);
        return view('pages.students.student_infos.edit')->with($data);
    }


    public function update(Request $request, $id)
    {
        $this->authorize('student.student-list.edit');
        try {
            $this->studentInfoService->updateStudentInfo($request, $id);
            return redirect()->route('student_info.index')->with('success', 'Student information updated successfully');
        } catch (\Exception $e) {
            return redirect()->route('student_info.index')->with('warning', $e->getMessage());
        }
    }

    public function destroy($id)
    {
        $this->authorize('student.student-list.delete');
        $this->studentInfoService->deleteStudentInfo($id);
        return redirect()->route('student_info.index')
            ->with('success', 'Student information deleted successfully');
    }


    //--------Student Info Import/Export-------------

    public function showImportForm()
    {
        return view('pages.students.import.create');
    }

    public function importStudentInfo(Request $request, StudentsInfoImport $import)
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls',
        ]);

        $file = $request->file('file');

        try {
            Excel::import($import, $file);
            $importResult = $import->getImportResult();

            if ($importResult['status'] == true) {
                $meaasge = "{$importResult['imported']} imported successfully and {$importResult['duplicate']} duplicate found!";
                return redirect()->back()->with('success', $meaasge);
            } else {
                return redirect()->back()->with('warning', "Falied to import student data");
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('warning', $e->getMessage());
        }
    }

    public function exportStudentInfo(Request $request)
    {
        $filters = $request->only(['branch', 'shift', 'group', 'student_class', 'section']);
        return Excel::download(new StudentsInfoExport($filters), 'students.xlsx');
    }

    public function studentIDCard(Request $request)
    {

        $data = $this->studentInfoService->getRelatedData();
        $students = $this->studentInfoService->getStudents($request->query());
        $data['students'] = $students;
        $data['student_name'] = $this->studentInfoService->getStudentNameWithID($request->student_id_no, $students);
        // dd($data);
        return view('pages.students.id-card.index',$data);
    }

    public function studentIdCardDownload(Request $request){
        $data = $this->studentInfoService->getRelatedData();
        $students = $this->studentInfoService->getStudents($request->query());
        $data['students'] = $students;
        $data['student_name'] = $this->studentInfoService->getStudentNameWithID($request->student_id_no, $students);
        // dd($request->all(), $data);
        $customPaper = array(0,0,360,460);
        $pdf = PDF::loadView('pages.students.pdf.studentIDCard', $data)->setPaper($customPaper);
        return $pdf->download('document.pdf');
        // return $pdf->stream();
    }

    public function studentStatusUpdate(Request $request)
    {
        $student = StudentInfo::findOrFail($request->id);
        $student->status = $request->status;
        $student->save();

        return response()->json([
            'success' => true,
            'message' => 'Status updated successfully'
        ]);
    }


    

    

}
