<?php

namespace App\Http\Controllers;

use App\Models\DailyUpdate;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\DailyUpdate as DailyUpdateCollection;

class DailyUpdateController extends Controller
{
    public function index(Request $request)
    {
        try {
            $limit = $request->query('limit', 10);
                $query = DailyUpdate::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, ['dailyupdate_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);
                        }
                    }
                }
                $dailyupdates = $query->orderBy('updated_at', 'desc')->paginate($limit);
                
                $dailyupdateCollection = DailyUpdateCollection::collection($dailyupdates->items());

                $responseData = [
                    'records' => $dailyupdateCollection,
                    'pagination' => [
                        'current_page' => $dailyupdates->currentPage(),
                        'last_page' => $dailyupdates->lastPage(),
                        'per_page' => $dailyupdates->perPage(),
                        'total' => $dailyupdates->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([
                'dailyupdate_name' => 'required|string|max:100',
            ]);

            DB::beginTransaction();
            $dailyupdate = DailyUpdate::create([
                'dailyupdate_name' => $request->dailyupdate_name,
                'dailyupdate_description' => $request->dailyupdate_description,
                'dailyupdate_slug' => $this->createUniqueSlug($request->dailyupdate_name),
                'dailyupdate_category_id' => $request->dailyupdate_category_id,
                'dailyupdate_image_id' => $request->dailyupdate_image_id,
                'status' => $request->status ?? true, // Default to true if status is not provided.
            ]);
 
            DB::commit();
            return response()->json(['message' => 'DailyUpdate created successfully', 'record' => new DailyUpdateCollection($dailyupdate)], 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{
            $dailyupdate = DailyUpdate::findOrFail($id);
            return response()->json(['message' => 'DailyUpdate Details Fetached successfully', 'record' => new DailyUpdateCollection($dailyupdate)], 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([
                'dailyupdate_name' => 'required|string|max:100',
            ]);

            DB::beginTransaction();
    
            $dailyupdate = DailyUpdate::findOrFail($id); 
            // Update user data
            $dailyupdate->dailyupdate_name = $request->dailyupdate_name;
            $dailyupdate->dailyupdate_description = $request->dailyupdate_description;
            $dailyupdate->dailyupdate_category_id = $request->dailyupdate_category_id;
            $dailyupdate->dailyupdate_slug = $request->dailyupdate_slug;
            $dailyupdate->dailyupdate_image_id = $request->dailyupdate_image_id ?? $dailyupdate->dailyupdate_image_id;
            $dailyupdate->status = $request->status ?? $dailyupdate->status;
            $dailyupdate->save();
            DB::commit();
    
            return response()->json(['message' => 'DailyUpdate updated successfully', 'record' => new DailyUpdateCollection($dailyupdate)], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'DailyUpdate 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 dailyupdate  with the specified IDs
                $dailyupdates = DailyUpdate::whereIn('id', $ids)->get();
                
                // Delete the fetched dailyupdate groups
                foreach ($dailyupdates as $dailyupdate) {
                    $dailyupdate->delete();
                }
            }
                return response()->json(['message' => 'DailyUpdate and associated entries deleted successfully'], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'DailyUpdate 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);
        }
    }




    function createUniqueSlug($title)
    {
        // Generate initial slug
        $slug = Str::slug($title);
        $originalSlug = $slug;
        $counter = 1;

        // Check if the slug already exists in the database
        while (DailyUpdate::where('dailyupdate_slug', $slug)->exists()) {
            // If it exists, append the counter and increment it
            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }

        return $slug;
    }
}
