<?php

namespace App\Http\Controllers;

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

use App\Models\PriceCity;
use Illuminate\Http\Request;
use App\Http\Resources\PriceCity as PriceCityCollection;

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

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

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

                $pricecitys = $query->orderBy('id')->paginate($limit);
                $pricecityCollection = PriceCityCollection::collection($pricecitys->items());

                $responseData = [
                    'records' => $pricecityCollection,
                    'pagination' => [
                        'current_page' => $pricecitys->currentPage(),
                        'last_page' => $pricecitys->lastPage(),
                        'per_page' => $pricecitys->perPage(),
                        'total' => $pricecitys->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([
                    'city_name' => 'required',
                ]);
    
                DB::beginTransaction();
                $pricecity = PriceCity::create([
                    'city_name' => $request->city_name,
                    'price_country_id' => $request->price_country_id,
                    'price_state_id' => $request->price_state_id,
                    'status' => $request->status ?? true,
                ]);
     
                DB::commit();
                return response()->json(['message' => 'City created successfully', 'record' => new PriceCityCollection($pricecity)], 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{
                $pricecity = PriceCity::findOrFail($id);
                return response()->json(['message' => 'City Details Fetached successfully', 'record' => new PriceCityCollection($pricecity)], 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([
                    'city_name' => 'required',
                ]);
    
                DB::beginTransaction();
        
                $pricecity = PriceCity::findOrFail($id); 
                // Update user data

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