<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\UserPlan;

class PlansController extends Controller
{
    public function index(Request $request)
    {
        // Fetch active plans from database
        $plansQuery = DB::table('user_plans')
            ->where('status', 'Active')
            ->orderBy('price', 'asc')
            ->get();

        // Transform database records to app format
        $plans = $plansQuery->map(function ($plan) {
            
            // 1. Calculate Prices properly
            // stored price is Base Price
            $originalPrice = (float) $plan->price;
            $finalPrice = $originalPrice;

            if ($plan->discount_percentage > 0) {
                // Percentage Discount
                $finalPrice = $originalPrice * (1 - ($plan->discount_percentage / 100));
            } elseif ($plan->discount_fixed_amount > 0) {
                // Fixed Amount Discount
                $finalPrice = max(0, $originalPrice - $plan->discount_fixed_amount);
            }
            
            // 2. Build Features List
            $features = [];
            
            if ($plan->post_limit > 0) {
                $features[] = "Post up to {$plan->post_limit} ads";
            }
            if ($plan->lead_limit > 0) {
                $features[] = "View {$plan->lead_limit} ads with direct contact";
                $features[] = "WhatsApp direct messaging";
            }
            if ($plan->has_analytics) {
                $features[] = $plan->analytics_tier === 'advanced' 
                    ? "Advanced analytics dashboard" 
                    : "Basic ad analytics (views & likes)";
            }
            if ($plan->verified_badge) {
                $features[] = lcfirst($plan->plan_name) . " badge";
                $features[] = "Verified tick mark ✓";
            }
            if ($plan->theme && $plan->theme !== 'standard') {
                $features[] = "Special VIP app theme";
            }
            if ($plan->ad_free) {
                $features[] = "Ad-free experience (no ads)";
            }
            $features[] = "{$plan->validity_days} days validity";

            // Add priority support/features based on plan name (legacy/special logic)
            if ($plan->plan_name === 'VIP Seller') {
                $features[] = "Priority listing placement";
                $features[] = "Featured ad options";
            }
            if ($plan->plan_name === 'VIP Pro') {
                $features[] = "✨ All VIP Buyer features";
                $features[] = "✨ All VIP Seller features";
                $features[] = "Priority support 24/7";
            }
            if ($plan->plan_name === 'VIP Buyer') {
                $features[] = "Priority notifications";
                $features[] = "Save unlimited favorites";
            }
            if ($plan->plan_name === 'Standard') {
                $features[] = "Email notifications";
                $features[] = "Standard support";
            }

            // 3. Determine Badge
            $badge = null;
            if ($plan->plan_name === 'VIP Pro') {
                $badge = 'BEST VALUE';
            } elseif ($plan->plan_name === 'VIP Seller') {
                $badge = 'POPULAR';
            }

            // 4. Determine Theme Color
            $color = match($plan->theme) {
                'blue' => 'blue',
                'orange' => 'orange',
                'purple' => 'purple',
                default => 'green' // Default changed to green for Standard usually
            };

            // 5. Construct Response Object
            return [
                'id' => $plan->id,
                'name' => $plan->plan_name,
                'slug' => strtolower(str_replace(' ', '-', $plan->plan_name)),
                
                // CRITICAL FIX: 'price' is the FINAL price the user pays
                'price' => round((float) $finalPrice, 2),
                
                // 'original_price' is shown crossed out if discount exists
                'original_price' => round((float) $originalPrice, 2),
                
                'duration_days' => $plan->duration_days,
                'features' => $features,
                'post_limit' => $plan->post_limit,
                'featured_limit' => 0,
                'ad_free' => (bool) $plan->ad_free,
                'has_analytics' => (bool) $plan->has_analytics,
                'analytics_type' => $plan->analytics_tier,
                'verified_badge' => (bool) $plan->verified_badge,
                'badge_type' => $plan->badge_style,
                'special_theme' => $plan->theme !== 'standard',
                'theme_color' => $color,
                'direct_contact_limit' => $plan->lead_limit,
                'whatsapp_access' => $plan->lead_limit > 0,
                'color' => $color,
                'gradient' => $plan->halo_effect ? true : false,
                'badge' => $badge,
                
                // Discount text for UI
                'discount' => $plan->discount_percentage > 0 
                    ? (int)$plan->discount_percentage . "% OFF" // Clean integer percent
                    : ($plan->discount_fixed_amount > 0 ? "₹{$plan->discount_fixed_amount} OFF" : null),
                
                'is_default' => (bool) $plan->is_default,
            ];
        })->toArray();

        // Get user's current plan
        $currentPlanId = $request->user()?->current_plan_id;
        
        // Debug logging
        \Log::info('Plans API called', [
            'user_id' => $request->user()?->id,
            'current_plan_id' => $currentPlanId,
            'plans_count' => count($plans)
        ]);
        
        // Get currency symbol
        $currencySetting = DB::table('settings')->where('key', 'currency_symbol')->first();
        $currencySymbol = $currencySetting ? $currencySetting->value : '₹';

        return response()->json([
            'plans' => array_values($plans),
            'current_plan_id' => $currentPlanId,
            'currency_symbol' => $currencySymbol,
        ]);
    }

