<?php

namespace App\Http\Controllers;

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

use App\Models\PriceState;
use Illuminate\Http\Request;
use App\Http\Resources\PriceState as PriceStateCollection;

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

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

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

                $pricestates = $query->orderBy('id')->paginate($limit);
                $pricestateCollection = PriceStateCollection::collection($pricestates->items());

                $responseData = [
                    'records' => $pricestateCollection,
                    'pagination' => [
                        'current_page' => $pricestates->currentPage(),
                        'last_page' => $pricestates->lastPage(),
                        'per_page' => $pricestates->perPage(),
                        'total' => $pricestates->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([
                    'state_name' => 'required',
                ]);
    
                DB::beginTransaction();
                $pricestate = PriceState::create([
                    'state_name' => $request->state_name,
                    'price_country_id' => $request->price_country_id,
                    'status' => $request->status ?? true,
                ]);
     
                DB::commit();
                return response()->json(['message' => 'State created successfully', 'record' => new PriceStateCollection($pricestate)], 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{
                $pricestate = PriceState::findOrFail($id);
                return response()->json(['message' => 'State Details Fetached successfully', 'record' => new PriceStateCollection($pricestate)], 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([
                    'state_name' => 'required',
                ]);
    
                DB::beginTransaction();
        
                $pricestate = PriceState::findOrFail($id); 
                // Update user data

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