<?php

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


use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Resources\Category as CategoryCollection;

class CategoryController extends Controller
{
    public function index(Request $request)
        {
            try {
                $limit = $request->query('limit', 10);
                $query = Category::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, ['category_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);
                        }
                    }
                }
                if ($request->has('category_name') || $request->has('status') || $request->has('product_id')) {
                    $categories = $query->orderBy('updated_at', 'desc')->paginate($limit);
                }else{
                    $categories = Category::where('is_child', 0)->paginate($limit);
                }
                
                $categoryCollection = CategoryCollection::collection($categories->items());

                $responseData = [
                    'records' => $categoryCollection,
                    'pagination' => [
                        'current_page' => $categories->currentPage(),
                        'last_page' => $categories->lastPage(),
                        'per_page' => $categories->perPage(),
                        'total' => $categories->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([
                    'category_name' => 'required',
                ]);
    
                DB::beginTransaction();
                $category = Category::create([
                    'category_name' => $request->category_name,
                    'product_id' => $request->product_id,
                    'parent_id' => $request->parent_id,
                    'is_child' => $request->parent_id == null ? 0 : 1,
                    'status' => $request->status ?? true,
                ]);
     
                DB::commit();
                return response()->json(['message' => 'Category created successfully', 'record' => new CategoryCollection($category)], 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{
                $category = Category::findOrFail($id);
                return response()->json(['message' => 'Category Details Fetached successfully', 'record' => new CategoryCollection($category)], 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([
                    'category_name' => 'required',
                    'product_id' => 'required',
                ]);
    
                DB::beginTransaction();
        
                $category = Category::findOrFail($id); 
                // Update user data

                $category->category_name = $request->category_name;
                $category->product_id = $request->product_id;
                $category->parent_id = $request->parent_id;
                $category->is_child = $request->parent_id == null ? 0 : 1;
                $category->status = $request->status;
                $category->save();
    
                DB::commit();
        
                return response()->json(['message' => 'Category updated successfully', 'record' => new CategoryCollection($category)], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Category 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
                    $categories = Category::whereIn('id', $ids)->get();
                    
                    // Delete the fetched product groups
                    foreach ($categories as $category) {
                        $category->children->delete();
                        $category->delete();
                    }
                }
                return response()->json(['message' => 'Category and associated entries deleted successfully'], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Category 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);
            }
        }

        /* Category Parent data*/

        public function parent(Request $request)
        {
            try {
                $categories = Category::where('is_child', 0)->get();
               // return response()->json(['records' => $categories]);

                if ($categories->isEmpty()) {
                  return response()->json(['records' => []]);
                }else{
                    return response()->json(['records' => CategoryCollection::collection($categories)]);
                }
            } 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);
            }
        }

        public function productCategory($id){
            try {
                $categories = Category::where('product_id',$id)->where('is_child', 0)->get();
                //return response()->json(['records' => $categories]);

                if ($categories->isEmpty()) {
                  return response()->json(['records' => []]);
                }else{
                    return response()->json(['records' => CategoryCollection::collection($categories)]);
                }
            } 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);
            }

        }
}
