<?php

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

use Illuminate\Http\Request;
use App\Models\ProductGroup;
use App\Http\Resources\ProductGroup as ProductGroupCollection;

class ProductGroupController extends Controller
{
    public function index(Request $request)
    {
        try {
            $limit = $request->query('limit', 10);
            $productgroup = ProductGroup::paginate($limit);
            $productgroupCollection = ProductGroupCollection::collection($productgroup->items());
            $responseData = [
                'records' => $productgroupCollection,
                'pagination' => [
                    'current_page' => $productgroup->currentPage(),
                    'last_page' => $productgroup->lastPage(),
                    'per_page' => $productgroup->perPage(),
                    'total' => $productgroup->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([
                'group_name' => 'required',
            ]);

            DB::beginTransaction();
            $productgroup = ProductGroup::create([
                'group_name' => $request->group_name,
                'status' => $request->status ?? true,
            ]);
 
            DB::commit();
            return response()->json(['message' => 'Group created successfully', 'record' => new ProductGroupCollection($productgroup)], 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{
            $productgroup = ProductGroup::findOrFail($id);
            return response()->json(['message' => 'Group Details Fetached successfully', 'record' => new ProductGroupCollection($productgroup)], 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([
                'group_name' => 'required',
            ]);

            DB::beginTransaction();
    
            $productgroup = ProductGroup::findOrFail($id); 
            // Update user data

            $productgroup->group_name = $request->group_name;
            $productgroup->status = $request->status;
            $productgroup->save();

            DB::commit();
    
            return response()->json(['message' => 'Group updated successfully', 'record' => new ProductGroupCollection($productgroup)], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Group 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 groups with the specified IDs
                $productGroups = ProductGroup::whereIn('id', $ids)->get();
                
                // Delete the fetched product groups
                foreach ($productGroups as $productGroup) {
                    $productGroup->delete();
                }
            }
            return response()->json(['message' => 'Group and associated entries deleted successfully'], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Group 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);
        }
    }
}
