<?php

namespace App\Http\Controllers;

use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

use App\Models\PriceProduct;
use Illuminate\Http\Request;
use App\Http\Resources\PriceProduct as PriceProductCollection;

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

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

                $query = PriceProduct::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, ['product_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);
                        }
                    }
                }

                $priceproducts = $query->orderBy('id')->paginate($limit);
                $priceproductCollection = PriceProductCollection::collection($priceproducts->items());

                $responseData = [
                    'records' => $priceproductCollection,
                    'pagination' => [
                        'current_page' => $priceproducts->currentPage(),
                        'last_page' => $priceproducts->lastPage(),
                        'per_page' => $priceproducts->perPage(),
                        'total' => $priceproducts->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([
                    'product_name' => 'required',
                ]);
    
                DB::beginTransaction();
                $priceproduct = PriceProduct::create([
                    'product_name' => $request->product_name,
                    'status' => $request->status ?? true,
                ]);
     
                DB::commit();
                return response()->json(['message' => 'Product created successfully', 'record' => new PriceProductCollection($priceproduct)], 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{
                $priceproduct = PriceProduct::findOrFail($id);
                return response()->json(['message' => 'Product Details Fetached successfully', 'record' => new PriceProductCollection($priceproduct)], 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([
                    'product_name' => 'required',
                ]);
    
                DB::beginTransaction();
        
                $priceproduct = PriceProduct::findOrFail($id); 
                // Update user data

                $priceproduct->product_name = $request->product_name;
                $priceproduct->status = $request->status;
                $priceproduct->save();
    
                DB::commit();
        
                return response()->json(['message' => 'Product updated successfully', 'record' => new PriceProductCollection($priceproduct)], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'PriceProduct 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 priceproduct  with the specified IDs
                    $priceproducts = PriceProduct::whereIn('id', $ids)->get();
                    
                    // Delete the fetched priceproduct groups
                    foreach ($priceproducts as $priceproduct) {
                        $priceproduct->delete();
                    }
                }
                return response()->json(['message' => 'Product and associated entries deleted successfully'], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Product 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 activePriceProduct()
        {
            try {
                $priceproduct = PriceProduct::where('status',true)->orderBy('id')->get();
    
                return response()->json(['records' => PriceProductCollection::collection($priceproduct)]);
            } 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);
            }
        }
    }