<?php

namespace App\Http\Controllers\Api\Teacher;

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

class RevisionWizardController extends Controller
{
    /**
     * Display All Revision Wizards
     */
    public function index()
    {
        try {
            $teacherId = Auth::guard('sanctum')->user()->id;
            $revisionWizards = RevisionWizard::select('id', 'title', 'file', 'class_id', 'section', 'year', 'subject_id', 'teacher_id', 'issue_date','teacher_class_id')->with(['teacher:id,first_name,last_name', 'classRelation:id,class_name', 'subject:id,subject_name'])->where('teacher_id', $teacherId)->latest()->get();
            if ($revisionWizards->isEmpty()) {
                return response()->json([
                    'response_status' => 400
                ], 200);
            }
            // Map data to the required format
            $formattedData = $revisionWizards->map(function ($item) {
                $downloadLink = asset('uploads/revision_wizards/' . $item->file);
                $viewLink = 'https://docs.google.com/gview?url=' . urlencode($downloadLink) . '&embedded=true';
                return [
                    'id' => $item->id,
                    'teacher_class_id' => $item->teacher_class_id,
                    'title' => $item->title,
                    'file' => $item->file,
                    'download_link' => $downloadLink,
                    'view_link' => $viewLink,
                    'class_id' => $item->class_id,
                    'section' => $item->section,
                    'year' => $item->year,
                    'issue_date' => $item->issue_date,
                    'subject_id' => $item->subject_id,
                    'class_name' => $item->classRelation->class_name ?? null,
                    'subject_name' => $item->subject->subject_name ?? null,
                    'teacher_id' => $item->teacher_id,
                    'teacher' => [
                        'id' => $item->teacher->id,
                        'first_name' => $item->teacher->first_name,
                        'last_name' => $item->teacher->last_name,
                    ]
                ];
            });

            return response()->json([
                'data' => ['revision_wizards' => $formattedData],
                '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)
    {
        // dd($request->all());
        try {
            // Validate the request inputs
            $validation = Validator::make($request->all(), [
                'teacher_id' => 'required|exists:teachers,id',
                'teacher_class_id' => 'required|exists:teacher_classes,id',
                'title' => 'required|string',
                'file' => 'required|file|mimes:pptx|max:102400',
            ]);

            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/revision_wizards/');
                $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);

            // Get current date and time
            $currentLocalDateTime = Carbon::now()->format('Y-m-d H:i:s');

            // Store the new study guide in the database
            $revisionWizard = RevisionWizard::create([
                'teacher_id' => $request->teacher_id,
                'teacher_class_id' => $request->teacher_class_id,
                'class_id' => $teacherClass->class_id,
                'year' => $teacherClass->year,
                'section' => $teacherClass->section,
                'subject_id' => $teacherClass->subject_id,
                'title' => $request->title,
                'file' => $filename,
                'issue_date' => $currentLocalDateTime,
            ]);

            // Generate the download and view links for the uploaded file
            $downloadLink = asset('uploads/revision_wizards/' . $filename);
            $viewLink = 'https://docs.google.com/gview?url=' . urlencode($downloadLink) . '&embedded=true';

            // Include the download and view links in the response
            $revisionWizard->download_link = $downloadLink;
            $revisionWizard->view_link = $viewLink;

            // Return success response with the created study guide data
            return response([
                'response_status' => 200,
                'response_message' => ['success' => ['Revision Wizard Created Successfully!']],
                'data' => [
                    'study_guide' => $revisionWizard
                ]
            ], 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;
            $revisionWizard = RevisionWizard::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 (!$revisionWizard) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['study_guide' => $revisionWizard];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 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_id' => 'required|exists:teachers,id',
                'teacher_class_id' => 'required|exists:teacher_classes,id',
                'title' => 'required|string',
                'file' => 'nullable|file|mimes:pptx|max:102400',
            ]);

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

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

            // Initialize filename variable with the existing file name
            $filename = $revisionWizard->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/revision_wizards/');

                // 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 ($revisionWizard->file && file_exists($path . $revisionWizard->file)) {
                    unlink($path . $revisionWizard->file);
                }

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

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

            // Update the revision wizard fields
            $revisionWizard->teacher_id = $request->teacher_id;
            $revisionWizard->teacher_class_id = $request->teacher_class_id;
            $revisionWizard->class_id = $teacherClass->class_id;
            $revisionWizard->year = $teacherClass->year;
            $revisionWizard->section = $teacherClass->section;
            $revisionWizard->subject_id = $teacherClass->subject_id;
            $revisionWizard->title = $request->title;
            $revisionWizard->file = $filename;
            $revisionWizard->save();

            // Generate the download and view links for the uploaded file
            $downloadLink = asset('uploads/revision_wizards/' . $filename);
            $viewLink = 'https://docs.google.com/gview?url=' . urlencode($downloadLink) . '&embedded=true';

            // Include the download and view links in the response
            $revisionWizard->download_link = $downloadLink;
            $revisionWizard->view_link = $viewLink;

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

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

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

            $revisionWizard->delete();
            return response()->json([
                'response_message' => ['success' => ['Revision Wizard Deleted Successfully!']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
    
    // Display All Revision Wizards from Admin
     public function getAdminRevisionWizards()
     {
         try {

             $revisionWizards = AdminRevisionWizard::select('id', 'title', 'file', 'class_id', 'issue_date', 'subject_id')->with(['classRelation:id,class_name', 'subject:id,subject_name'])->latest()->get();

             if (!$revisionWizards->isEmpty()) {
                 // Map data to the required format
                 $formattedData = $revisionWizards->map(function ($item) {
                     $downloadLink = asset('uploads/admin_revision_wizards/' . $item->file);
                     $viewLink = 'https://docs.google.com/gview?url=' . urlencode($downloadLink) . '&embedded=true';
                     return [
                         'id' => $item->id,
                         'title' => $item->title,
                         'file' => $item->file,
                         'download_link' => $downloadLink,
                         'view_link' => $viewLink,
                         'class_id' => $item->class_id,
                         'issue_date' => $item->issue_date,
                         'class_name' => $item->classRelation->class_name ?? null,
                         'subject_id' => $item->subject_id,
                         'subject_name' => $item->subject->subject_name ?? null,
                     ];
                 });

                 // $data = array_merge($data, ['revision_wizards' => $formattedData]);
                 return response()->json([
                     'data' => ['admin_revision_wizards' => $formattedData],
                     'response_status' => 200,
                 ], 200);
             }
         } catch (Exception $exception) {
             // Handle any errors that occur
             return response()->json([
                 'validation_errors' => ['error' => [$exception->getMessage()]],
                 'response_status' => 400,
             ], 200);
         }
     }
}
