<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Classes;
use App\Models\Subject;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;
use Exception;

class ClassController extends Controller
{
    /**
     * Display All Classes without Trashed
     */
    public function indexClasses()
    {
        try {
            $classes = Classes::select('id', 'class_name', 'is_active', 'deleted_at')->latest()->get();
            if ($classes->isEmpty()) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['classes' => $classes];
            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 Active Classes without Trashed
     */
    public function index()
    {
        try {
            $classes = Classes::select('id', 'class_name', 'is_active', 'deleted_at')->where('is_active',1)->latest()->get();
            if ($classes->isEmpty()) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['classes' => $classes];
            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 Classes with Trashed.
     */
    public function withTrashed()
    {
        try {
            $classes = Classes::select('id', 'class_name', 'is_active', 'deleted_at')->withTrashed()->latest()->get();
            if ($classes->isEmpty()) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['Classes not found.']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['classes' => $classes];
            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 Classes.
     */
    public function trash()
    {
        try {
            $classes = Classes::select('id', 'class_name', 'is_active', 'deleted_at')->onlyTrashed()->latest()->get();
            if ($classes->isEmpty()) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['classes' => $classes];
            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 Classes.
     */
    public function restore(string $id)
    {
        try {
            $class = Classes::select('id', 'class_name', 'is_active', 'deleted_at')->onlyTrashed()->find($id);
            if (!$class) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $class->restore();
            $data = ['class' => $class];
            return response()->json([
                'data' => $data,
                'response_message' => ['success' => ['Year 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 {
            $validation = Validator::make($request->all(), [
                'class_name' => 'required|string|unique:classes',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ],[
                'class_name.unique' => 'The Year Name has already been taken',
            ]);

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

            // Create Image Process
            $filename = '';

            if ($request->hasFile('image')) {
                $file = $request->file('image');
                $extension = $file->getClientOriginalExtension();
                $filename = time() . '.' . $extension;
                $path = public_path('uploads/classes/');

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

            // Store the new class
            $class = Classes::create([
                'class_name' => $request->class_name,
                'image' => $filename, // Save the filename (nullable)
            ]);

            $data = ['class' => $class];
            return response([
                'response_status' => 200,
                'response_message' => ['success' => ['Year Created Successfully!']],
                'data' => $data
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        try {
            $class = Classes::select('id', 'class_name','is_active', 'deleted_at')->with(['subjects:id,subject_name'])->find($id);
            if (!$class) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['class' => $class];
            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 Class.
     */
    public function activeClass(Request $request, string $id)
    {
        try {

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

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

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

            $data = ['class' => $class];
            return response()->json([
                'data' => $data,
                'response_message' => ['success' => ['Year 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(), [
                'class_name' => 'required|string|unique:classes',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ],[
                'class_name.unique' => 'The Year Name has already been taken',
            ]);

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

            $class = Classes::find($id);
            if (!$class) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }

            $filename = '';

            // Create Image Process
            if ($request->hasFile('image')) {
                $file = $request->file('image');
                $extension = $file->getClientOriginalExtension();
                $filename = time() . '.' . $extension;
                $path = public_path('uploads/classes/');

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

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

                // Update the class image filename
                $class->image = $filename;
            }

            $class->class_name = $request->class_name;
            $class->save();

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

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

            $class->delete();
            $class = Classes::select('id', 'class_name', 'is_active', 'deleted_at')->onlyTrashed()->latest()->get();
            $data = ['class' => $class];
            return response()->json([
                'response_message' => ['success' => ['Year has been sent to Trash!']],
                'response_status' => 200,
                'data' => $data
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

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

            // Delete Image From Folder
            if ($class->image && File::exists(public_path('uploads/classes/' . $class->image))) {
                File::delete(public_path('uploads/classes/' . $class->image));
            }

            $class->forceDelete();

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