<?php

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

use App\Models\Specification;
use App\Models\SpecificationData;
use Illuminate\Http\Request;
use App\Http\Resources\Specification as SpecificationCollection;

class SpecificationController extends Controller
{
    public function index(Request $request)
        {
            try {
                $limit = $request->query('limit', 10);
                $specification = Specification::paginate($limit);
                $specificationCollection = SpecificationCollection::collection($specification->items());
                $responseData = [
                    'records' => $specificationCollection,
                    'pagination' => [
                        'current_page' => $specification->currentPage(),
                        'last_page' => $specification->lastPage(),
                        'per_page' => $specification->perPage(),
                        'total' => $specification->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_id' => 'required',
                ]);
    
                DB::beginTransaction();
                $specification = Specification::create([
                    'grade_id' => $request->grade_id,
                    'status' => $request->status ?? true, // Default to true if status is not provided.
                ]);

                foreach ($request->attribute_value as $attribute) {
                    SpecificationData::create([
                        'specification_id' => $specification->id,
                        'attribute_id' => $attribute['attribute_id'],
                        'value' => $attribute['value'],
                    ]);
                }
    
                DB::commit();

                return response()->json(['message' => 'Specification created successfully', 'record' => new SpecificationCollection($specification)], 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{
                $specification = Specification::findOrFail($id);
                return response()->json(['message' => 'Specification Details Fetached successfully', 'record' => new SpecificationCollection($specification)], 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_id' => 'required',
                ]);
    
                DB::beginTransaction();
        
                $specification = Specification::findOrFail($id); 
                // Update user data
                $specification->grade_id = $request->grade_id;
                $specification->status = $request->status;
                $specification->save();
                $specification->specification_data()->delete();
                
                foreach ($request->attribute_value as $attribute) {
                    SpecificationData::create([
                        'specification_id' => $specification->id,
                        'attribute_id' => $attribute['attribute_id'],
                        'value' => $attribute['value'],
                    ]);
                }
    
                DB::commit();
                return response()->json(['message' => 'Specification updated successfully', 'record' => new SpecificationCollection($specification)], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Specification 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
                    $Specifications = Specification::whereIn('id', $ids)->get();
                    
                    // Delete the fetched product groups
                    foreach ($Specifications as $Specification) {
                        $Specification->delete();
                    }
                }
                return response()->json(['message' => 'Specification and associated entries deleted successfully'], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Specification 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 Data Specification Data


        
}
