<?php

namespace App\Http\Controllers;

use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\Subscription as SubscriptionCollection;
use Razorpay\Api\Api;

class SubscriptionController extends Controller
{
    public function index(Request $request)
    {
        try {
            $limit = $request->query('limit', 10);
                $query = Subscription::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, ['subscription_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);
                        }
                    }
                }
                $subscriptions = $query->orderBy('updated_at', 'desc')->paginate($limit);
                
                $subscriptionCollection = SubscriptionCollection::collection($subscriptions->items());

                $responseData = [
                    'records' => $subscriptionCollection,
                    'pagination' => [
                        'current_page' => $subscriptions->currentPage(),
                        'last_page' => $subscriptions->lastPage(),
                        'per_page' => $subscriptions->perPage(),
                        'total' => $subscriptions->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)
    {
        $validatedData = $request->validate([
            'subscription_name' => 'required|string|max:100',
        ]);

        DB::beginTransaction();
        try {
            
            $api = new Api(config('services.razorpay.key'), config('services.razorpay.secret'));
            $plan = $api->plan->create([
                'period' => 'monthly',
                'interval' => $request->subscription_duration,
                'item' => [
                    'name' => $request->subscription_name,
                    'amount' => $request->subscription_rate * 100, // Amount in paise
                    'currency' => 'INR',
                    'description' => $request->subscription_description,
                ],
            ]);

            if (!$plan || !isset($plan->id)) {
                Log::info('Razorpay Plan Creation Response:', (array) $plan);
                throw new \Exception("Plan creation failed. No plan ID returned.");
            }

            $subscription = Subscription::create([
                'subscription_name' => $request->subscription_name,
                'subscription_description' => $request->subscription_description,
                'subscription_plan_id' => $plan->id,
                'subscription_duration' => $request->subscription_duration,
                'subscription_rate' => $request->subscription_rate,
                'subscription_image_id' => $request->subscription_image_id,
                'status' => $request->status ?? true, // Default to true if status is not provided.
            ]);

            DB::commit();
            return response()->json(['message' => 'Subscription created successfully', 'record' => new SubscriptionCollection($subscription)], 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{
            $subscription = Subscription::findOrFail($id);
            return response()->json(['message' => 'Subscription Details Fetached successfully', 'record' => new SubscriptionCollection($subscription)], 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([
                'subscription_name' => 'required|string|max:100',
            ]);

            DB::beginTransaction();
    
            $subscription = Subscription::findOrFail($id); 
            // Update user data
            $subscription->subscription_name = $request->subscription_name;
            $subscription->subscription_description = $request->subscription_description;
            $subscription->subscription_duration = $request->subscription_duration;
            $subscription->subscription_rate = $request->subscription_rate;
            $subscription->subscription_image_id = $request->subscription_image_id ?? $subscription->subscription_image_id;
            $subscription->status = $request->status ?? $subscription->status;
            $subscription->save();
            DB::commit();
    
            return response()->json(['message' => 'Subscription updated successfully', 'record' => new SubscriptionCollection($subscription)], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Subscription 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 subscription  with the specified IDs
                $subscriptions = Subscription::whereIn('id', $ids)->get();
                
                // Delete the fetched subscription groups
                foreach ($subscriptions as $subscription) {
                    $subscription->delete();
                }
            }
                return response()->json(['message' => 'Subscription and associated entries deleted successfully'], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Subscription 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);
        }
    }
}
