<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\User;
use App\Models\Grade;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\Post as PostCollection;

class PostController extends Controller
{
    public function index(Request $request)
        {
           // try {
                $limit = $request->query('limit', 50);

                $query = Post::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' && $key !== 'product_ids' && $key !== 'city_ids' && $key !== 'grade_ids' && $key !== 'date_range' && $key !== 'post_type') {
                            // Apply exact match for other fields
                            $query->where($key, $value);
                        }
                    }
                // Apply date range filter
                if ($request->has('date_range')) {
                    $dates = explode(' - ', $request->input('date_range'));
                    $startDate = \Carbon\Carbon::createFromFormat('d/m/Y', $dates[0])->startOfDay();
                    $endDate = \Carbon\Carbon::createFromFormat('d/m/Y', $dates[1])->endOfDay();
                    $query->whereBetween('created_at', [$startDate, $endDate]);
                }

                // Apply Product filter
                if ($request->has('product_ids')) {
                    $product = explode(",", $request->product_ids);
                    $query->whereIn('product_id', $product);
                }

                // Apply City filter
                if ($request->has('city_ids')) {
                    $city = explode(",", $request->city_ids);
                    $query->whereIn('city_id', $city);
                }

                 // Apply Grade filter
                 if ($request->has('grade_ids')) {
                    $grade = explode(",", $request->grade_ids);
                    $query->whereIn('grade_id', $grade);
                }

                // Apply Grade filter
                if ($request->has('user_id')) {
                    $query->where('user_id',$request->user_id);
                }

                if ($request->has('post_type') && $request->post_type == 'my_post') {
                    $query->where('user_id',$request->user()->id);
                }

                


                $posts = $query->orderBy('updated_at','desc')->paginate($limit);
                $postCollection = PostCollection::collection($posts->items());

                $responseData = [
                    'records' => $postCollection,
                    'pagination' => [
                        'current_page' => $posts->currentPage(),
                        'last_page' => $posts->lastPage(),
                        'per_page' => $posts->perPage(),
                        'total' => $posts->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{
            if ($request->filled('grade_id')) {
                // If grade_id is provided but doesn't exist, inform the user to create it
                $grade = Grade::findOrFail($request->grade_id);
        
                if (!$grade) {
                    return response()->json(['message' => 'Please create this grade'], 500);
                }
                // grade_id exists, proceed with additional logic if needed
                $grade_id = $request->grade_id;
            } else {
                // grade_id is not provided, so handle accordingly
                $grade_id = null;
            }
    
                DB::beginTransaction();
                $post = Post::create([
                    'product_id' => $request->product_id,
                    'category_id' => $request->category_id,
                    'city_id' => $request->city_id,
                    'grade_id' => $grade_id,
                    'user_id' => $request->user()->id,
                    'name' => $request->name,
                    'email' => $request->email,
                    'phone' => $request->phone,
                    'cover_letter' => $request->cover_letter,
                    'experience' => $request->experience,
                    'title' => $request->title,
                    'shape' => $request->shape,
                    'segment' => $request->segment,
                    'stock_type' => $request->stock_type,
                    'qty_unit' => $request->qty_unit,
                    'size_unit' => $request->size_unit,
                    'qty' => $request->qty,
                    'size' => $request->size,
                    'description' => $request->description,
                    'address' => $request->address,
                    'status' => $request->status,
                    'image_id' => $request->image_id,
                    //'other_image_id' => $request->other_image_id,
                   // 'cv_id' => $request->cv_id,
                ]);

                DB::commit();
                return response()->json(['message' => 'Post created successfully', 'record' => new PostCollection($post)], 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], 500);
            }
        }
    
        /**
         * Display the specified resource.
         */
        public function show($id)
        {
            try{
                $post = Post::findOrFail($id);
                return response()->json(['message' => 'Post Details Fetached successfully', 'record' => new PostCollection($post)], 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 {
                DB::beginTransaction();
        
                $post = Post::findOrFail($id); 
                $post->product_id = $request->product_id;
                $post->category_id = $request->category_id;
                $post->city_id = $request->city_id;
                $post->grade_id = $request->grade_id;
                //$post->user_id = $request->user_id;
                $post->name = $request->name;
                $post->email = $request->email;
                $post->phone = $request->phone;
                $post->cover_letter = $request->cover_letter;
                $post->experience = $request->experience;
                $post->title = $request->title;
                $post->shape = $request->shape;
                $post->segment = $request->segment;
                $post->stock_type = $request->stock_type;
                $post->qty_unit = $request->qty_unit;
                $post->size_unit = $request->size_unit;
                $post->qty = $request->qty;
                $post->size = $request->size;
                $post->description = $request->description;
                $post->address = $request->address;
                $post->status = $request->status;
                $post->image_id = $request->image_id;
                $post->other_image_id = $request->other_image_id;
                $post->cv_id = $request->cv_id;

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

        public function getAnonymous()
        {
            try {
                $filteredPosts = Post::whereIn('user_id', ['16907'])->get();
                foreach ($filteredPosts as $post) {
                    $post->delete(); // Triggers Eloquent model events
                }
                
                return response()->json(['Count' => Count($filteredPosts), 'data' => $filteredPosts, ], 200);
            } catch (ModelNotFoundException $e) {
                DB::rollBack();
                return response()->json(['message' => 'Post 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);
            }
        }



}
