<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminRevisionWizard;
use App\Models\Classes;
use Illuminate\Http\Request;
use App\Models\RevisionWizard;
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 {
            $revisionWizards = AdminRevisionWizard::select('id', 'title', 'file', 'class_id', 'issue_date','subject_id')->with(['classRelation:id,class_name','subject:id,subject_name'])->orderBy('id', 'desc')->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/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,
                ];
            });

            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)
    {
        try {
            // Validate the request inputs
            $validation = Validator::make($request->all(), [
                'class_id' => 'nullable|exists:classes,id',
                'subject_id' => 'nullable|exists:subjects,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);
            }

            // 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/admin_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);
            }

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

            // Store the new study guide in the database
            $revisionWizard = AdminRevisionWizard::create([
                'class_id' => $request->class_id ?? null,
                'subject_id' => $request->subject_id ?? null,
                'title' => $request->title,
                'file' => $filename,
                'issue_date' => $currentLocalDateTime,
            ]);

            // Generate the download and view links for the uploaded file
            $downloadLink = asset('uploads/admin_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' => [
                    'revision_wizard' => $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 {
            $revisionWizard = AdminRevisionWizard::select('id', 'title', 'file', 'class_id', 'issue_date')->with(['classRelation:id,class_name','subject:id,subject_name'])->find($id);
            if (!$revisionWizard) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['revision_wizard' => $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(), [
                'class_id' => 'nullable|exists:classes,id',
                'subject_id' => 'nullable|exists:subjects,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 = AdminRevisionWizard::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/admin_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 the revision wizard fields
            $revisionWizard->class_id = $request->class_id ?? null;
            $revisionWizard->subject_id = $request->subject_id ?? null;
            $revisionWizard->title = $request->title;
            $revisionWizard->file = $filename;
            $revisionWizard->save();

            // Generate the download and view links for the uploaded file
            $downloadLink = asset('uploads/admin_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' => [
                    'revision_wizard' => $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 = AdminRevisionWizard::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/admin_revision_wizards/' . $revisionWizard->file))) {
                File::delete(public_path('uploads/admin_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);
        }
    }
}
