<?php

namespace App\Http\Controllers;

use App\Model\Client\wallet;
use App\Model\Client\walletTransaction;
use App\Model\Master\Order;
use App\Model\Master\PaymentTransaction;
use Razorpay\Api\Api;
use Illuminate\Http\Request;
use App\Model\Master\ClientPackage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Carbon;
use App\Model\Master\Package;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class RazorpayController extends Controller
{
    protected $PlanId;
    protected $TrialPackageKey = "";

    public function __construct()
    {
        $this->PlanId = env('RAZORPAY_PLAN_ID', 'plan_RsiNoYek6KV4uO');
    }

    public function api()
    {
        return new Api(env('RAZORPAY_KEY'), env('RAZORPAY_SECRET'));
    }

    /**
     * ----------------------------------------------------------------------------
     *  CREATE RECHARGE ORDER (Razorpay)
     * ----------------------------------------------------------------------------
     */
    public function createOrderRecharge(Request $r)
    {
        $this->logToFile("RAZORPAY_RECHARGE_STEP_1: Request received - " . json_encode($r->all()));

        $this->validate($r, [
            'amount' => 'required|numeric|min:1'
        ]);

        $this->logToFile("RAZORPAY_RECHARGE_STEP_2: Validation OK - Amount: {$r->amount}");

        try {
            $this->logToFile("RAZORPAY_RECHARGE_STEP_3: Creating Razorpay Order...");

            $apiOrder = $this->api()->order->create([
                'receipt' => 'rech_' . time(),
                'amount' => $r->amount * 100,
                'currency' => 'INR'
            ]);

            $this->logToFile("RAZORPAY_RECHARGE_STEP_4: Razorpay Order Created - " . json_encode($apiOrder->toArray()));

            $this->logToFile("RAZORPAY_RECHARGE_STEP_5: Creating DB Order...");

            $order = new Order();
            $order->client_id = $r->auth->parent_id;
            $order->net_amount = $r->amount;
            $order->gross_amount = $r->amount;
            $order->status = 'initiated';
            $order->payment_method = 'razorpay';
            $order->order_type = 'recharge';
            $order->gateway_order_id = $apiOrder['id'];
            $order->save();

            $this->logToFile("RAZORPAY_RECHARGE_STEP_6: DB Order Saved - Order ID: {$order->id}");

            $this->logToFile("RAZORPAY_RECHARGE_STEP_7: Creating Payment Transaction Entry...");

            $pt = new PaymentTransaction();
            $pt->order_id = $order->id;
            $pt->payment_gateway_type = 'razorpay';
            $pt->status = 'initiated';
            $pt->response = json_encode($apiOrder->toArray());
            $pt->save();

            $this->logToFile("RAZORPAY_RECHARGE_STEP_8: Payment Transaction Saved - PT ID: {$pt->id}");

            return [
                'success' => true,
                'order_id' => $apiOrder['id'],
                'amount' => $r->amount
            ];
        } catch (\Throwable $e) {
            $this->logToFile("ERROR: RAZORPAY_RECHARGE_ERROR_CREATE_ORDER - Message: {$e->getMessage()}");

            return $this->failResponse("Failed to create order", [$e->getMessage()]);
        }
    }

    /**
     * ----------------------------------------------------------------------------
     *  VERIFY RECHARGE ORDER
     * ----------------------------------------------------------------------------
     */
    public function verifyOrderRecharge(Request $r)
    {
        $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_1: Request received - " . json_encode($r->all()));

        try {
            $this->validate($r, [
                'razorpay_order_id' => 'required',
                'razorpay_payment_id' => 'required',
                'razorpay_signature' => 'required',
                'amount' => 'required|numeric'
            ]);

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_2: Validation OK");

            $order = Order::where('gateway_order_id', $r->razorpay_order_id)->first();

            if (!$order) {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_RECHARGE_STEP_3: Order Not Found");
                return $this->failResponse("Order not found", [], null, 422);
            }

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_3: Order Found - Order ID: {$order->id}");

            $generated = hash_hmac(
                'sha256',
                $r->razorpay_order_id . '|' . $r->razorpay_payment_id,
                env('RAZORPAY_SECRET')
            );

            if ($generated !== $r->razorpay_signature) {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_RECHARGE_STEP_4: INVALID SIGNATURE");

                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode(['error' => 'Invalid signature'])
                    ]);

                return $this->failResponse("Invalid signature", [], null, 400);
            }

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_4: Signature Valid");

            $api = $this->api();
            $razorOrder = $api->order->fetch($r->razorpay_order_id);
            $payments = $razorOrder->payments();

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_5: Razorpay Payments Retrieved");

            $payment = collect($payments['items'])
                ->firstWhere('id', $r->razorpay_payment_id);

            if (!$payment) {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_RECHARGE_STEP_6: PAYMENT NOT FOUND");

                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode(['error' => 'Payment not found'])
                    ]);

                return $this->failResponse("Payment not found", [], null, 422);
            }

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_6: Payment Found");

            if ($payment['status'] !== 'captured') {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_RECHARGE_STEP_7: PAYMENT NOT CAPTURED");

                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode($payment->toArray())
                    ]);

                return $this->failResponse("Payment not captured", [], null, 422);
            }

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_7: Payment Captured");

            $order->status = 'success';
            $order->save();

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_8: Order Updated To Success");

            PaymentTransaction::where('order_id', $order->id)
                ->update([
                    'status' => 'success',
                    'response' => json_encode($payment->toArray())
                ]);

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_9: Payment Transaction Updated");

            wallet::creditCharge($r->amount, $r->auth->parent_id, 'INR');

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_10: Wallet Credited");

            $w = new walletTransaction();
            $w->setConnection("mysql_" . $r->auth->parent_id);
            $w->currency_code = 'INR';
            $w->amount = $r->amount;
            $w->transaction_type = 'credit';
            $w->transaction_reference = $r->razorpay_payment_id;
            $w->description = 'Recharge';
            $w->save();

            $this->logToFile("RAZORPAY_VERIFY_RECHARGE_STEP_11: Wallet Transaction Saved");

            // Send email notification to user and admin
            $this->sendRechargeEmail($r->auth, $r->amount, $r->razorpay_payment_id);

            return $this->successResponse("Recharge successful", []);
        } catch (\Throwable $e) {

            $this->logToFile("ERROR: RAZORPAY_VERIFY_RECHARGE_EXCEPTION - Message: {$e->getMessage()}");

            if (isset($order)) {
                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode(['exception' => $e->getMessage()])
                    ]);
            }

            return $this->failResponse("Recharge failed", [$e->getMessage()]);
        }
    }

    public function fetchSubscriptionPlan(Request $r)
    {
        $this->logToFile("RAZORPAY_FETCH_PLAN_STEP_1: Request received - " . json_encode($r->all()));

        try {
            $planId = $this->PlanId;

            $this->logToFile("RAZORPAY_FETCH_PLAN_STEP_2: Fetching plan - Plan ID: {$planId}");

            $plan = $this->api()->plan->fetch($planId);

            $this->logToFile("RAZORPAY_FETCH_PLAN_STEP_4: Razorpay plan fetched - " . json_encode($plan->toArray()));

            // Extract data based on actual response
            $item = $plan['item'];
            $priceINR = $item['amount'] / 100;     // convert paise → INR
            $name = $item['name'];
            $currency = $item['currency'];
            $interval = $plan['period'];           // monthly / yearly
            $frequency = $plan['interval'];         // 1, 3, 6, etc.

            $billingCycle = $frequency . " " .
                ($interval === "monthly" ? "month(s)" : ($interval === "yearly" ? "year(s)" : $interval));

            $this->logToFile("RAZORPAY_FETCH_PLAN_STEP_5: Final processed plan - Name: {$name}, Amount: {$priceINR}, Interval: {$interval}, Frequency: {$frequency}");

            return [
                'success' => true,
                'message' => 'Plan fetched successfully',
                'data' => [
                    'plan_id' => $planId,
                    'name' => $name,
                    'amount' => $priceINR,
                    'currency' => $currency,
                    'interval' => $interval,
                    'frequency' => $frequency,
                    'billing_cycle' => $billingCycle
                ]
            ];
        } catch (\Throwable $e) {

            $this->logToFile("ERROR: RAZORPAY_FETCH_PLAN_ERROR - Message: {$e->getMessage()}");

            return [
                'success' => false,
                'message' => 'Failed to fetch plan',
                'error' => $e->getMessage()
            ];
        }
    }



    /**
     * ----------------------------------------------------------------------------
     *  CREATE SUBSCRIPTION
     * ----------------------------------------------------------------------------
     */
    public function createSubscription(Request $r)
    {
        $this->logToFile("RAZORPAY_SUB_STEP_1: Received Request - " . json_encode($r->all()));

        $this->validate($r, [
            'plan_id' => 'required|string',
        ]);

        try {
            $this->logToFile("RAZORPAY_SUB_STEP_2: Creating DB Order...");

            $order = new Order();
            $order->client_id = $r->auth->parent_id;
            $order->net_amount = 0;
            $order->gross_amount = 0;
            $order->status = 'initiated';
            $order->payment_method = 'razorpay';
            $order->order_type = 'subscription';
            $order->save();

            $this->logToFile("RAZORPAY_SUB_STEP_3: Order Saved - Order ID: {$order->id}");

            $pt = new PaymentTransaction();
            $pt->order_id = $order->id;
            $pt->payment_gateway_type = 'razorpay';
            $pt->status = 'initiated';
            $pt->response = json_encode(['plan_id' => $r->plan_id]);
            $pt->save();

            $this->logToFile("RAZORPAY_SUB_STEP_4: Payment Transaction Created - PT ID: {$pt->id}");

            $this->logToFile("RAZORPAY_SUB_STEP_5: Creating Razorpay Subscription...");

            $sub = $this->api()->subscription->create([
                'plan_id' => $r->plan_id,
                'customer_notify' => 1,
                'total_count' => 12
            ]);

            $this->logToFile("RAZORPAY_SUB_STEP_6: Subscription Created - " . json_encode($sub->toArray()));

            $order->gateway_subscription_id = $sub['id'];
            $order->save();

            $pt->response = json_encode($sub->toArray());
            $pt->save();

            $this->logToFile("RAZORPAY_SUB_STEP_7: Subscription DB Updates Complete");

            return [
                'success' => true,
                'subscription_id' => $sub['id'],
                'order_db_id' => $order->id
            ];
        } catch (\Throwable $e) {
            $this->logToFile("ERROR: RAZORPAY_SUB_CREATE_ERROR - Message: {$e->getMessage()}");

            return $this->failResponse("Failed to create subscription", [$e->getMessage()]);
        }
    }

    /**
     * ----------------------------------------------------------------------------
     *  VERIFY SUBSCRIPTION PAYMENT
     *  - Primary activation path (frontend callback)
     *  - Idempotent: safe to call multiple times for same payment_id
     *  - Uses Subscription + Payment API (NOT Invoice API - has propagation delay)
     * ----------------------------------------------------------------------------
     */
    public function verifySubscription(Request $r)
    {
        $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_1: Request received - " . json_encode($r->all()));

        try {
            $this->validate($r, [
                'razorpay_subscription_id' => 'required',
                'razorpay_payment_id' => 'required',
                'razorpay_signature' => 'required'
            ]);

            $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_2: Validation OK");

            // ── IDEMPOTENCY CHECK ──
            // If this payment_id was already processed, return success immediately
            $alreadyProcessed = ClientPackage::where('psp_reference', $r->razorpay_payment_id)->first();
            if ($alreadyProcessed) {
                $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_2B: IDEMPOTENT HIT - Payment already processed - psp_reference: {$r->razorpay_payment_id}");
                return $this->successResponse("Subscription already activated", []);
            }

            $order = Order::where('gateway_subscription_id', $r->razorpay_subscription_id)
                ->first();

            if (!$order) {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_SUB_STEP_3: Order Not Found");
                return $this->failResponse("Order not found", [], null, 422);
            }

            // ── SIGNATURE VERIFICATION ──
            $generated = hash_hmac(
                'sha256',
                $r->razorpay_payment_id . '|' . $r->razorpay_subscription_id,
                env('RAZORPAY_SECRET')
            );

            if ($generated !== $r->razorpay_signature) {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_SUB_STEP_4: INVALID SIGNATURE");

                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode(['error' => 'Invalid signature'])
                    ]);

                return $this->failResponse("Invalid signature", [], null, 400);
            }

            $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_4: Signature Valid");

            // ── FETCH SUBSCRIPTION STATUS ──
            // Signature is cryptographic proof. Subscription fetch is a secondary confirmation.
            $subscription = $this->api()->subscription->fetch($r->razorpay_subscription_id);

            $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_5: Subscription Fetched - " . json_encode($subscription->toArray()));

            $subStatus = $subscription['status'] ?? 'unknown';

            if (!in_array($subStatus, ['active', 'authenticated', 'completed'])) {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_SUB_STEP_6: SUBSCRIPTION NOT ACTIVE - Status: {$subStatus}");

                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode($subscription->toArray())
                    ]);

                return $this->failResponse("Subscription not active (status: {$subStatus})", [], null, 422);
            }

            // ── FETCH PAYMENT STATUS ──
            $payment = $this->api()->payment->fetch($r->razorpay_payment_id);

            $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_6: Payment Fetched - Status: " . ($payment['status'] ?? 'unknown'));

            if (!in_array($payment['status'] ?? '', ['captured', 'authorized'])) {
                $this->logToFile("ERROR: RAZORPAY_VERIFY_SUB_STEP_6B: PAYMENT NOT CAPTURED - Status: " . ($payment['status'] ?? 'unknown'));

                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode($payment->toArray())
                    ]);

                return $this->failResponse("Payment not captured", [], null, 422);
            }

            $paymentAmount = $payment['amount'] ?? 0;

            $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_7: Payment Verified Successfully - Amount: {$paymentAmount}");

            // ── UPDATE ORDER + TRANSACTION (inside DB transaction) ──
            DB::connection('master')->beginTransaction();

            try {
                $order->status = 'success';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'success',
                        'response' => json_encode($payment->toArray())
                    ]);

                $this->logToFile("RAZORPAY_VERIFY_SUB_STEP_8: Subscription Verification Complete");

                // ── PACKAGE ASSIGNMENT ──
                $this->logToFile("RAZORPAY_VERIFY_SUB_PACKAGE_STEP: Starting package assignment");

                $clientId = $r->auth->parent_id;

                // End trial package if active
                $trial = ClientPackage::where('client_id', $clientId)
                    ->where('package_key', $this->TrialPackageKey)
                    ->where('end_time', '>=', Carbon::now())
                    ->first();

                if ($trial) {
                    $this->logToFile("RAZORPAY_VERIFY_SUB_PACKAGE_STEP: Ending active trial");
                    $trial->end_time = Carbon::now();
                    $trial->expiry_time = Carbon::now();
                    $trial->save();
                }

                $package = Package::where('razorpay_plan_id', $this->PlanId)->first();

                if (!$package) {
                    DB::connection('master')->rollBack();
                    $this->logToFile("ERROR: RAZORPAY_VERIFY_SUB_PACKAGE_STEP: Package not found for Razorpay plan - Plan ID: {$this->PlanId}");
                    return $this->failResponse("Package not configured", [], null, 422);
                }

                $planKey = $package->key;
                $start = Carbon::now();
                $end = Carbon::now()->addMonth();

                // ── IDEMPOTENCY: Re-check inside transaction ──
                $dupeCheck = ClientPackage::where('psp_reference', $r->razorpay_payment_id)->first();
                if ($dupeCheck) {
                    DB::connection('master')->commit();
                    $this->logToFile("RAZORPAY_VERIFY_SUB_PACKAGE_STEP: IDEMPOTENT HIT inside txn - psp_reference: {$r->razorpay_payment_id}");
                    return $this->successResponse("Subscription already activated", []);
                }

                // Check if client already has this package (update vs create)
                $existing = ClientPackage::where('client_id', $clientId)
                    ->where('package_key', $planKey)
                    ->orderByDesc('id')
                    ->first();

                if ($existing) {
                    $this->logToFile("RAZORPAY_VERIFY_SUB_PACKAGE_STEP: Updating existing package - Client Package ID: {$existing->id}");

                    $existing->start_time = $start;
                    $existing->end_time = $end;
                    $existing->expiry_time = $end;
                    $existing->payment_cent_amount = $paymentAmount;
                    $existing->payment_time = Carbon::now();
                    $existing->payment_method = "razorpay";
                    $existing->psp_reference = $r->razorpay_payment_id;
                    $existing->razorpay_subscription_id = $r->razorpay_subscription_id;
                    $existing->razorpay_plan_id = $this->PlanId;
                    $existing->save();

                    DB::connection('master')->commit();

                    $this->sendSubscriptionEmail($r->auth, $existing, $paymentAmount, $r->razorpay_payment_id, 'renewed');
                    wallet::updateSubscriptionStatus($clientId);

                    return $this->successResponse("Subscription renewed successfully", []);
                }

                // ── CREATE NEW PACKAGE ──
                $clientPackage = new ClientPackage();
                $clientPackage->client_id = $clientId;
                $clientPackage->package_key = $planKey;
                $clientPackage->quantity = 1;
                $clientPackage->start_time = $start;
                $clientPackage->end_time = $end;
                $clientPackage->expiry_time = $end;
                $clientPackage->billed = "monthly";
                $clientPackage->payment_cent_amount = $paymentAmount;
                $clientPackage->payment_time = Carbon::now();
                $clientPackage->payment_method = "razorpay";
                $clientPackage->psp_reference = $r->razorpay_payment_id;
                $clientPackage->razorpay_subscription_id = $r->razorpay_subscription_id;
                $clientPackage->razorpay_plan_id = $this->PlanId;
                $clientPackage->save();

                DB::connection('master')->commit();

                $this->logToFile("RAZORPAY_VERIFY_SUB_PACKAGE_STEP: ClientPackage saved - Client Package ID: {$clientPackage->id}");

                $this->sendSubscriptionEmail($r->auth, $clientPackage, $paymentAmount, $r->razorpay_payment_id, 'activated');
                wallet::updateSubscriptionStatus($clientId);

                return $this->successResponse("Subscription activated successfully", []);

            } catch (\Throwable $dbEx) {
                DB::connection('master')->rollBack();
                throw $dbEx;
            }

        } catch (\Throwable $e) {

            $this->logToFile("ERROR: RAZORPAY_VERIFY_SUB_EXCEPTION - Message: {$e->getMessage()} - Trace: {$e->getTraceAsString()}");

            if (isset($order) && $order->status !== 'success') {
                $order->status = 'failed';
                $order->save();

                PaymentTransaction::where('order_id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'response' => json_encode(['exception' => $e->getMessage()])
                    ]);
            }

            return $this->failResponse("Subscription verification failed", [$e->getMessage()]);
        }
    }

    /**
     * ----------------------------------------------------------------------------
     *  CREATE AUTO-RECHARGE MANDATE (UPI Autopay Setup)
     * ----------------------------------------------------------------------------
     */
    public function createAutoRechargeMandate(Request $r)
    {
        $this->logToFile("AUTO_MANDATE_CREATE: request - " . json_encode($r->all()));

        try {
            $amount = max(1, intval($r->amount ?? 100));

            $rzp = $this->api();
            $clientId = $r->auth->parent_id;

            $user = DB::connection("master")->table("users")
                ->where("id", $r->auth->id)
                ->first();

            $customer = null;

            try {
                // TRY CREATING CUSTOMER
                $customer = $rzp->customer->create([
                    "name" => trim($user->first_name . " " . $user->last_name),
                    "email" => $user->email,
                    "contact" => $user->mobile
                ]);

                $this->logToFile("AUTO_MANDATE_CREATE: customer created - " . json_encode($customer->toArray()));
            } catch (\Exception $e) {

                // ==========================================
                // HANDLE: "Customer already exists" CASE
                // ==========================================
                if (str_contains($e->getMessage(), "Customer already exists")) {

                    $this->logToFile("WARNING: AUTO_MANDATE_CREATE: Customer already exists, fetching...");

                    // Fetch customer by contact (best lookup method)
                    $customerList = $rzp->customer->all([
                        "contact" => $user->mobile
                    ]);

                    if (count($customerList->items) > 0) {
                        $customer = $customerList->items[0];
                        $this->logToFile("AUTO_MANDATE_CREATE: existing customer fetched - " . json_encode($customer->toArray()));
                    } else {
                        // Fallback: search by email
                        $customerList = $rzp->customer->all([
                            "email" => $user->email
                        ]);

                        if (count($customerList->items) > 0) {
                            $customer = $customerList->items[0];
                            $this->logToFile("AUTO_MANDATE_CREATE: existing customer fetched via email - " . json_encode($customer->toArray()));
                        }
                    }

                    if (!$customer) {
                        $this->logToFile("ERROR: AUTO_MANDATE_CREATE: Failed to fetch existing customer");
                        return [
                            "success" => false,
                            "message" => "Unable to fetch existing customer from Razorpay"
                        ];
                    }
                } else {
                    // Any other Razorpay error
                    throw $e;
                }
            }


            // ================================
            // CREATE MANDATE ORDER (UPI Autopay)
            // Per Razorpay docs: method=upi for UPI recurring, amount=100 (₹1 min)
            // ================================
            $order = $rzp->order->create([
                "amount" => 100,  // ₹1 = 100 paise (minimum for UPI authorization)
                "currency" => "INR",
                "receipt" => "mandate_" . time(),
                "method" => "upi",  // Use 'upi' for UPI Autopay (not emandate)
                "customer_id" => $customer["id"],
                "token" => [
                    "max_amount" => 1500000,  // ₹15,000 max limit in paise
                    "expire_at" => strtotime("+5 years"),
                    "frequency" => "as_presented"
                ],
                "notes" => [
                    "type" => "auto_mandate_setup",
                    "client_id" => $clientId,
                    "recharge_amount" => $amount  // User's preferred recharge amount
                ]
            ]);

            $this->logToFile("AUTO_MANDATE_CREATE: order created - " . json_encode($order->toArray()));

            return [
                "success" => true,
                "order_id" => $order["id"],
                "customer_id" => $customer["id"],
                "razorpay_key" => env("RAZORPAY_KEY")
            ];
        } catch (\Exception $e) {
            $this->logToFile("ERROR: AUTO_MANDATE_CREATE_ERROR - Message: {$e->getMessage()}");
            return [
                "success" => false,
                "message" => $e->getMessage()
            ];
        }
    }


    /**
     * ----------------------------------------------------------------------------
     *  VERIFY AUTO-RECHARGE MANDATE (Post-Handler Update)
     * ----------------------------------------------------------------------------
     */
    public function verifyAutoRechargeMandate(Request $r)
    {
        $this->logToFile("AUTO_MANDATE_VERIFY: request - " . json_encode($r->all()));

        try {
            $this->validate($r, [
                "razorpay_payment_id" => "required",
                "razorpay_subscription_id" => "sometimes",
                "razorpay_signature" => "required",
                "razorpay_order_id" => "required",

                "auto_reload_threshold" => "required|integer|min:1",
                "auto_reload_amount" => "required|integer|min:1"
            ]);

            $rzp = $this->api();

            // VERIFY SIGNATURE
            $generated = hash_hmac(
                "sha256",
                $r->razorpay_order_id . "|" . $r->razorpay_payment_id,
                env("RAZORPAY_SECRET")
            );

            if ($generated !== $r->razorpay_signature) {
                return $this->failResponse("Invalid signature", [], null, 400);
            }

            // FETCH PAYMENT → THIS CONTAINS TOKEN INFO
            $payment = $rzp->payment->fetch($r->razorpay_payment_id);

            $customerId = $payment->customer_id ?? null;
            $tokenId = $payment->token_id ?? null;
            $mandateId = $payment->mandate_id ?? null;

            if (!$customerId || !$tokenId) {
                $this->logToFile("ERROR: AUTO_MANDATE_VERIFY: Missing token or customer");
                return $this->failResponse("Mandate not attached to customer", [], null, 422);
            }

            // SAVE TO USER
            DB::connection("master")->update("
            UPDATE users
            SET
                auto_reload_enabled = 1,
                auto_reload_threshold = :threshold,
                auto_reload_amount = :amount,
                razorpay_customer_id = :customer,
                razorpay_token_id = :token,
                razorpay_mandate_id = :mandate
            WHERE id = :id
        ", [
                "threshold" => $r->auto_reload_threshold,
                "amount" => $r->auto_reload_amount,
                "customer" => $customerId,
                "token" => $tokenId,
                "mandate" => $mandateId,
                "id" => $r->auth->id
            ]);

            $this->logToFile("AUTO_MANDATE_VERIFY: saved - Customer: {$customerId}, Token: {$tokenId}, Mandate: {$mandateId}");

            // Send email notification to user and admin
            $this->sendMandateSetupEmail($r->auth, $r->auto_reload_threshold, $r->auto_reload_amount);

            return $this->successResponse("Mandate saved");
        } catch (\Exception $e) {
            $this->logToFile("ERROR: AUTO_MANDATE_VERIFY_ERROR - Message: {$e->getMessage()}");
            return $this->failResponse("Mandate verification failed", [$e->getMessage()]);
        }
    }


    /**
     * ----------------------------------------------------------------------------
     *  TRIGGER AUTO-RECHARGE (One-Off Charge on Low Balance)
     * ----------------------------------------------------------------------------
     */
    public function triggerAutoRecharge(Request $r)
    {
        $this->logToFile("AUTO_RECHARGE_TRIGGER: request - " . json_encode($r->all()));

        try {
            $this->validate($r, [
                "amount" => "required|numeric|min:1"
            ]);

            // Fetch user & mandate info
            $user = DB::connection("master")->table("users")
                ->where("id", $r->auth->id)
                ->first();

            $customerId = $user->razorpay_customer_id;
            $tokenId = $user->razorpay_token_id;
            $clientId = $user->parent_id;

            // Mandate missing → cannot trigger auto debit
            if (!$customerId || !$tokenId) {
                $this->logToFile("WARNING: AUTO_RECHARGE_TRIGGER: missing mandate - Customer ID: {$customerId}, Token ID: {$tokenId}");

                return [
                    "success" => false,
                    "message" => "No active UPI AutoPay mandate found. Please setup auto-recharge again."
                ];
            }

            $rzp = $this->api();
            $amountPaise = intval($r->amount * 100); // ₹ → paise

            // 1. Create Order
            $order = $rzp->order->create([
                "amount"   => $amountPaise,
                "currency" => "INR",
                "receipt"  => "manual_auto_recharge_" . time(),
                "notes"    => [
                    "type"      => "auto_recharge",
                    "client_id" => $clientId,
                    "user_id"   => $user->id
                ]
            ]);

            $this->logToFile("AUTO_RECHARGE_TRIGGER: order_created - " . json_encode($order->toArray()));

            // 2. Create Recurring Payment
            // 2. Pre-Check: Verify Resource Ownership (Customer & Token)
            // Retrieve keys
            $key = \Razorpay\Api\Api::getKey();
            $secret = \Razorpay\Api\Api::getSecret();
            if (!$key) $key = env('RAZORPAY_KEY');
            if (!$secret) $secret = env('RAZORPAY_SECRET');

            $key = trim($key);
            $secret = trim($secret);
            $authHeader = 'Basic ' . base64_encode($key . ':' . $secret);
            
            // A. Verify Customer Exists for this Key
            $custCheck = Http::withHeaders(['Authorization' => $authHeader])
                            ->get("https://api.razorpay.com/v1/customers/{$customerId}");
            
            if ($custCheck->failed()) {
                $this->logToFile("ERROR: PRE_CHECK_FAIL: Customer {$customerId} invalid. " . $custCheck->body());
                return [
                    "success" => false, 
                    "message" => "Validation Failed: The Razorpay Customer ID linked to this user does not exist or belongs to a different API Key. Please Re-register Auto-Recharge."
                ];
            }

            // B. Verify Token Exists/Is Active
            // Correct endpoint: /customers/{cust_id}/tokens/{token_id}
            $tokenCheck = Http::withHeaders(['Authorization' => $authHeader])
                             ->get("https://api.razorpay.com/v1/customers/{$customerId}/tokens/{$tokenId}");

            if ($tokenCheck->failed()) {
                 $this->logToFile("ERROR: PRE_CHECK_FAIL: Token {$tokenId} invalid or not found. " . $tokenCheck->body());
                 return [
                    "success" => false, 
                    "message" => "Validation Failed: The Saved Mandate Token could not be found or is inactive. Please Re-register Auto-Recharge."
                ];
            }
            
            $tokenData = $tokenCheck->json();
            $this->logToFile("DEBUG: Token Details: " . json_encode($tokenData));

            // 3. Create Recurring Payment (Using standard /payments endpoint)
            $url = 'https://api.razorpay.com/v1/payments';
            
            $postData = [
                "email"       => $user->email,
                "contact"     => $user->mobile,
                "amount"      => $amountPaise,
                "currency"    => "INR",
                "order_id"    => $order["id"],
                "customer_id" => $customerId,
                "token"       => $tokenId,
                "recurring"   => 1,
                "description" => "Wallet Auto-Recharge (Manual)",
                "notes"       => [
                    "type"      => "auto_recharge",
                    "client_id" => $clientId,
                    "user_id"   => $user->id
                ]
            ];
            
            $this->logToFile("DEBUG: Payment Payload: " . json_encode($postData));

            $response = Http::withHeaders([
                'Authorization' => $authHeader
            ])->post($url, $postData);

            if ($response->status() == 401) {
                // Should not happen if pre-checks pass, but good safety
                $this->logToFile("ERROR: AUTO_RECHARGE_TRIGGER_HTTP_ERROR (401) after pre-check.");
                $status = $tokenData['status'] ?? 'unknown';
                return [
                    "success" => false,
                    "message" => "Razorpay Auth Failed: Token Status is '$status'. Please Disable and Re-Enable Auto-Recharge."
                ];
            }

            if ($response->failed()) {
                $errorMsg = $response->body();
                $this->logToFile("ERROR: AUTO_RECHARGE_TRIGGER_HTTP_ERROR (Status: " . $response->status() . ") - " . $errorMsg);
                throw new \Exception("Razorpay Recurring Payment Failed: " . $errorMsg);
            }

            $payment = $response->json();

            $this->logToFile("AUTO_RECHARGE_TRIGGER: payment_created - " . json_encode($payment));

            return [
                "success" => true,
                "payment_id" => $payment["razorpay_payment_id"],
                "order_id" => $order["id"],
                "status" => "initiated"
            ];
        } catch (\Exception $e) {
            $this->logToFile("ERROR: AUTO_RECHARGE_TRIGGER_ERROR - Message: {$e->getMessage()}");
            return [
                "success" => false,
                "message" => $e->getMessage()
            ];
        }
    }

    /**
     * ------------------------------------------------------------
     * SEND RECHARGE EMAIL (User + Admin)
     * ------------------------------------------------------------
     */
    private function sendRechargeEmail($user, $amount, $paymentId)
    {
        try {
            $currentDate = Carbon::now()->format('d M Y, h:i A');
            $subject = "Wallet Recharge Successful";

            // Send to user if email exists
            if (!empty($user->email)) {
                $userBodyContent = "
                    <div style='background: #28a745; color: white; padding: 15px; border-radius: 5px; text-align: center; margin-bottom: 20px;'>
                        <h2 style='margin: 0;'>✓ Wallet Recharged Successfully</h2>
                    </div>
                    <p style='color: #555;'>Dear {$user->first_name},</p>
                    <p style='color: #555;'>Your wallet has been recharged successfully. The amount has been credited to your account.</p>
                    <table cellpadding='8' cellspacing='0' width='100%' style='margin-top: 20px; border-collapse: collapse; border: 1px solid #ddd;'>
                        <tr style='background: #f8f8f8;'>
                            <td colspan='2' style='border-bottom: 1px solid #ddd; padding: 10px;'><strong style='color: #333; font-size: 16px;'>Transaction Details</strong></td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; width:150px; border-bottom: 1px solid #ddd;'><strong>Amount</strong></td>
                            <td style='border-bottom: 1px solid #ddd; color: #28a745; font-weight: bold; font-size: 18px;'>₹" . number_format($amount, 2) . "</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Payment ID</strong></td>
                            <td style='border-bottom: 1px solid #ddd; font-family: monospace; font-size: 12px;'>{$paymentId}</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Transaction Type</strong></td>
                            <td style='border-bottom: 1px solid #ddd;'>Wallet Recharge</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2;'><strong>Date</strong></td>
                            <td>{$currentDate}</td>
                        </tr>
                    </table>
                    <p style='margin-top: 25px; color: #555;'>You can view your current wallet balance by logging into your account.</p>
                    <p style='color: #555;'>Thank you for using our services!</p>
                ";

                $emailHtml = view('emails.razorpay.notification', [
                    'subject' => $subject,
                    'body' => $userBodyContent
                ])->render();

                send_sendgrid_mail($user->email, $subject, $emailHtml);
                $this->logToFile("RZP_RECHARGE_EMAIL_SENT_USER - Email: {$user->email}");
            }

            // Send to admin(s) - supports multiple comma-separated emails
            $adminEmails = env('ADMIN_NOTIFY_EMAIL', 'admin@example.com');
            $adminEmailList = array_map('trim', explode(',', $adminEmails));

            $adminBodyContent = "
                <div style='background: #007bff; color: white; padding: 12px; border-radius: 5px; margin-bottom: 20px;'>
                    <h2 style='margin: 0;'>🔔 Razorpay: Wallet Recharge Completed</h2>
                </div>
                <p style='color: #555;'>A wallet recharge transaction has been processed successfully.</p>
                <table cellpadding='8' cellspacing='0' width='100%' style='margin-top: 20px; border-collapse: collapse; border: 1px solid #ddd;'>
                    <tr style='background: #f8f8f8;'>
                        <td colspan='2' style='border-bottom: 1px solid #ddd; padding: 10px;'><strong style='color: #333; font-size: 16px;'>Transaction Details</strong></td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; width:150px; border-bottom: 1px solid #ddd;'><strong>Client ID</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$user->parent_id}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>User ID</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$user->id}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>User Email</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$user->email}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Amount</strong></td>
                        <td style='border-bottom: 1px solid #ddd; color: #28a745; font-weight: bold; font-size: 18px;'>₹" . number_format($amount, 2) . "</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Payment ID</strong></td>
                        <td style='border-bottom: 1px solid #ddd; font-family: monospace; font-size: 12px;'>{$paymentId}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2;'><strong>Timestamp</strong></td>
                        <td>{$currentDate}</td>
                    </tr>
                </table>
            ";

            $adminEmailHtml = view('emails.razorpay.notification', [
                'subject' => $subject,
                'body' => $adminBodyContent
            ])->render();

            foreach ($adminEmailList as $adminEmail) {
                if (!empty($adminEmail)) {
                    send_sendgrid_mail($adminEmail, $subject, $adminEmailHtml);
                }
            }
            $this->logToFile("RZP_RECHARGE_EMAIL_SENT_ADMIN - Email: {$adminEmail}");

        } catch (\Exception $e) {
            $this->logToFile("ERROR: RZP_RECHARGE_EMAIL_FAILED - Error: {$e->getMessage()}");
        }
    }

    /**
     * ------------------------------------------------------------
     * SEND SUBSCRIPTION EMAIL (User + Admin)
     * ------------------------------------------------------------
     */
    private function sendSubscriptionEmail($user, $clientPackage, $amountPaisa, $paymentId, $action)
    {
        try {
            $amount = $amountPaisa / 100;
            $packageKey = $clientPackage->package_key;
            $endDate = Carbon::parse($clientPackage->end_time)->format('Y-m-d H:i:s');
            $currentDate = Carbon::now()->format('d M Y, h:i A');
            $subject = "Subscription " . ucfirst($action) . " - Payment Successful";

            // Send to user if email exists
            if (!empty($user->email)) {
                $userBodyContent = "
                    <h2 style='color: #333;'>Subscription " . ucfirst($action) . " Successfully</h2>
                    <p style='color: #555;'>Dear {$user->first_name},</p>
                    <p style='color: #555;'>Your subscription has been <strong>{$action}</strong> successfully. Thank you for your continued trust in our services.</p>
                    <table cellpadding='8' cellspacing='0' width='100%' style='margin-top: 20px; border-collapse: collapse; border: 1px solid #ddd;'>
                        <tr style='background: #f8f8f8;'>
                            <td colspan='2' style='border-bottom: 1px solid #ddd; padding: 10px;'><strong style='color: #333; font-size: 16px;'>Subscription Details</strong></td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; width:150px; border-bottom: 1px solid #ddd;'><strong>Package</strong></td>
                            <td style='border-bottom: 1px solid #ddd;'>{$packageKey}</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Amount</strong></td>
                            <td style='border-bottom: 1px solid #ddd; color: #28a745; font-weight: bold;'>₹" . number_format($amount, 2) . "</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Payment ID</strong></td>
                            <td style='border-bottom: 1px solid #ddd; font-family: monospace; font-size: 12px;'>{$paymentId}</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Valid Until</strong></td>
                            <td style='border-bottom: 1px solid #ddd;'>{$endDate}</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2;'><strong>Date</strong></td>
                            <td>{$currentDate}</td>
                        </tr>
                    </table>
                    <p style='margin-top: 25px; color: #555;'>Your subscription is now active and will remain valid until <strong>{$endDate}</strong>.</p>
                    <p style='color: #555;'>If you have any questions, please feel free to contact our support team.</p>
                ";

                $emailHtml = view('emails.razorpay.notification', [
                    'subject' => $subject,
                    'body' => $userBodyContent
                ])->render();

                send_sendgrid_mail($user->email, $subject, $emailHtml);
                $this->logToFile("RZP_SUBSCRIPTION_EMAIL_SENT_USER - Email: {$user->email}");
            }

            // Send to admin(s) - supports multiple comma-separated emails
            $adminEmails = env('ADMIN_NOTIFY_EMAIL', 'admin@example.com');
            $adminEmailList = array_map('trim', explode(',', $adminEmails));

            $adminBodyContent = "
                <div style='background: #007bff; color: white; padding: 12px; border-radius: 5px; margin-bottom: 20px;'>
                    <h2 style='margin: 0;'>🔔 Razorpay: Subscription " . ucfirst($action) . "</h2>
                </div>
                <p style='color: #555;'>A subscription has been {$action} successfully.</p>
                <table cellpadding='8' cellspacing='0' width='100%' style='margin-top: 20px; border-collapse: collapse; border: 1px solid #ddd;'>
                    <tr style='background: #f8f8f8;'>
                        <td colspan='2' style='border-bottom: 1px solid #ddd; padding: 10px;'><strong style='color: #333; font-size: 16px;'>Subscription Details</strong></td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; width:150px; border-bottom: 1px solid #ddd;'><strong>Client ID</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$clientPackage->client_id}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>User Email</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$user->email}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Package</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$packageKey}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Amount</strong></td>
                        <td style='border-bottom: 1px solid #ddd; color: #28a745; font-weight: bold;'>₹" . number_format($amount, 2) . "</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Payment ID</strong></td>
                        <td style='border-bottom: 1px solid #ddd; font-family: monospace; font-size: 12px;'>{$paymentId}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Valid Until</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$endDate}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Action</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'><span style='background: #28a745; color: white; padding: 3px 8px; border-radius: 3px; font-size: 12px;'>" . strtoupper($action) . "</span></td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2;'><strong>Timestamp</strong></td>
                        <td>{$currentDate}</td>
                    </tr>
                </table>
            ";

            $adminEmailHtml = view('emails.razorpay.notification', [
                'subject' => $subject,
                'body' => $adminBodyContent
            ])->render();

            foreach ($adminEmailList as $adminEmail) {
                if (!empty($adminEmail)) {
                    send_sendgrid_mail($adminEmail, $subject, $adminEmailHtml);
                }
            }
            $this->logToFile("RZP_SUBSCRIPTION_EMAIL_SENT_ADMIN - Email: {$adminEmail}");

        } catch (\Exception $e) {
            $this->logToFile("ERROR: RZP_SUBSCRIPTION_EMAIL_FAILED - Error: {$e->getMessage()}");
        }
    }

    /**
     * ------------------------------------------------------------
     * SEND AUTO-RECHARGE MANDATE SETUP EMAIL (User + Admin)
     * ------------------------------------------------------------
     */
    private function sendMandateSetupEmail($user, $threshold, $amount)
    {
        try {
            $currentDate = Carbon::now()->format('d M Y, h:i A');
            $subject = "Auto-Recharge Mandate Setup Successful";

            // Send to user if email exists
            if (!empty($user->email)) {
                $userBodyContent = "
                    <div style='background: #28a745; color: white; padding: 15px; border-radius: 5px; text-align: center; margin-bottom: 20px;'>
                        <h2 style='margin: 0;'>✓ Auto-Recharge Activated</h2>
                    </div>
                    <p style='color: #555;'>Dear {$user->first_name},</p>
                    <p style='color: #555;'>Your UPI AutoPay mandate has been set up successfully for automatic wallet recharges.</p>
                    <table cellpadding='8' cellspacing='0' width='100%' style='margin-top: 20px; border-collapse: collapse; border: 1px solid #ddd;'>
                        <tr style='background: #f8f8f8;'>
                            <td colspan='2' style='border-bottom: 1px solid #ddd; padding: 10px;'><strong style='color: #333; font-size: 16px;'>Auto-Recharge Settings</strong></td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; width:200px; border-bottom: 1px solid #ddd;'><strong>Low Balance Trigger</strong></td>
                            <td style='border-bottom: 1px solid #ddd;'>₹" . number_format($threshold, 2) . "</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Recharge Amount</strong></td>
                            <td style='border-bottom: 1px solid #ddd; color: #28a745; font-weight: bold;'>₹" . number_format($amount, 2) . "</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2;'><strong>Setup Date</strong></td>
                            <td>{$currentDate}</td>
                        </tr>
                    </table>
                    <div style='background: #e7f3ff; border-left: 4px solid #007bff; padding: 15px; margin-top: 20px; border-radius: 3px;'>
                        <p style='margin: 0; color: #004085;'><strong>💡 How it works:</strong><br>
                        When your wallet balance falls below ₹" . number_format($threshold, 2) . ", we will automatically debit ₹" . number_format($amount, 2) . " from your saved payment method and credit it to your wallet.</p>
                    </div>
                    <p style='margin-top: 25px; color: #555;'>You can manage or disable auto-recharge anytime from your account settings.</p>
                    <p style='color: #555;'>Thank you for using our services!</p>
                ";

                $emailHtml = view('emails.razorpay.notification', [
                    'subject' => $subject,
                    'body' => $userBodyContent
                ])->render();

                send_sendgrid_mail($user->email, $subject, $emailHtml);
                $this->logToFile("RZP_MANDATE_EMAIL_SENT_USER - Email: {$user->email}");
            }

            // Send to admin(s) - supports multiple comma-separated emails
            $adminEmails = env('ADMIN_NOTIFY_EMAIL', 'admin@example.com');
            $adminEmailList = array_map('trim', explode(',', $adminEmails));

            $adminBodyContent = "
                <div style='background: #007bff; color: white; padding: 12px; border-radius: 5px; margin-bottom: 20px;'>
                    <h2 style='margin: 0;'>🔔 Razorpay: Auto-Recharge Mandate Setup</h2>
                </div>
                <p style='color: #555;'>A user has successfully set up UPI AutoPay for automatic wallet recharges.</p>
                <table cellpadding='8' cellspacing='0' width='100%' style='margin-top: 20px; border-collapse: collapse; border: 1px solid #ddd;'>
                    <tr style='background: #f8f8f8;'>
                        <td colspan='2' style='border-bottom: 1px solid #ddd; padding: 10px;'><strong style='color: #333; font-size: 16px;'>Mandate Details</strong></td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; width:200px; border-bottom: 1px solid #ddd;'><strong>Client ID</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$user->parent_id}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>User ID</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$user->id}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>User Email</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>{$user->email}</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Low Balance Trigger</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>₹" . number_format($threshold, 2) . "</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2; border-bottom: 1px solid #ddd;'><strong>Recharge Amount</strong></td>
                        <td style='border-bottom: 1px solid #ddd; color: #28a745; font-weight: bold;'>₹" . number_format($amount, 2) . "</td>
                    </tr>
                    <tr>
                        <td style='background: #f2f2f2;'><strong>Timestamp</strong></td>
                        <td>{$currentDate}</td>
                    </tr>
                </table>
            ";

            $adminEmailHtml = view('emails.razorpay.notification', [
                'subject' => $subject,
                'body' => $adminBodyContent
            ])->render();

            foreach ($adminEmailList as $adminEmail) {
                if (!empty($adminEmail)) {
                    send_sendgrid_mail($adminEmail, $subject, $adminEmailHtml);
                }
            }
            $this->logToFile("RZP_MANDATE_EMAIL_SENT_ADMIN - Email: {$adminEmail}");

        } catch (\Exception $e) {
            $this->logToFile("ERROR: RZP_MANDATE_EMAIL_FAILED - Error: {$e->getMessage()}");
        }
    }

    /**
     * ------------------------------------------------------------
     * LOG TO FILE (File-based logging for Razorpay transactions)
     * ------------------------------------------------------------
     */
    private function logToFile($message)
    {
        $logFile = storage_path('app/razorpay_transactions.log');
        $timestamp = date('Y-m-d H:i:s');
        $logMessage = "[{$timestamp}] {$message}\n";
        file_put_contents($logFile, $logMessage, FILE_APPEND);
    }
}
