<?php

namespace App\Http\Controllers;

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

class RazorpayWebhookController extends Controller
{
    protected function api()
    {
        return new Api(env('RAZORPAY_KEY'), env('RAZORPAY_SECRET'));
    }
    /**
     * ------------------------------------------------------
     * MAIN WEBHOOK HANDLER
     * - Verifies Razorpay webhook signature before processing
     * - Acts as BACKUP to frontend verifySubscription()
     * ------------------------------------------------------
     */
    public function handle(Request $r)
    {
        $this->logToFile("RZP_WEBHOOK_RECEIVED - " . json_encode($r->all()));

        // ── WEBHOOK SIGNATURE VERIFICATION ──
        $webhookSecret = env('RAZORPAY_WEBHOOK_SECRET');

        if ($webhookSecret) {
            $expectedSignature = $r->header('X-Razorpay-Signature');
            $rawBody = $r->getContent();

            if (!$expectedSignature) {
                $this->logToFile("ERROR: RZP_WEBHOOK_MISSING_SIGNATURE_HEADER");
                return response()->json(['status' => 'unauthorized'], 401);
            }

            $generatedSignature = hash_hmac('sha256', $rawBody, $webhookSecret);

            if (!hash_equals($generatedSignature, $expectedSignature)) {
                $this->logToFile("ERROR: RZP_WEBHOOK_INVALID_SIGNATURE - Expected: {$expectedSignature}");
                return response()->json(['status' => 'unauthorized'], 401);
            }

            $this->logToFile("RZP_WEBHOOK_SIGNATURE_VERIFIED");
        } else {
            $this->logToFile("WARNING: RZP_WEBHOOK_SECRET_NOT_SET - Skipping signature verification");
        }

        $event = $r->event ?? null;
        $payload = $r->payload ?? [];

        if (!$event) {
            $this->logToFile("ERROR: RZP_WEBHOOK_ERROR: Missing event");
            return response()->json(['status' => 'ignored'], 200);
        }

        switch ($event) {

            case "subscription.charged":
                return $this->handleSubscriptionCharged($payload);

            case "payment.captured":
                return $this->handlePaymentCaptured($payload);

            case "subscription.failed":
                $this->logToFile("WARNING: RZP_SUB_FAILED - " . json_encode($payload));
                return response()->json(['status' => 'logged'], 200);

            case "invoice.paid":
                return $this->handleInvoicePaid($payload);

            case "invoice.partially_paid":
                $this->logToFile("WARNING: RZP_WEBHOOK_PARTIAL_PAYMENT - " . json_encode($payload));
                return response()->json(['status' => 'logged'], 200);

            default:
                $this->logToFile("RZP_WEBHOOK_IGNORED_EVENT - Event: {$event}");
                return response()->json(['status' => 'ignored'], 200);
        }
    }

