<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FanCardPlan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FanCardPlanController extends Controller
{
    /**
     * Display a listing of fan card plans
     */
    public function index()
    {
        $plans = FanCardPlan::orderBy('sort_order', 'asc')
                            ->orderBy('price', 'asc')
                            ->paginate(20);

        $settings = \DB::table('settings')->where('id', 1)->first();
        $title = 'VIP Fan Card Plans';

        return view('admin.fan_card_plans.index', compact('plans', 'settings', 'title'));
    }

    /**
     * Show the form for creating a new plan
     */
    public function create()
    {
        $settings = \DB::table('settings')->where('id', 1)->first();
        $title = 'Create Fan Card Plan';

        return view('admin.fan_card_plans.create', compact('settings', 'title'));
    }

    /**
     * Store a newly created plan
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255|unique:fan_card_plans,name',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'discount_percentage' => 'nullable|integer|min:0|max:100',
            'sort_order' => 'nullable|integer|min:0',
            'badge_color' => 'nullable|string|max:50',
            'icon' => 'nullable|string|max:50',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                           ->withErrors($validator)
                           ->withInput();
        }

        // Handle benefits as array
        $benefits = [];
        if ($request->has('benefits')) {
            $benefitsInput = $request->input('benefits');
            if (is_array($benefitsInput)) {
                $benefits = array_filter($benefitsInput); // Remove empty values
            }
        }

        // If featured, unset other featured plans
        if ($request->is_featured) {
            FanCardPlan::where('is_featured', true)->update(['is_featured' => false]);
        }

        FanCardPlan::create([
            'name' => $request->name,
            'price' => $request->price,
            'description' => $request->description,
            'benefits' => $benefits,
            'discount_percentage' => $request->discount_percentage ?? 0,
            'is_active' => $request->has('is_active'),
            'is_featured' => $request->has('is_featured'),
            'sort_order' => $request->sort_order ?? 0,
            'badge_color' => $request->badge_color,
            'icon' => $request->icon ?? 'star',
        ]);

        return redirect()->route('admin.fan-card-plans.index')
                       ->with('success', 'Fan card plan created successfully!');
    }

    /**
     * Show the form for editing the specified plan
     */
    public function edit($id)
    {
        $plan = FanCardPlan::findOrFail($id);
        $settings = \DB::table('settings')->where('id', 1)->first();
        $title = 'Edit Fan Card Plan';

        return view('admin.fan_card_plans.edit', compact('plan', 'settings', 'title'));
    }

    /**
     * Update the specified plan
     */
    public function update(Request $request, $id)
    {
        $plan = FanCardPlan::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255|unique:fan_card_plans,name,' . $id,
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'discount_percentage' => 'nullable|integer|min:0|max:100',
            'sort_order' => 'nullable|integer|min:0',
            'badge_color' => 'nullable|string|max:50',
            'icon' => 'nullable|string|max:50',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                           ->withErrors($validator)
                           ->withInput();
        }

        // Handle benefits as array
        $benefits = [];
        if ($request->has('benefits')) {
            $benefitsInput = $request->input('benefits');
            if (is_array($benefitsInput)) {
                $benefits = array_filter($benefitsInput);
            }
        }

        // If featured, unset other featured plans
        if ($request->has('is_featured') && !$plan->is_featured) {
            FanCardPlan::where('is_featured', true)->update(['is_featured' => false]);
        }

        $plan->update([
            'name' => $request->name,
            'price' => $request->price,
            'description' => $request->description,
            'benefits' => $benefits,
            'discount_percentage' => $request->discount_percentage ?? 0,
            'is_active' => $request->has('is_active'),
            'is_featured' => $request->has('is_featured'),
            'sort_order' => $request->sort_order ?? 0,
            'badge_color' => $request->badge_color,
            'icon' => $request->icon ?? 'star',
        ]);

        return redirect()->route('admin.fan-card-plans.index')
                       ->with('success', 'Fan card plan updated successfully!');
    }

    /**
     * Remove the specified plan
     */
    public function destroy($id)
    {
        $plan = FanCardPlan::findOrFail($id);
        
        // Check if plan has bookings
        $bookingsCount = \DB::table('celebrity_bookings')
                           ->where('booking_type', 'fan_card')
                           ->whereRaw("JSON_EXTRACT(notes, '$.membership_tier') = ?", [$plan->slug])
                           ->count();

        if ($bookingsCount > 0) {
            return redirect()->back()
                           ->with('error', 'Cannot delete this plan as it has ' . $bookingsCount . ' active bookings.');
        }

        $plan->delete();

        return redirect()->route('admin.fan-card-plans.index')
                       ->with('success', 'Fan card plan deleted successfully!');
    }

    /**
     * Toggle plan active status
     */
    public function toggleStatus($id)
    {
        $plan = FanCardPlan::findOrFail($id);
        $plan->is_active = !$plan->is_active;
        $plan->save();

        $status = $plan->is_active ? 'activated' : 'deactivated';
        
        return redirect()->back()
                       ->with('success', 'Plan ' . $status . ' successfully!');
    }
}
