<?php

namespace App\Http\Controllers;

use App\Models\Advertisement;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\Advertisement as AdvertisementCollection;
use Carbon\Carbon;

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

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

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

                $advertisements = $query->orderBy('updated_at', 'desc')->paginate($limit);
                $advertisementCollection = AdvertisementCollection::collection($advertisements->items());

                $responseData = [
                    'records' => $advertisementCollection,
                    'pagination' => [
                        'current_page' => $advertisements->currentPage(),
                        'last_page' => $advertisements->lastPage(),
                        'per_page' => $advertisements->perPage(),
                        'total' => $advertisements->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([
                    'advertisement_name' => 'required|string|max:100',
                ]);
    
                DB::beginTransaction();
                $advertisement = Advertisement::create([
                    'advertisement_name' => $request->advertisement_name,
                    'advertisement_block' => $request->advertisement_block,
                    'advertisement_description' => $request->advertisement_description,
                    'start_at' => $this->formatDate($request->start_at),
                    'expires_at' => $this->formatDate($request->expires_at),
                    'advertisement_url' => $request->advertisement_url,
                    'advertisement_image_id' => $request->advertisement_image_id,
                    'advertisement_slider_image_id' => $request->advertisement_slider_image_id,
                    'status' => $request->status ?? true
                ]);
     
                DB::commit();
                return response()->json(['message' => 'Advertisement created successfully', 'record' => new AdvertisementCollection($advertisement)], 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{
                $advertisement = Advertisement::findOrFail($id);
                return response()->json(['message' => 'Advertisement Details Fetached successfully', 'record' => new AdvertisementCollection($advertisement)], 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([
                    'advertisement_name' => 'required|string|max:100',
                ]);
    
                DB::beginTransaction();


        
                $advertisement = Advertisement::findOrFail($id); 

                $advertisement->advertisement_name = $request->advertisement_name;
                $advertisement->advertisement_block = $request->advertisement_block;
                $advertisement->advertisement_description = $request->advertisement_description;
                $advertisement->start_at = $this->formatDate($request->start_at) ;
                $advertisement->expires_at = $this->formatDate($request->expires_at);
                $advertisement->advertisement_url = $request->advertisement_url;
                $advertisement->advertisement_image_id = $request->advertisement_image_id ?? $advertisement->advertisement_image_id;
                $advertisement->advertisement_slider_image_id =$request->advertisement_slider_image_id ?? $advertisement->advertisement_slider_image_id;
                $advertisement->status = $request->status ?? $advertisement->status;

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

        // Others

        private function formatDate($data){
            $Date = Carbon::createFromFormat('d/m/Y', $data);
            $DateTime = $Date->setTime(00, 00, 0);
            $finalDate = $DateTime->format('Y-m-d H:i:s');
            return $finalDate;
        }
    
}