    /**
     * ------------------------------------------------------
     * subscription.charged
     * - BACKUP handler: only creates package if verifySubscription() didn't already
     * - Idempotent: checks psp_reference before any write
     * - For renewals (paid_count > 1): always updates existing package dates
     * ------------------------------------------------------
     */
    private function handleSubscriptionCharged($payload)
    {
        $this->logToFile("RZP_SUB_CHARGED_START - " . json_encode($payload));

        if (
            !isset($payload['subscription']['entity']) ||
            !isset($payload['payment']['entity'])
        ) {

            $this->logToFile("ERROR: RZP_SUB_CHARGED_INVALID_PAYLOAD");
            return response()->json(['status' => 'ignored'], 200);
        }

        $sub = $payload['subscription']['entity'];
        $pay = $payload['payment']['entity'];
        $notes = $sub['notes'] ?? [];

        $subscriptionId = $sub['id'];
        $paymentId = $pay['id'];
        $amountPaisa = $pay['amount'];
        $currentStart = Carbon::createFromTimestamp($sub['current_start']);
        $currentEnd = Carbon::createFromTimestamp($sub['current_end']);
        $planId = $sub['plan_id'];

        $this->logToFile("RZP_SUB_CHARGED_DATA - Subscription ID: {$subscriptionId}, Payment ID: {$paymentId}, Amount: {$amountPaisa}, Plan ID: {$planId}, Notes Type: " . ($notes['type'] ?? 'none'));

        // Check if auto-recharge
        if (isset($notes['type']) && $notes['type'] === 'auto_recharge') {
            return $this->handleAutoRechargeCharged($payload);
        }

        // ── IDEMPOTENCY: Check if this payment_id was already processed ──
        $alreadyHandled = ClientPackage::where('psp_reference', $paymentId)->first();

        if ($alreadyHandled) {
            // Payment was already processed (by verifySubscription or a previous webhook delivery).
            // For renewals, still update the end dates from the authoritative webhook timestamps.
            $alreadyHandled->end_time = $currentEnd;
            $alreadyHandled->expiry_time = $currentEnd;
            if ($sub['current_start']) {
                $alreadyHandled->renewed_at = $currentStart;
            }
            $alreadyHandled->save();

            wallet::updateSubscriptionStatus($alreadyHandled->client_id);

            $this->logToFile("RZP_SUB_CHARGED_IDEMPOTENT_HIT - psp_reference: {$paymentId}, updated end_time to webhook timestamps");
            return response()->json(['status' => 'already_processed'], 200);
        }

        // ── Resolve package from plan_id ──
        $package = Package::where('razorpay_plan_id', $planId)->first();

        if (!$package) {
            $this->logToFile("ERROR: RZP_SUB_CHARGED_PLAN_NOT_FOUND - Plan ID: {$planId}");
            return response()->json(['status' => 'ignored'], 200);
        }

        $packageKey = $package->key;

        // ── Find existing client package for this subscription ──
        $clientPackage = ClientPackage::where('razorpay_subscription_id', $subscriptionId)
            ->orderBy('id', 'desc')
            ->first();

        if ($clientPackage) {
            $this->logToFile("RZP_SUB_CHARGED_UPDATE_EXISTING_PACKAGE");

            $clientPackage->renewed_at = $currentStart;
            $clientPackage->end_time = $currentEnd;
            $clientPackage->expiry_time = $currentEnd;
            $clientPackage->payment_time = Carbon::now();
            $clientPackage->payment_cent_amount = $amountPaisa;
            $clientPackage->psp_reference = $paymentId;
            $clientPackage->save();

            $this->sendPackageUpdateEmail($clientPackage, $amountPaisa, $paymentId, 'renewed');
            wallet::updateSubscriptionStatus($clientPackage->client_id);

            return response()->json(['status' => 'package_updated'], 200);
        }

        // ── No existing record: create new (fallback if verifySubscription() missed) ──
        $this->logToFile("RZP_SUB_CHARGED_CREATE_NEW_PACKAGE");

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

        if (!$order) {
            $this->logToFile("ERROR: RZP_SUB_CHARGED_NO_ORDER_FOUND");
            return response()->json(['status' => 'ignored'], 200);
        }

        $clientId = $order->client_id;

        // Mark order as success if it was still initiated/failed
        if ($order->status !== 'success') {
            $order->status = 'success';
            $order->save();
        }

        $cp = new ClientPackage();
        $cp->client_id = $clientId;
        $cp->package_key = $packageKey;
        $cp->quantity = 1;
        $cp->start_time = $currentStart;
        $cp->end_time = $currentEnd;
        $cp->expiry_time = $currentEnd;
        $cp->billed = 'monthly';
        $cp->payment_cent_amount = $amountPaisa;
        $cp->payment_time = Carbon::now();
        $cp->payment_method = 'razorpay';
        $cp->psp_reference = $paymentId;
        $cp->razorpay_subscription_id = $subscriptionId;
        $cp->razorpay_plan_id = $planId;
        $cp->save();

        $this->logToFile("RZP_SUB_CHARGED_PACKAGE_CREATED - Client Package ID: {$cp->id}");

        $this->sendPackageUpdateEmail($cp, $amountPaisa, $paymentId, 'created');
        wallet::updateSubscriptionStatus($clientId);

        return response()->json(['status' => 'package_created'], 200);
    }

