<?php

namespace App\Http\Controllers;

use App\Http\Traits\ResponseTrait;
use App\Models\PaymentMethod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PaymentMethodController extends Controller
{
    use ResponseTrait;

    /**
     * Get user's payment methods
     * GET /payment-methods
     */
    public function index(Request $request)
    {
        $user = $request->user();
        
        $paymentMethods = PaymentMethod::where('user_id', $user->id)
            ->where('is_active', true)
            ->orderBy('is_default', 'desc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($method) {
                return [
                    'id' => $method->id,
                    'type' => $method->type,
                    'brand' => $method->brand,
                    'last4' => $method->last4,
                    'expiry_month' => $method->expiry_month,
                    'expiry_year' => $method->expiry_year,
                    'provider' => $method->provider,
                    'phone' => $method->phone,
                    'is_default' => $method->is_default,
                    'nickname' => $method->nickname,
                ];
            });

        return $this->successResponse($paymentMethods, 'Payment methods retrieved successfully');
    }

    /**
     * Add payment method
     * POST /payment-methods
     */
    public function store(Request $request)
    {
        $request->validate([
            'type' => 'required|string|in:card,mobile_money,bank_transfer,paypal',
            'card_number' => 'nullable|string|required_if:type,card',
            'expiry_month' => 'nullable|integer|min:1|max:12|required_if:type,card',
            'expiry_year' => 'nullable|integer|min:' . date('Y') . '|required_if:type,card',
            'cvv' => 'nullable|string|required_if:type,card',
            'provider' => 'nullable|string',
            'phone' => 'nullable|string|required_if:type,mobile_money',
            'nickname' => 'nullable|string|max:255',
            'is_default' => 'boolean',
        ]);

        $user = $request->user();

        DB::beginTransaction();
        try {
            // In a real implementation, you would tokenize the payment method with a payment gateway
            // For now, we'll just store basic information
            $last4 = null;
            $brand = null;
            $providerToken = null;

            if ($request->type === 'card' && $request->card_number) {
                $last4 = substr($request->card_number, -4);
                // Determine brand from card number (simplified)
                $firstDigit = substr($request->card_number, 0, 1);
                if ($firstDigit == '4') {
                    $brand = 'Visa';
                } elseif ($firstDigit == '5') {
                    $brand = 'Mastercard';
                } else {
                    $brand = 'Other';
                }
                // In real implementation, tokenize with payment gateway
                $providerToken = 'tok_' . str_random(24); // Placeholder
            } elseif ($request->type === 'mobile_money' && $request->phone) {
                $last4 = substr($request->phone, -4);
                $brand = $request->provider ?? 'MTN'; // Default provider
            }

            $paymentMethod = PaymentMethod::create([
                'user_id' => $user->id,
                'type' => $request->type,
                'brand' => $brand,
                'last4' => $last4,
                'expiry_month' => $request->expiry_month,
                'expiry_year' => $request->expiry_year,
                'provider' => $request->provider ?? 'stripe', // Default provider
                'phone' => $request->phone,
                'provider_token' => $providerToken,
                'is_default' => $request->boolean('is_default', false),
                'nickname' => $request->nickname,
            ]);

            DB::commit();

            return response()->json([
                'code' => 201,
                'error' => false,
                'status' => 'success',
                'message' => 'Payment method added successfully',
                'data' => [
                    'payment_method' => [
                        'id' => $paymentMethod->id,
                        'type' => $paymentMethod->type,
                        'brand' => $paymentMethod->brand,
                        'last4' => $paymentMethod->last4,
                        'expiry_month' => $paymentMethod->expiry_month,
                        'expiry_year' => $paymentMethod->expiry_year,
                        'provider' => $paymentMethod->provider,
                        'phone' => $paymentMethod->phone,
                        'is_default' => $paymentMethod->is_default,
                        'nickname' => $paymentMethod->nickname,
                    ],
                ],
            ], 201, [], JSON_NUMERIC_CHECK);

        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorResponse('Failed to add payment method: ' . $e->getMessage());
        }
    }

    /**
     * Delete payment method
     * DELETE /payment-methods/{id}
     */
    public function destroy(Request $request, PaymentMethod $paymentMethod)
    {
        $user = $request->user();

        // Verify ownership
        if ($paymentMethod->user_id !== $user->id) {
            return $this->notFoundResponse();
        }

        // Check if payment method is being used by active subscription
        $activeSubscription = \App\Models\Subscription::where('payment_method_id', $paymentMethod->id)
            ->where('status', 'active')
            ->where(function ($query) {
                $query->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            })
            ->exists();

        if ($activeSubscription) {
            return $this->errorResponse('Cannot delete payment method that is being used by an active subscription');
        }

        $paymentMethod->update(['is_active' => false]);
        // Or delete: $paymentMethod->delete();

        return $this->successResponse([], 'Payment method deleted successfully');
    }
}
