<?php

namespace App\Http\Controllers;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

use App\Models\Grade;
use Illuminate\Http\Request;
use App\Models\SpecificationData;
use App\Http\Resources\Grade as GradeCollection;

class GradeController extends Controller
{
    public function index(Request $request)
        {
            try {



                $limit = $request->query('limit', 10);

                $query = Grade::query();
                // Get all parameters from the request
                $parameters = $request->all();

            // Loop through each parameter and apply filters to the query
                foreach ($parameters as $key => $value) {
                    // Make sure the key is not a reserved Laravel parameter
                    if ($key !== 'page' && $key !== 'limit') {
                        if (in_array($key, ['grade_name'])) {
                            // Apply search functionality using 'like' for name, email, and phone
                            $query->where($key, 'like', "%$value%");
                        } else {
                            // Apply exact match for other fields
                            $query->where($key, $value);
                        }
                    }
                }

                $grades = $query->orderBy('updated_at', 'desc')->paginate($limit);
                $gradeCollection = GradeCollection::collection($grades->items());

                $responseData = [
                    'records' => $gradeCollection,
                    'pagination' => [
                        'current_page' => $grades->currentPage(),
                        'last_page' => $grades->lastPage(),
                        'per_page' => $grades->perPage(),
                        'total' => $grades->total(),
                    ],
                ];
    
                return response()->json($responseData);
            } catch (QueryException $e) {
                return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
            } catch (\Exception $e) {
                return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
            }
        }
    
    
        /**
         * Store a newly created resource in storage.
         */
        public function store(Request $request)
        {
            try {
                $validatedData = $request->validate([
                    'grade_name' => 'required',
                ]);
    
                DB::beginTransaction();
                $grade = Grade::create([
                    'grade_name' => $request->grade_name,
                    'status' => $request->status ?? true, // Default to true if status is not provided.
                ]);

                foreach ($request->attribute_value as $attribute) {
                    SpecificationData::create([
                        'grade_id' => $grade->id,
                        'attribute_id' => $attribute['attribute_id'],
                        'value' => $attribute['value'],
                    ]);
                }
     
                DB::commit();
                return response()->json(['message' => 'Grade created successfully', 'record' => new GradeCollection($grade)], 201);
            } catch (QueryException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
            }
        }
    
        /**
         * Display the specified resource.
         */
        public function show($id)
        {
            try{
                $grade = Grade::findOrFail($id);
                return response()->json(['message' => 'Grade Details Fetached successfully', 'record' => new GradeCollection($grade)], 200);
            }catch (\Exception $e) {
                return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
            }
            
        }
    
    
        /**
         * Update the specified resource in storage.
         */
        public function update(Request $request, $id)
        {
            try {
                $validatedData = $request->validate([
                    'grade_name' => 'required',
                ]);
    
                DB::beginTransaction();
        
                $grade = Grade::findOrFail($id); 
                // Update user data

                $grade->grade_name = $request->grade_name;
                $grade->status = $request->status;
                $grade->save();

                $grade->specification_data()->delete();
                
                foreach ($request->attribute_value as $attribute) {
                    SpecificationData::create([
                        'grade_id' => $grade->id,
                        'attribute_id' => $attribute['attribute_id'],
                        'value' => $attribute['value'],
                    ]);
                }
    
                DB::commit();
        
                return response()->json(['message' => 'Grade updated successfully', 'record' => new GradeCollection($grade)], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Grade not found'], 404);
            } catch (QueryException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
            }
        }
    
        /**
         * Remove the specified resource from storage.
         */
        public function destroy($id)
        {
            try {
                $ids = explode(",",$id);
                if (!empty($ids)) {
                    // Fetch the product  with the specified IDs
                    $grades = Grade::whereIn('id', $ids)->get();
                    
                    // Delete the fetched product groups
                    foreach ($grades as $grade) {
                        $grade->delete();
                    }
                }
                return response()->json(['message' => 'Grade and associated entries deleted successfully'], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Grade not found'], 404);
            } catch (QueryException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
            }
        }


        // Other Resources

        public function activeGrade()
        {
            try {
                $grade = Grade::where('status',true)->get();
    
                return response()->json(['records' => GradeCollection::collection($grade)]);
            } catch (QueryException $e) {
                return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
            } catch (\Exception $e) {
                return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
            }
        }
}
