@extends('layouts.app')
@section('title', 'Recharge')
@section('content')
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.20/dist/sweetalert2.min.css">
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>

    <style>
        .page-wrapper {
            padding: 20px;
        }

        .card-box {
            background: #ffffff;
            border-radius: 14px;
            padding: 22px;
            border: 1px solid #e5e7eb;
            margin-bottom: 24px;
            box-shadow: 0 3px 16px rgba(0, 0, 0, 0.06);
        }

        .wallet-box {
            background: #f8fbff;
            border: 1px solid #d7e3ff;
            border-radius: 14px;
            padding: 30px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .wallet-amount {
            font-size: 44px;
            font-weight: 700;
            color: #089447;
            margin-top: 5px;
            letter-spacing: -1px;
        }

        .section-title {
            font-size: 18px;
            font-weight: 600;
        }

        .recharge-input-group .input-group-text {
            font-size: 18px;
            font-weight: bold;
        }

        .recharge-input-group input {
            font-size: 18px;
            padding: 14px 12px;
        }

        .btn-primary {
            padding: 12px 20px;
            font-size: 16px;
            font-weight: 600;
            transition: .2s;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.16);
        }

        .switch-toggle {
            position: relative;
            width: 50px;
            height: 26px;
            display: inline-block;
        }

        .switch-toggle input {
            display: none;
        }

        .switch-toggle .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #d1d5db;
            border-radius: 34px;
            transition: 0.3s;
        }

        .switch-toggle .slider:before {
            position: absolute;
            content: "";
            height: 20px;
            width: 20px;
            left: 3px;
            bottom: 3px;
            background: #fff;
            border-radius: 50%;
            transition: 0.3s;
        }

        .switch-toggle input:checked+.slider {
            background: #089447;
        }

        .switch-toggle input:checked+.slider:before {
            transform: translateX(24px);
        }

        @media (max-width: 768px) {
            .wallet-box {
                flex-direction: column;
                align-items: flex-start;
                gap: 20px;
            }

            .btn-primary {
                width: 100%;
            }
        }
    </style>

    <div class="page-wrapper">
        <div class="page-header d-flex justify-content-between align-items-center mb-3">
            <div class="d-flex align-items-center gap-2">
                <a href="{{ url()->previous() }}" class="btn btn-light px-2 py-1">
                    <i class="ti ti-arrow-narrow-left me-1"></i>
                </a>
                <h4 class="mb-0">Recharge Account</h4>
            </div>

            <div class="head-icons">
                <a href="" data-bs-toggle="tooltip" title="Refresh"><i class="ti ti-refresh-dot"></i></a>
                <a href="javascript:void(0)" id="collapse-header" data-bs-toggle="tooltip" title="Collapse">
                    <i class="ti ti-chevrons-up"></i>
                </a>
            </div>
        </div>

        <div class="card-box">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <span class="section-title">Wallet</span>
                <a href="{{ url('wallet/transactions') }}" class="btn btn-outline-primary">View Transactions</a>
            </div>

            <form id="rechargeForm" method="post">
                @csrf
                <input type="hidden" name="request_type" value="recharge">

                <!-- Wallet Balance -->
                <div class="wallet-box mb-4">
                    <div>
                        <div class="text-muted">Current Wallet Balance</div>
                        <div class="wallet-amount">₹{{ number_format($wallet->amount ?? 0, 2) }}</div>
                        <div class="text-muted small mt-1">Available for use</div>
                    </div>
                    <i class="fa fa-wallet" style="font-size:40px;color:#4b5563;"></i>
                </div>

                <!-- Auto Recharge -->
                @include('billing.razorpay-auto-recharge-section')

                <!-- Recharge Amount -->
                <div class="mb-3 col-12 d-flex justify-content-end align-items-center">
                    <div class="col-6">
                        <label class="form-label">Recharge Amount *</label>
                        <div class="input-group recharge-input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" class="form-control" name="amount" id="amount"
                                placeholder="Enter amount" required min="1" step="1"
                                oninput="this.value = this.value.replace(/^0+/, '')">
                        </div>
                    </div>
                </div>

                <div class="text-end mt-3">
                    <button type="submit" class="btn btn-primary">Recharge Now</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.20/dist/sweetalert2.all.min.js"></script>

    <script>
        $(function() {

            console.log("PAGE LOADED: Recharge Page Ready.");

            $("#rechargeForm").submit(async function(e) {
                e.preventDefault();
                console.log("STEP 1: Form Submitted");

                const amount = parseFloat($('#amount').val());

                if (!amount || amount < 1) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Amount',
                        text: 'Minimum recharge amount is ₹1.'
                    });
                    return;
                }

                Swal.fire({
                    title: 'Processing...',
                    text: 'Saving settings & processing recharge. Please wait.',
                    allowOutsideClick: false,
                    didOpen: () => Swal.showLoading()
                });

                try {
                    console.log("STEP 4: Creating Razorpay Order…");

                    const orderRes = await fetch("{{ url('/razorpay-create-order-recharge') }}", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            "X-CSRF-TOKEN": '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({
                            amount
                        })
                    });

                    const orderData = await orderRes.json();
                    console.log("Order Response:", orderData);

                    if (!orderData.success) {
                        Swal.close();
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: orderData.message || "Failed to create payment order."
                        });
                        return;
                    }

                    Swal.close();

                    console.log("STEP 5: Opening Razorpay Popup…");

                    const rzp = new Razorpay({
                        key: orderData.key,
                        amount: orderData.amount * 100,
                        currency: "INR",
                        order_id: orderData.order_id,
                        name: "Wallet Recharge",
                        description: "Recharge Wallet Balance",

                        handler: async function(resp) {
                            console.log("STEP 6: Payment success", resp);

                            Swal.fire({
                                title: "Verifying Payment…",
                                allowOutsideClick: false,
                                didOpen: () => Swal.showLoading()
                            });

                            console.log("STEP 7: Sending verification request…");

                            const verifyRes = await fetch(
                                "{{ url('/razorpay-verify-order-recharge') }}", {
                                    method: "POST",
                                    headers: {
                                        "Content-Type": "application/json",
                                        "X-CSRF-TOKEN": '{{ csrf_token() }}'
                                    },
                                    body: JSON.stringify({
                                        razorpay_order_id: resp
                                            .razorpay_order_id,
                                        razorpay_payment_id: resp
                                            .razorpay_payment_id,
                                        razorpay_signature: resp
                                            .razorpay_signature,
                                        amount: amount
                                    })
                                });

                            const verifyData = await verifyRes.json();
                            console.log("Verification Response:", verifyData);

                            if (verifyData.success) {
                                let timer = 5;

                                Swal.fire({
                                    icon: 'success',
                                    title: 'Success!',
                                    html: `Recharge successful. Redirecting in <b id="timer">${timer}</b> seconds…`,
                                    showConfirmButton: false,
                                    didOpen: () => {
                                        const interval = setInterval(() => {
                                            timer--;
                                            if (timer <= 0) {
                                                clearInterval(interval);
                                                window.location.href =
                                                    "/wallet/transactions";
                                            }
                                            $('#timer').text(timer);
                                        }, 1000);
                                    }
                                });

                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Verification Failed',
                                    text: verifyData.message ||
                                        "Could not verify payment."
                                });
                            }
                        }
                    });

                    rzp.on("payment.failed", function(err) {
                        console.error("Razorpay Payment Failed:", err.error);
                        Swal.fire({
                            icon: "error",
                            title: "Payment Failed",
                            text: err.error.description ||
                                "Payment could not be completed."
                        });
                    });

                    rzp.open();

                } catch (error) {
                    console.error("ERROR:", error);
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to process recharge.'
                    });
                }
            });
        });
    </script>
@endsection
