<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\PricingPlan;

class PricingPlanController extends Controller
{

    public function index()
    {
        $pricingPlans = PricingPlan::orderBy('id', 'desc')->get();
        return sendSuccessResponse($pricingPlans->map(function ($pricingPlan) {
            return [
                'id' => $pricingPlan->id,
                'name' => $pricingPlan->name,
                'description' => $pricingPlan->description,
                'speed' => $pricingPlan->speed,
                'price' => $pricingPlan->price,
                'type' => $pricingPlan->type,
                'features' => json_decode($pricingPlan->features),
                'buy_link' => $pricingPlan->buy_link,
            ];
        }));
    }



    public function pricingPlans()
    {
        $pricingPlans = PricingPlan::orderBy('id', 'desc')->paginate(10);
        return view('Backend.PricingPlan.pricing-plans-list', ['pricingPlans' => $pricingPlans]);
    }

    public function create()
    {
        return view('Backend.PricingPlan.pricing-plans');
    }

    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|min:3|max:50',
                'description' => 'required|string|min:10|max:500',
                'speed' => 'required|numeric',
                'price' => 'required|numeric|min:0|max:999999',
                'type' => 'required|in:regular,sme',
                'feature1' => 'required|string|min:3|max:100',
                'feature2' => 'required|string|min:3|max:100',
                'feature3' => 'required|string|min:3|max:100',
                'feature4' => 'nullable|string|min:3|max:100',
                'feature5' => 'nullable|string|min:3|max:100',
                'feature6' => 'nullable|string|min:3|max:100',
                'buy_link' => 'required|url',
            ]);

            // Extract and filter features
            $features = collect(range(1, 6))
                ->map(fn($i) => $validated["feature$i"] ?? null)
                ->filter()
                ->values()
                ->toArray();

            // Remove individual feature fields and add features array
            $planData = collect($validated)
                ->except(['feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6'])
                ->put('features', json_encode($features))
                ->toArray();

            $pricingPlan = PricingPlan::create($planData);

            toastr()->success('Pricing plan created successfully');
            return redirect()->route('admin.pricing-plans');
        } catch (\Illuminate\Validation\ValidationException $e) {
            toastr()->error('Validation failed');
            return redirect()->back()->withErrors($e->errors())->withInput();
        } catch (\Exception $e) {
            toastr()->error('An error occurred while creating the pricing plan');
            return redirect()->back()->withInput();
        }
    }

    public function edit($id)
    {
        $pricingPlan = PricingPlan::find($id);
        return view('Backend.PricingPlan.pricing-plans', ['pricingPlan' => $pricingPlan]);
    }

    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'name' => 'required|string|min:3|max:50',
            'description' => 'required|string|min:10|max:500',
            'speed' => 'required|numeric',
            'price' => 'required|numeric|min:0|max:999999',
            'type' => 'required|in:regular,sme',
            'feature1' => 'required|string|min:3|max:100',
            'feature2' => 'required|string|min:3|max:100',
            'feature3' => 'required|string|min:3|max:100',
            'feature4' => 'nullable|string|min:3|max:100',
            'feature5' => 'nullable|string|min:3|max:100',
            'feature6' => 'nullable|string|min:3|max:100',
            'buy_link' => 'required|url',
        ]);

        try {
            $pricingPlan = PricingPlan::find($id);
            // Extract and filter features
            $features = collect(range(1, 6))
                ->map(fn($i) => $validated["feature$i"] ?? null)
                ->filter()
                ->values()
                ->toArray();

            // Remove individual feature fields and add features array
            $planData = collect($validated)
                ->except(['feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6'])
                ->put('features', json_encode($features))
                ->toArray();

            $pricingPlan->update($planData);
            toastr()->success('Pricing plan updated successfully');
            return redirect()->route('admin.pricing-plans');
        } catch (\Exception $e) {
            toastr()->error('An error occurred while updating the pricing plan');
            return redirect()->back()->withInput();
        }
    }

    public function destroy($id)
    {
        $pricingPlan = PricingPlan::find($id);
        $pricingPlan->delete();
        toastr()->success('Pricing plan deleted successfully');
        return redirect()->route('admin.pricing-plans');
    }
}
