<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\Tenant;
use App\Services\PaymentService;
use App\Services\TenantSyncService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    protected $paymentService;
    protected $syncService;

    public function __construct(PaymentService $paymentService, TenantSyncService $syncService)
    {
        $this->paymentService = $paymentService;
        $this->syncService = $syncService;
    }

    public function index()
    {
        // Admin only - view payment settings
        if (!Auth::user()->hasRole('Admin')) {
            abort(403);
        }

        $gateways = $this->paymentService->getActiveGateways();
        $settings = AppSetting::where('key', 'like', '%payment%')
                            ->orWhere('key', 'like', '%sslcommerz%')
                            ->orWhere('key', 'like', '%bkash%')
                            ->orWhere('key', 'like', '%nagad%')
                            ->orWhere('key', 'like', '%rocket%')
                            ->get()
                            ->pluck('value', 'key')
                            ->toArray();

        return view('admin.payment.index', compact('gateways', 'settings'));
    }

    public function updateSettings(Request $request)
    {
        // Admin only
        if (!Auth::user()->hasRole('Admin')) {
            abort(403);
        }

        $validated = $request->validate([
            'payment_gateway' => 'required|in:stripe,sslcommerz',
            'payment_key' => 'nullable|string',
            'payment_secret' => 'nullable|string',
            'stripe_sandbox' => 'boolean',
            'sslcommerz_store_id' => 'nullable|string',
            'sslcommerz_store_password' => 'nullable|string',
            'sslcommerz_sandbox' => 'boolean',
            'enable_bkash_manual' => 'boolean',
            'bkash_number' => 'nullable|string',
            'bkash_type' => 'in:personal,business',
            'enable_nagad_manual' => 'boolean',
            'nagad_number' => 'nullable|string',
            'nagad_type' => 'in:personal,business',
            'enable_rocket_manual' => 'boolean',
            'rocket_number' => 'nullable|string',
            'rocket_type' => 'in:personal,business',
        ]);

        // Update all settings
        foreach ($validated as $key => $value) {
            AppSetting::set($key, $value, 'payment');
        }

        return redirect()->route('admin.payment.index')
                    ->with('success', 'Payment settings updated successfully.');
    }

    public function purchasePlan(Request $request, Plan $plan)
    {
        $request->validate([
            'payment_gateway' => 'required|in:stripe,sslcommerz,bkash,nagad,rocket',
        ]);

        $tenant = Auth::user()->tenant;
        
        if (!$tenant) {
            abort(403, 'Tenant not found');
        }

        // Check if tenant already has an active subscription
        $existingSubscription = $tenant->subscription()
            ->where('status', 'active')
            ->where('ends_at', '>', now())
            ->first();

        if ($existingSubscription) {
            return back()->with('error', 'You already have an active subscription.');
        }

        try {
            // Process payment
            $result = $this->paymentService->processPayment(
                $request->payment_gateway,
                $plan->price,
                'USD',
                "Subscription to {$plan->name} for {$tenant->name}",
                [
                    'tenant_id' => $tenant->id,
                    'tenant_name' => $tenant->name,
                    'plan_id' => $plan->id,
                    'plan_name' => $plan->name,
                    'user_id' => Auth::id(),
                    'user_email' => Auth::user()->email
                ]
            );

            if ($result['success']) {
                // Create subscription record
                $ends_at = match($plan->interval) {
                    'daily' => now()->addDays(1),
                    'monthly' => now()->addDays(30), // 30 Day = 1 Month
                    'yearly' => now()->addDays(360), // 12 * 30 Days = 360 Days or 12 Months
                    default => now()->addMonths(1),
                };

                $subscription = $tenant->subscription()->create([
                    'plan_id' => $plan->id,
                    'status' => 'active',
                    'starts_at' => now(),
                    'ends_at' => $ends_at,
                    'trial_ends_at' => null,
                    'payment_gateway' => $result['gateway'],
                    'transaction_id' => $result['transaction_id'],
                    'amount' => $result['amount'],
                    'currency' => $result['currency'],
                    'payment_status' => 'paid'
                ]);

                // Update Tenant Category from Plan
                if ($plan->tenant_category_id) {
                    $tenant->update(['tenant_category_id' => $plan->tenant_category_id]);
                    
                    // Sync default categories to tenant database
                    if ($plan->category && $plan->category->default_categories) {
                        $this->syncService->syncCategoriesToTenant($tenant, $plan->category->default_categories);
                    }
                }

                Log::info('Subscription purchased successfully', [
                    'tenant_id' => $tenant->id,
                    'plan_id' => $plan->id,
                    'transaction_id' => $result['transaction_id'],
                    'amount' => $result['amount']
                ]);

                return redirect()->route('tenant.dashboard')
                    ->with('success', "Subscription to {$plan->name} purchased successfully!");
            } else {
                return back()->with('error', 'Payment failed. Please try again.');
            }

        } catch (\Exception $e) {
            Log::error('Payment processing failed', [
                'tenant_id' => $tenant->id,
                'plan_id' => $plan->id,
                'error' => $e->getMessage()
            ]);

            return back()->with('error', 'Payment processing failed: ' . $e->getMessage());
        }
    }

    public function paymentSuccess(Request $request)
    {
        $transactionId = $request->input('transaction_id');
        $gateway = $request->input('gateway');

        // Verify payment
        $verification = $this->paymentService->verifyPayment($gateway, $transactionId);

        if ($verification['success']) {
            // Update subscription status if needed
            $subscription = Subscription::where('transaction_id', $transactionId)->first();
            if ($subscription) {
                $subscription->update([
                    'payment_status' => 'verified',
                    'verified_at' => now()
                ]);
            }

            return redirect()->route('tenant.dashboard')
                ->with('success', 'Payment verified successfully!');
        } else {
            return redirect()->route('tenant.subscription.index')
                ->with('error', 'Payment verification failed. Please contact support.');
        }
    }

    public function paymentCallback(Request $request)
    {
        // Handle payment gateway callbacks (webhooks)
        $gateway = $request->input('gateway');
        $transactionId = $request->input('transaction_id');
        $status = $request->input('status');

        Log::info('Payment callback received', [
            'gateway' => $gateway,
            'transaction_id' => $transactionId,
            'status' => $status,
            'data' => $request->all()
        ]);

        // Update subscription based on callback
        $subscription = Subscription::where('transaction_id', $transactionId)->first();
        if ($subscription) {
            $subscription->update([
                'payment_status' => $status === 'success' ? 'paid' : 'failed',
                'status' => $status === 'success' ? 'active' : 'cancelled'
            ]);
        }

        return response()->json(['status' => 'received']);
    }

    public function refund(Request $request, Subscription $subscription)
    {
        // Admin only
        if (!Auth::user()->hasRole('Admin')) {
            abort(403);
        }

        $request->validate([
            'reason' => 'required|string|max:255',
            'amount' => 'nullable|numeric|min:0|max:' . $subscription->amount
        ]);

        try {
            $refund = $this->paymentService->refundPayment(
                $subscription->payment_gateway,
                $subscription->transaction_id,
                $request->amount
            );

            if ($refund['success']) {
                $subscription->update([
                    'status' => 'cancelled',
                    'refunded_at' => now(),
                    'refund_reason' => $request->reason,
                    'refund_amount' => $refund['amount'],
                    'refund_id' => $refund['refund_id']
                ]);

                return back()->with('success', 'Refund processed successfully.');
            } else {
                return back()->with('error', 'Refund failed. Please try again.');
            }

        } catch (\Exception $e) {
            Log::error('Refund processing failed', [
                'subscription_id' => $subscription->id,
                'error' => $e->getMessage()
            ]);

            return back()->with('error', 'Refund processing failed: ' . $e->getMessage());
        }
    }
}