    /**
     * Activate a plan (for free plans or after successful payment)
     */
    public function activate(Request $request, $planId)
    {
        try {
            $user = $request->user();
            $plan = DB::table('user_plans')->find($planId);

            if (!$plan) {
                return response()->json([
                    'success' => false,
                    'message' => 'Plan not found'
                ], 404);
            }

            if ($plan->status !== 'Active') {
                return response()->json([
                    'success' => false,
                    'message' => 'Plan is not active'
                ], 400);
            }

            // Calculate final price after discount
            $finalPrice = $plan->price;
            if ($plan->discount_percentage > 0) {
                $finalPrice = $plan->price * (1 - $plan->discount_percentage / 100);
            }

            // Check if it's a free plan (price is 0 or 100% discount)
            if ($finalPrice > 0) {
                return response()->json([
                    'success' => false,
                    'message' => 'This is a paid plan. Please complete payment first.',
                    'requires_payment' => true,
                    'amount' => $finalPrice
                ], 400);
            }

            // Activate the plan
            DB::table('users')->where('id', $user->id)->update([
                'current_plan_id' => $planId,
                'plan_expires_at' => now()->addDays($plan->validity_days),
                'membership_type' => $plan->plan_name,
                'updated_at' => now()
            ]);

            // Create subscription record
            $subscriptionId = 'SUB_' . strtoupper(uniqid());
            DB::table('subscriptions')->insert([
                'subscription_id' => $subscriptionId,
                'user_id' => $user->id,
                'plan_id' => $planId,
                'gateway_slug' => 'free',
                'status' => 'active',
                'payment_status' => 'completed',
                'start_date' => now(),
                'end_date' => now()->addDays($plan->validity_days),
                'amount' => 0,
                'currency' => 'INR',
                'billing_interval' => 'month',
                'billing_frequency' => 1,
                'auto_renew' => false,
                'created_at' => now(),
                'updated_at' => now()
            ]);

            \Log::info('Plan activated', [
                'user_id' => $user->id,
                'plan_id' => $planId,
                'plan_name' => $plan->plan_name,
                'subscription_id' => $subscriptionId
            ]);

            // Refresh user data
            $updatedUser = DB::table('users')->find($user->id);

            return response()->json([
                'success' => true,
                'message' => "Successfully activated {$plan->plan_name} plan!",
                'plan' => [
                    'id' => $plan->id,
                    'name' => $plan->plan_name,
                    'expires_at' => $updatedUser->plan_expires_at,
                    'features' => $this->getPlanFeatures($plan)
                ],
                'subscription_id' => $subscriptionId
            ]);

        } catch (\Exception $e) {
            \Log::error('Plan activation failed', [
                'error' => $e->getMessage(),
                'user_id' => $request->user()->id ?? null,
                'plan_id' => $planId
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to activate plan. Please try again.'
            ], 500);
        }
    }

    /**
     * Get plan features for UI display
     */
    private function getPlanFeatures($plan)
    {
        $features = [];

        if ($plan->post_limit > 0) {
            $features[] = "Post up to {$plan->post_limit} ads";
        }
        if ($plan->lead_limit > 0) {
            $features[] = "View {$plan->lead_limit} ads with direct contact";
            $features[] = "WhatsApp direct messaging";
        }
        if ($plan->has_analytics) {
            $features[] = $plan->analytics_tier === 'advanced' 
                ? "Advanced analytics dashboard" 
                : "Basic ad analytics";
        }
        if ($plan->verified_badge) {
            $features[] = lcfirst($plan->plan_name) . " badge";
            $features[] = "Verified tick mark ✓";
        }
        if ($plan->theme && $plan->theme !== 'standard') {
            $features[] = "Special VIP app theme";
        }
        if ($plan->ad_free) {
            $features[] = "Ad-free experience";
        }
        $features[] = "{$plan->validity_days} days validity";

        return $features;
    }
}
