<?php

namespace App\Http\Controllers\III_Ranks;

namespace App\Http\Controllers;

use App\Helper\Helper;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;

class PaymentController extends Controller
{

    /**
    * Checkout
    * @param Request $request
    * @return type
    */
    public function checkout(Request $request) {
        $cartTotal = 0;
        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId')
        );

        $url = env('API_URL') . 'stripe/get-customer-id';
        Helper::GetApi($url, $body);

        $paymentMethods = $this->getPaymentMethods();

        $objCartController = new CartController();
        $intCartTotal = $objCartController->getCartTotalAmount();

        return view('billing.checkout', ["paymentMethods" => $paymentMethods,"intCartTotal" => reset($intCartTotal)]);

    }

    /**
    * Add Balance
    * @param Request $request
    * @return type
    */
    public function recharge(Request $request)
    {
        $url = env('API_URL') . 'user-detail';
        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId'),
            'parentId' => Session::get('parentId')
        );
        $response = Helper::PostApi($url, $body);
        $user = $response->data;
        // Extract auto-reload fields safely
        $autoReloadEnabled = $user->auto_reload_enabled ?? 0;
        $autoReloadThreshold = $user->auto_reload_threshold ?? null;
        $autoReloadAmount = $user->auto_reload_amount ?? null;
        $razorpayCustomerTokenExists = $user->razorpay_token_id ?? null;

        $urlWalletCurrency = env('API_URL') . 'wallet/currency';
        $responseWalletCurrency = Helper::GetApi($urlWalletCurrency);
        $wallet = $responseWalletCurrency?->data ?? null;
        if ($wallet->currency_code == "INR") {
            return view('billing.razorpay-recharge', [
                "autoReloadEnabled" => $autoReloadEnabled,
                "autoReloadThreshold" => $autoReloadThreshold,
                "autoReloadAmount" => $autoReloadAmount,
                "razorpayCustomerTokenExists" => $razorpayCustomerTokenExists,
                "wallet" => $wallet,
            ]);
        }

        $paymentMethods = $this->getPaymentMethods();
        if (count($paymentMethods) < 1) {
            return redirect('payment-method-list');
        }

        $defaultPaymentMethod = $this->getDefaultPaymentMethod();

        return view('billing.recharge', [
            "paymentMethods" => $paymentMethods,
            "defaultPaymentMethod" => $defaultPaymentMethod,
            "autoReloadEnabled" => $autoReloadEnabled,
            "autoReloadThreshold" => $autoReloadThreshold,
            "autoReloadAmount" => $autoReloadAmount,
        ]);
    }


    /**
    * Get Payment Method
    * @param Request $request
    * @return type
    */
    public function getPaymentMethods() {
        $paymentMethods = [];
        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId')
        );
        $url = env('API_URL') . 'stripe/get-customer-payment-method';
        $response = Helper::GetApi($url, $body);

        if ($response->success) {
            if($response->data[0] == NULL){
                return [];
            }
            $paymentMethods = (array)$response->data[0]->data;
        }
        return $paymentMethods;
    }

    /**
     * SHow payment method / card lists
     * @return type
     */
    public function showPaymentMethodList()
    {
        if (session::get('currency') == "₹") {
            return redirect('/recharge');
        }
        $paymentMethods = $this->getPaymentMethods();
        $defaultPaymentMethod = $this->getDefaultPaymentMethod();
        $data = [
            "paymentMethods" => $paymentMethods,
            "defaultPaymentMethod" => $defaultPaymentMethod
        ];
        return view('billing.payment-method-list', $data);
    }

    /**
     * Delete payment method / card lists
     * @return type
     */
    public function deletePaymentMethod($id) {
        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId'),
            'payment_method_id' => $id
        );

        $url = env('API_URL') . 'stripe/delete-stripe-payment_method';
        $response = Helper::PostApi($url, $body);
        return response()->json($response);
    }

    /**
    * Add pay method
    * @param Request $request
    * @return type
    */
    public function editPaymentMethod() {
        return view('billing.add-payment-method', []);
    }

    /**
    * Add Card
    * @param Request $request
    * @return type
    */
    public function saveCard(Request $request) {
     $body = [
        'id'            => Session::get('id'),
        'token'         => Session::get('tokenId'),
        'payment_method' => $request->payment_method, // This is the only data sent from your script
        'set_default' => $request->set_default
    ];

        $url = env('API_URL') . 'stripe/save-card-new';
        $response = Helper::PostApi($url, $body);
        return response()->json($response);
    }

    /**
    * update pay method
    * @param Request $request
    * @return type
    */
    public function updatePaymentMethod($id) {
        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId'),
            'payment_method_id' => $id
        );

        $url = env('API_URL') . 'stripe/get-payment-method';
        $response = Helper::PostApi($url, $body);

        if($response->success == 'true') {
            $pmDetails = $response->data[0];
            return view('billing.update-payment-method', ['pmDetails' => $pmDetails]);
        }
        return redirect()->to('payment-method-list');
    }

    /**
    * Update Card
    * @param Request $request
    * @return type
    */
    public function updateCard(Request $request) {
        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId'),
            'payment_method_id' => $request->payment_method_id,
            'full_name' => $request->full_name,
            'line1' => $request->line1,
            'city' => $request->city,
            'state' => $request->state,
            'country' => $request->country,
            'postal_code' => $request->postal_code,
            'exp_month' => $request->exp_month,
            'exp_year' => $request->exp_year
        );

        $url = env('API_URL') . 'stripe/update-card';
        $response = Helper::PostApi($url, $body);
        return response()->json($response);
    }

     public function setDefaultPaymentMethod(Request $request)
    {
        try {
            $request->validate([
                'payment_method_id' => 'required|string',
            ]);

            $body = [
                'id' => Session::get('id'),
                'token' => Session::get('tokenId'),
                'payment_method' => $request->payment_method_id,
            ];

            $url = env('API_URL') . 'stripe/set-default-payment-method';
            $response = Helper::PostApi($url, $body);

            if ($response->success) {
                return response()->json([
                    'success' => true,
                    'message' => 'Default payment method updated successfully.',
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to set default payment method: ' . ($response->message ?? 'Unknown error'),
                ], 500);
            }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to set default payment method: ' . $e->getMessage(),
            ], 500);
        }
    }

     public function getDefaultPaymentMethod()
    {
        try {
            $body = [
                'id' => Session::get('id'),
                'token' => Session::get('tokenId'),
            ];

            $url = env('API_URL') . 'stripe/get-default-payment-method';
            $response = Helper::PostApi($url, $body);
            return $response->data ?? null;
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve default payment method: ' . $e->getMessage(),
            ], 500);
        }
    }


     public function updateAutoRechargeFrontend(Request $request)
    {
        try {
            // Validate frontend input
            $validated = $request->validate([
                'auto_reload_enabled'   => 'nullable|boolean',
                'auto_reload_threshold' => 'nullable|numeric|min:0',
                'auto_reload_amount'    => 'nullable|numeric|min:0',
                'delete_mandate'         => 'nullable|boolean',
            ]);

            // Prepare payload
            $payload = [
                'id' => Session::get('id'),
                'token' => Session::get('tokenId'),
                'parentId' => Session::get('parentId'),
                'auto_reload_enabled'   => (int)($validated['auto_reload_enabled'] ?? 0),
                'auto_reload_threshold' => $validated['auto_reload_threshold'] ?? null,
                'auto_reload_amount'    => $validated['auto_reload_amount'] ?? null,
                'delete_mandate'        => isset($validated['delete_mandate']) ? (bool)$validated['delete_mandate'] : false,
            ];

            // Call Lumen backend API
            $url = env('API_URL') . 'user/auto-recharge-update';
            $response = Helper::PostApi($url, $payload);

            // Handle backend API response
            if (!isset($response->success) || !$response->success) {
                return response()->json([
                    'success' => false,
                    'message' => $response->message ?? 'Failed to update settings on backend.',
                ], 400);
            }

            return response()->json([
                'success' => true,
                'message' => 'Auto-recharge settings updated successfully.',
            ]);
        } catch (\Throwable $e) {
            Log::error('AutoRecharge frontend update failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An unexpected error occurred while saving settings.',
            ], 500);
        }
    }

    public function buySubscriptionRZ(Request $request)
    {
        $urlWalletCurrency = env('API_URL') . 'wallet/currency';
        $responseWalletCurrency = Helper::GetApi($urlWalletCurrency);
        $wallet = $responseWalletCurrency?->data ?? null;

        $planURL = env('API_URL') . 'razorpay-fetch-subscription-plan';
        $responsePlan = Helper::GetApi($planURL);
        $plans = $responsePlan?->data ?? null;

        $clientPackageURL = env('API_URL') . 'client-package-exists';
        $body = [
            'client_id' => Session::get('parentId'),
            'razorpay_plan_id' => $plans->plan_id,
        ];
        $responseClientPackage = Helper::PostApi($clientPackageURL, $body);
        $clientPackage = $responseClientPackage ?? null;
        if ($wallet->currency_code == "INR") {
            return view('billing.buy-subscription-rz', compact('plans', 'clientPackage'));
        }
    }
}


