<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\StudyGuide;
use App\Models\TeacherClass;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;
use Exception;
use Illuminate\Support\Facades\Auth;

class StudyGuideController extends Controller
{
    /**
     * Display All Study Guides without Trashed.
     */
    public function index()
    {
        try {
            $teacherId = Auth::guard('sanctum')->user()->id;
            $studyGuides = StudyGuide::select('id', 'study_guide_name', 'file', 'class_id', 'section', 'subject_id', 'teacher_id')->with(['teacher:id,first_name,last_name', 'classRelation:id,class_name', 'subject:id,subject_name'])->where('teacher_id', $teacherId)->latest()->get();
            if ($studyGuides->isEmpty()) {
                return response()->json([
                    'response_status' => 400
                ], 200);
            }
            $data = ['study_guides' => $studyGuides];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Display All Study Guides with Trashed.
     */
    public function withTrashed()
    {
        try {
            $studyGuides = StudyGuide::with(['teacher', 'classRelation', 'section', 'subject'])->withTrashed()->latest()->get();
            if ($studyGuides->isEmpty()) {
                return response()->json([
                    'response_status' => 400
                ], 200);
            }
            $data = ['study_guides' => $studyGuides];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Display Only Trashed Study Guides.
     */
    public function trash()
    {
        try {
            $studyGuides = StudyGuide::with(['teacher', 'classRelation', 'section', 'subject'])->onlyTrashed()->latest()->get();
            if ($studyGuides->isEmpty()) {
                return response()->json([
                    'response_status' => 400
                ], 200);
            }
            $data = ['study_guides' => $studyGuides];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Display Restore Trashed Study Guides.
     */
    public function restore(string $id)
    {
        try {
            $studyGuide = StudyGuide::with(['teacher', 'classRelation', 'section', 'subject'])->onlyTrashed()->find($id);
            if (!$studyGuide) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $studyGuide->restore();
            $data = ['study_guide' => $studyGuide];
            return response()->json([
                'data' => $data,
                'response_message' => ['success' => ['Study Guide Restored Successfully!']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            // Validate the request inputs
            $validation = Validator::make($request->all(), [
                'teacher_class_id' => 'required|exists:teacher_classes,id',
                'study_guide_name' => 'required|string',
                'file' => 'nullable|file|mimes:pdf,docx|max:2048',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            // Initialize filename variable
            $filename = '';

            // Check if file is uploaded
            if ($request->hasFile('file')) {
                $file = $request->file('file');
                $extension = $file->getClientOriginalExtension();

                // Get the original filename without extension
                $originalFileName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                $formattedName = str_replace(' ', '_', $originalFileName); // Replace spaces with underscores

                // Set the base path for storing files
                $path = public_path('uploads/study_guides/');
                $filename = $formattedName . '.' . $extension; // Default filename based on the original file name

                // Check if file with the same name exists, and handle numbering
                $counter = 0;
                while (file_exists($path . $filename)) {
                    $counter++;
                    $filename = $formattedName . '_' . $counter . '.' . $extension; // Add numbering if file exists
                }

                // Move the file to the final path
                $file->move($path, $filename);
            }

            $teacherClass = TeacherClass::find($request->teacher_class_id);

            // Store the new study guide in the database
            $studyGuide = StudyGuide::create([
                'teacher_id' => $teacherClass->teacher_id,
                'class_id' => $teacherClass->class_id,
                'year' => $teacherClass->year,
                'section' => $teacherClass->section,
                'subject_id' => $teacherClass->subject_id,
                'study_guide_name' => $request->study_guide_name,
                'file' => $filename,
            ]);

            // Generate the download link for the uploaded file
            $downloadLink = asset('uploads/study_guides/' . $filename);

            // Include the download link in the study guide response
            $studyGuide->download_link = $downloadLink;

            // Return success response with the created study guide data
            return response([
                'response_status' => 200,
                'response_message' => ['success' => ['Study Guide Created Successfully!']],
                'data' => [
                    'study_guide' => $studyGuide
                ]
            ], 200);
        } catch (Exception $e) {
            // Catch any exceptions and return an error response
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        try {
            $teacherId = Auth::guard('sanctum')->user()->id;
            $studyGuide = StudyGuide::select('id', 'study_guide_name', 'file', 'class_id', 'section', 'subject_id', 'teacher_id')->with(['teacher:id,first_name,last_name', 'classRelation:id,class_name', 'subject:id,subject_name'])->where('teacher_id', $teacherId)->find($id);
            if (!$studyGuide) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['study_guide' => $studyGuide];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Update the Active Study Guide.
     */
    public function activeStudyGuide(Request $request, string $id)
    {
        try {

            $validation = Validator::make($request->all(), [
                'id' => 'nullable|exists:study_guides,id',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            // Find the class by ID
            $studyGuide = StudyGuide::find($id);
            if (!$studyGuide) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $studyGuide->is_active = !$studyGuide->is_active;
            $studyGuide->save();

            $data = ['studyGuide' => $studyGuide];
            return response()->json([
                'data' => $data,
                'response_message' => ['success' => ['Study Guide Status Updated Successfully!']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    // public function update(Request $request, string $id)
    // {
    //     try {
    //         $validation = Validator::make($request->all(), [
    //             'teacher_id' => 'required|exists:teachers,id',
    //             'class_id' => 'required|exists:classes,id',
    //             'section_id' => 'required|exists:sections,id',
    //             'subject_id' => 'required|exists:subjects,id',
    //             'file' => 'nullable|file|mimes:pdf,docx|max:2048',
    //         ]);

    //         if ($validation->fails()) {
    //             return response()->json([
    //                 'validation_errors' => $validation->messages(),
    //                 'response_status' => 400,
    //             ], 200);
    //         }

    //         // Find the study guide
    //         $studyGuide = StudyGuide::find($id);
    //         if (!$studyGuide) {
    //             return response()->json([
    //                 'validation_errors' => ['not_found' => ['No Data Found!']],
    //                 'response_status' => 400
    //             ], 200);
    //         }

    //         // File Upload Process
    //         $filename = $studyGuide->file; // Keep the existing file name initially

    //         if ($request->hasFile('file')) {
    //             $file = $request->file('file');
    //             $extension = $file->getClientOriginalExtension();

    //             // Use original file name (excluding extension) for checking and saving
    //             $originalFileName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
    //             $formattedName = str_replace(' ', '_', $originalFileName); // Replace spaces with underscores
    //             $filename = $formattedName . '.' . $extension; // Default filename with extension
    //             $path = public_path('uploads/study_guides/');

    //             // Check if the file with the same name exists, and handle numbering
    //             $counter = 0;
    //             while (file_exists($path . $filename)) {
    //                 $counter++;
    //                 $filename = $formattedName . '_' . $counter . '.' . $extension; // Add numbering if file exists
    //             }

    //             // Delete the old file if it exists
    //             if ($studyGuide->file && file_exists($path . $studyGuide->file)) {
    //                 unlink($path . $studyGuide->file);
    //             }

    //             // Move the new file to the path with the incremented or original name
    //             $file->move($path, $filename);

    //             // Update the study guide file with the new file name
    //             $studyGuide->file = $filename;
    //         }

    //         // Update other fields
    //         $studyGuide->teacher_id = $request->teacher_id;
    //         $studyGuide->class_id = $request->class_id;
    //         $studyGuide->section_id = $request->section_id;
    //         $studyGuide->subject_id = $request->subject_id;
    //         $studyGuide->study_guide_name = $request->study_guide_name;
    //         $studyGuide->save();

    //         // Construct the download link for the updated file
    //         $downloadLink = asset('uploads/study_guides/' . $studyGuide->file);

    //         // Include the download link in the study guide response
    //         $studyGuide->download_link = $downloadLink;

    //         return response([
    //             'response_status' => 200,
    //             'response_message' => ['success' => ['Study Guide Updated Successfully!']],
    //             'data' => [
    //                 'study_guide' => $studyGuide
    //             ]
    //         ], 200);
    //     } catch (Exception $e) {
    //         return response()->json([
    //             'validation_errors' => $e->getMessage(),
    //             'response_status' => 400,
    //         ], 200);
    //     }
    // }

    public function update(Request $request, string $id)
    {
        try {
            // Validate the request inputs
            $validation = Validator::make($request->all(), [
                'teacher_class_id' => 'required|exists:teacher_classes,id',
                'study_guide_name' => 'required|string',
                'file' => 'nullable|file|mimes:pdf,docx|max:2048',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            // Find the study guide by ID
            $studyGuide = StudyGuide::find($id);
            if (!$studyGuide) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400,
                ], 200);
            }

            // Initialize filename variable with the existing file name
            $filename = $studyGuide->file;

            // Check if a new file is uploaded
            if ($request->hasFile('file')) {
                $file = $request->file('file');
                $extension = $file->getClientOriginalExtension();

                // Get the original filename without extension
                $originalFileName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                $formattedName = str_replace(' ', '_', $originalFileName); // Replace spaces with underscores
                $filename = $formattedName . '.' . $extension; // Default filename based on the original file name
                $path = public_path('uploads/study_guides/');

                // Check if file with the same name exists, and handle numbering
                $counter = 0;
                while (file_exists($path . $filename)) {
                    $counter++;
                    $filename = $formattedName . '_' . $counter . '.' . $extension; // Add numbering if file exists
                }

                // Delete the old file if it exists
                if ($studyGuide->file && file_exists($path . $studyGuide->file)) {
                    unlink($path . $studyGuide->file);
                }

                // Move the new file to the final path
                $file->move($path, $filename);
            }

            // Update study guide details based on the related teacher class
            $teacherClass = TeacherClass::find($request->teacher_class_id);

            // Update the study guide fields
            $studyGuide->teacher_id = $teacherClass->teacher_id;
            $studyGuide->class_id = $teacherClass->class_id;
            $studyGuide->year = $teacherClass->year;
            $studyGuide->section = $teacherClass->section;
            $studyGuide->subject_id = $teacherClass->subject_id;
            $studyGuide->study_guide_name = $request->study_guide_name;
            $studyGuide->file = $filename;
            $studyGuide->save();

            // Generate the download link for the uploaded file
            $downloadLink = asset('uploads/study_guides/' . $filename);

            // Include the download link in the study guide response
            $studyGuide->download_link = $downloadLink;

            // Return success response with the updated study guide data
            return response([
                'response_status' => 200,
                'response_message' => ['success' => ['Study Guide Updated Successfully!']],
                'data' => [
                    'study_guide' => $studyGuide
                ]
            ], 200);
        } catch (Exception $e) {
            // Catch any exceptions and return an error response
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }



    /**
     * Temporary Remove from storage.
     */
    public function delete(string $id)
    {
        try {
            $studyGuide = StudyGuide::find($id);
            if (!$studyGuide) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }

            // Delete File From Folder
            if ($studyGuide->file && File::exists(public_path('uploads/study_guides/' . $studyGuide->file))) {
                File::delete(public_path('uploads/study_guides/' . $studyGuide->file));
            }

            $studyGuide->forceDelete();
            $data = ['study_guide' => $studyGuide];
            return response()->json([
                'response_message' => ['success' => ['Study Guide Deleted Successfully!']],
                'response_status' => 200,
                'data' => $data
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Permanently Remove Study Guide from storage.
     */
    public function destroy(string $id)
    {
        try {
            $studyGuide = StudyGuide::find($id);
            if (!$studyGuide) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }

            // Delete File From Folder
            if ($studyGuide->file && File::exists(public_path('uploads/study_guides/' . $studyGuide->file))) {
                File::delete(public_path('uploads/study_guides/' . $studyGuide->file));
            }

            $studyGuide->forceDelete();
            return response()->json([
                'response_message' => ['success' => ['Study Guide Deleted Successfully!']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
}