    /**
     * ------------------------------------------------------------
     * AUTO-RECHARGE CHARGED HANDLER
     * Triggered when notes[type] == auto_recharge
     * ------------------------------------------------------------
     */
    private function handleAutoRechargeCharged($payload)
    {
        $this->logToFile("RZP_AUTO_CHARGED_START - " . json_encode($payload));

        $sub = $payload['subscription']['entity'];
        $pay = $payload['payment']['entity'];
        $notes = $sub['notes'] ?? [];

        $subscriptionId = $sub['id'];
        $paymentId = $pay['id'];
        $amountPaisa = $pay['amount'];

        /**
         * ------------------------------------------------------------
         * 1) Resolve user_id from notes
         * ------------------------------------------------------------
         */
        $userId = $notes['user_id'] ?? null;

        if (!$userId) {
            $this->logToFile("ERROR: RZP_AUTO_CHARGED_MISSING_USER_ID - Notes: " . json_encode($notes));
            return response()->json(['status' => 'ignored'], 200);
        }

        /**
         * ------------------------------------------------------------
         * 2) Fetch user → resolve correct client_id (parent_id)
         * ------------------------------------------------------------
         */
        $user = DB::connection("master")
            ->table("users")
            ->where("id", $userId)
            ->first();

        if (!$user) {
            $this->logToFile("ERROR: RZP_AUTO_CHARGED_USER_NOT_FOUND - User ID: {$userId}");
            return response()->json(['status' => 'ignored'], 200);
        }

        $clientId = $user->parent_id;

        if (!$clientId) {
            $this->logToFile("ERROR: RZP_AUTO_CHARGED_NO_PARENT_ID - User ID: {$userId}");
            return response()->json(['status' => 'ignored'], 200);
        }

        $amount = $amountPaisa / 100;

        $this->logToFile("RZP_AUTO_CHARGED_CLIENT_ID_RESOLVED - User ID: {$userId}, Client ID: {$clientId}, Amount: {$amount}");

        /**
         * ---------------------------------------------------
         * 3) SAVE TOKEN + CUSTOMER (MANDATE)
         * ---------------------------------------------------
         */
        $tokenId = $pay['token_id'] ?? null;
        $customerId = $pay['customer_id'] ?? null;

        if ($tokenId && $customerId) {

            DB::connection("master")
                ->table("users")
                ->where("id", $userId)
                ->update([
                    "razorpay_token_id" => $tokenId,
                    "razorpay_customer_id" => $customerId
                ]);

            $this->logToFile("RZP_AUTO_CHARGED_TOKEN_SAVED - User ID: {$userId}, Token ID: {$tokenId}, Customer ID: {$customerId}");
        }

        /**
         * ---------------------------------------------------
         * 4) CREATE/UPDATE ORDER (order_type = auto_recharge)
         * ---------------------------------------------------
         */
        $order = Order::where('gateway_subscription_id', $subscriptionId)->first();

        if (!$order) {
            $order = new Order();
            $order->client_id = $clientId;
            $order->net_amount = $amount;
            $order->gross_amount = $amount;
            $order->status = 'initiated';
            $order->payment_method = 'razorpay';
            $order->order_type = 'auto_recharge';
            $order->gateway_order_id = $paymentId;
            $order->gateway_subscription_id = $subscriptionId;
            $order->save();

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

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

        /**
         * ---------------------------------------------------
         * 5) UPDATE PAYMENT TRANSACTION
         * ---------------------------------------------------
         */
        $pt = PaymentTransaction::where('order_id', $order->id)->first();

        if (!$pt) {
            $pt = new PaymentTransaction();
            $pt->order_id = $order->id;
            $pt->payment_gateway_type = 'razorpay';
            $pt->status = 'initiated';
        }

        $pt->status = 'success';
        $pt->response = json_encode($pay);
        $pt->save();

        $this->logToFile("RZP_AUTO_CHARGED_PT_UPDATED - PT ID: {$pt->id}");

        /**
         * ---------------------------------------------------
         * 6) CREDIT WALLET
         * ---------------------------------------------------
         */
        wallet::creditCharge($amount, $clientId, 'INR');

        $this->logToFile("RZP_AUTO_CHARGED_WALLET_CREDITED - Client ID: {$clientId}, Amount: {$amount}");

        /**
         * ---------------------------------------------------
         * 7) WALLET TRANSACTION ENTRY
         * ---------------------------------------------------
         */
        $w = new walletTransaction();
        $w->setConnection("mysql_" . $clientId);
        $w->currency_code = 'INR';
        $w->amount = $amount;
        $w->transaction_type = 'credit';
        $w->transaction_reference = $paymentId;
        $w->description = 'Auto-Recharge';
        $w->save();

        $this->logToFile("RZP_AUTO_CHARGED_WALLET_TX_SAVED - Reference: {$paymentId}, Client ID: {$clientId}");

        /**
         * ---------------------------------------------------
         * 8) CLEAR AUTO-RECHARGE PENDING FLAG
         * ---------------------------------------------------
         */
        DB::connection("master")
            ->table("users")
            ->where("id", $userId)
            ->update(['auto_recharge_pending' => 0]);

        $this->logToFile("RZP_AUTO_CHARGED_PENDING_FLAG_CLEARED - User ID: {$userId}");

        // Send email notification to user and admin
        $this->sendAutoRechargeEmail($user, $amount, $paymentId, $clientId);

        return response()->json(['status' => 'auto_recharge_processed'], 200);
    }



    /**
     * ------------------------------------------------------
     * invoice.paid
     * ------------------------------------------------------
     * Backup handler (some merchants get renewals via invoice events)
     */
    private function handleInvoicePaid($payload)
    {
        $this->logToFile("RZP_INVOICE_PAID_START - " . json_encode($payload));

        if (!isset($payload['invoice']['entity'])) {
            $this->logToFile("ERROR: RZP_INVOICE_PAID_INVALID");
            return response()->json(['status' => 'ignored'], 200);
        }

        $invoice = $payload['invoice']['entity'];

        $subscriptionId = $invoice['subscription_id'] ?? null;
        $paymentId = $invoice['payment_id'] ?? null;
        $amountPaisa = $invoice['amount'];
        $periodStart = Carbon::createFromTimestamp($invoice['billing_start'] ?? $invoice['date']);
        $periodEnd = Carbon::createFromTimestamp($invoice['billing_end'] ?? ($invoice['date'] + 2592000)); // fallback 30d

        if (!$subscriptionId) {
            $this->logToFile("ERROR: RZP_INVOICE_PAID_NO_SUB_ID");
            return response()->json(['status' => 'ignored'], 200);
        }

        // Get package
        $order = Order::where('gateway_subscription_id', $subscriptionId)->first();
        if (!$order) {
            $this->logToFile("ERROR: RZP_INVOICE_PAID_NO_ORDER");
            return response()->json(['status' => 'ignored'], 200);
        }

        $package = Package::where('razorpay_plan_id', $order->razorpay_plan_id ?? null)->first();
        if (!$package) {
            $this->logToFile("ERROR: RZP_INVOICE_PAID_PACKAGE_NOT_FOUND");
            return response()->json(['status' => 'ignored'], 200);
        }

        // Update package
        $cp = ClientPackage::where('razorpay_subscription_id', $subscriptionId)
            ->orderBy('id', 'desc')
            ->first();

        if ($cp) {
            $cp->start_time = $periodStart;
            $cp->end_time = $periodEnd;
            $cp->expiry_time = $periodEnd;
            $cp->payment_cent_amount = $amountPaisa;
            $cp->payment_time = Carbon::now();
            $cp->psp_reference = $paymentId;
            $cp->save();

            // Send email notification to user and admin
            $this->sendPackageUpdateEmail($cp, $amountPaisa, $paymentId, 'renewed');

            // SYNC WALLET STATUS
            wallet::updateSubscriptionStatus($cp->client_id);

            return response()->json(['status' => 'package_updated'], 200);
        }

        return response()->json(['status' => 'ignored'], 200);
    }

    /**
     * ------------------------------------------------------------
     * SEND PACKAGE UPDATE EMAIL (User + Admin)
     * ------------------------------------------------------------
     */
    private function sendPackageUpdateEmail($clientPackage, $amountPaisa, $paymentId, $action)
    {
        try {
            // Get user details
            $user = DB::connection("master")
                ->table("users")
                ->where("parent_id", $clientPackage->client_id)
                ->where("role", "admin")
                ->first();

            $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');

            // Email subject
            $subject = "Subscription " . ucfirst($action) . " - Payment Successful";

            // Send to user if email exists
            if ($user && !empty($user->email)) {
                $userBodyContent = "
                    <h2 style='color: #333;'>Subscription " . ucfirst($action) . " Successfully</h2>
                    <p style='color: #555;'>Dear Customer,</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;'>Transaction 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 or concerns, 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_WEBHOOK_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;'>🔔 Webhook Event: Subscription " . ucfirst($action) . "</h2>
                </div>
                <p style='color: #555;'>A subscription webhook event 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;'>{$clientPackage->client_id}</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; border-bottom: 1px solid #ddd;'><strong>User Email</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'>" . ($user->email ?? 'N/A') . "</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_WEBHOOK_EMAIL_SENT_ADMIN - Email: {$adminEmail}");

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

    /**
     * ------------------------------------------------------------
     * SEND AUTO-RECHARGE EMAIL (User + Admin)
     * ------------------------------------------------------------
     */
    private function sendAutoRechargeEmail($user, $amount, $paymentId, $clientId)
    {
        try {
            $currentDate = Carbon::now()->format('d M Y, h:i A');

            // Email subject
            $subject = "Auto-Recharge Successful - Wallet Credited";

            // 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 Successful</h2>
                    </div>
                    <p style='color: #555;'>Dear Customer,</p>
                    <p style='color: #555;'>Your wallet has been auto-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;'>Auto-Recharge</td>
                        </tr>
                        <tr>
                            <td style='background: #f2f2f2;'><strong>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>💡 What is Auto-Recharge?</strong><br>Auto-Recharge automatically adds funds to your wallet when your balance is low, ensuring uninterrupted service.</p>
                    </div>
                    <p style='margin-top: 25px; color: #555;'>You can view your current wallet balance by logging into your account.</p>
                    <p style='color: #555;'>If you have any questions or concerns, 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_WEBHOOK_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;'>🔔 Webhook Event: Auto-Recharge Processed</h2>
                </div>
                <p style='color: #555;'>An auto-recharge webhook event has been processed successfully. Wallet has been credited.</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;'>{$clientId}</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; border-bottom: 1px solid #ddd;'><strong>Transaction Type</strong></td>
                        <td style='border-bottom: 1px solid #ddd;'><span style='background: #28a745; color: white; padding: 3px 8px; border-radius: 3px; font-size: 12px;'>AUTO-RECHARGE</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_WEBHOOK_EMAIL_SENT_ADMIN - Email: {$adminEmail}");

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

    /**
     * ----------------------------------------------------------------------------
     * payment.captured HANDLER (Recurring Payments)
     * ----------------------------------------------------------------------------
     */
    private function handlePaymentCaptured($payload)
    {
        $this->logToFile("RZP_PAYMENT_CAPTURED_START - " . json_encode($payload));

        $payment = $payload['payment']['entity'];
        $notes = $payment['notes'] ?? [];

        // Check if this is an auto-recharge payment
        if (($notes['type'] ?? '') !== 'auto_recharge') {
            $this->logToFile("RZP_PAYMENT_CAPTURED_IGNORED - Not auto_recharge");
            return response()->json(['status' => 'ignored'], 200);
        }

        $paymentId = $payment['id'];
        $amountPaisa = $payment['amount'];
        $orderId = $payment['order_id'];
        $clientId = $notes['client_id'] ?? null;
        $userId = $notes['user_id'] ?? null;

        if (!$clientId || !$userId) {
            $this->logToFile("ERROR: RZP_PAYMENT_CAPTURED_MISSING_DATA - Notes: " . json_encode($notes));
            return response()->json(['status' => 'ignored'], 200);
        }

        $amount = $amountPaisa / 100;

        /**
         * ---------------------------------------------------
         * 1) UPDATE USER TOKENS (Mandate Refresh)
         * ---------------------------------------------------
         */
        $tokenId = $payment['token_id'] ?? null;
        $customerId = $payment['customer_id'] ?? null;

        if ($tokenId && $customerId) {
            DB::connection("master")
                ->table("users")
                ->where("id", $userId)
                ->update([
                    "razorpay_token_id" => $tokenId,
                    "razorpay_customer_id" => $customerId
                ]);
            $this->logToFile("RZP_PAYMENT_CAPTURED_TOKEN_SAVED");
        }

        /**
         * ---------------------------------------------------
         * 2) CREATE/UPDATE ORDER
         * ---------------------------------------------------
         */
        // Try to find order by gateway_order_id first
        $order = Order::where('gateway_order_id', $orderId)->first();

        if (!$order) {
            $order = new Order();
            $order->client_id = $clientId;
            $order->net_amount = $amount;
            $order->gross_amount = $amount;
            $order->status = 'initiated';
            $order->payment_method = 'razorpay';
            $order->order_type = 'auto_recharge';
            $order->gateway_order_id = $orderId;
            $order->save();
        }

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

        /**
         * ---------------------------------------------------
         * 3) UPDATE PAYMENT TRANSACTION
         * ---------------------------------------------------
         */
        $pt = PaymentTransaction::where('order_id', $order->id)->first();

        if (!$pt) {
            $pt = new PaymentTransaction();
            $pt->order_id = $order->id;
            $pt->payment_gateway_type = 'razorpay';
            $pt->status = 'initiated';
        }

        $pt->status = 'success';
        $pt->response = json_encode($payment);
        $pt->save();

        /**
         * ---------------------------------------------------
         * 4) CREDIT WALLET
         * ---------------------------------------------------
         */
        wallet::creditCharge($amount, $clientId, 'INR');
        $this->logToFile("RZP_PAYMENT_CAPTURED_WALLET_CREDITED - Amount: {$amount}");

        /**
         * ---------------------------------------------------
         * 5) WALLET TRANSACTION ENTRY
         * ---------------------------------------------------
         */
        $w = new walletTransaction();
        $w->setConnection("mysql_" . $clientId);
        $w->currency_code = 'INR';
        $w->amount = $amount;
        $w->transaction_type = 'credit';
        $w->transaction_reference = $paymentId;
        $w->description = 'Auto-Recharge (Recurring)';
        $w->save();

        /**
         * ---------------------------------------------------
         * 6) CLEAR PENDING FLAG
         * ---------------------------------------------------
         */
        DB::connection("master")
            ->table("users")
            ->where("id", $userId)
            ->update(['auto_recharge_pending' => 0]);

        // Send email
        $user = DB::connection("master")->table("users")->where("id", $userId)->first();
        if ($user) {
            $this->sendAutoRechargeEmail($user, $amount, $paymentId, $clientId);
        }

        return response()->json(['status' => 'auto_recharge_processed'], 200);
    }

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

