@extends('layouts.front')

@section('content')
@php
    $upiId = '8619586477-2@ybl';
    $upiLabel = 'Wallet Recharge';
    $upiLink = 'upi://pay?pa='.$upiId.'&am='.number_format($amt, 2, '.', '').'&tn='.rawurlencode($upiLabel);
@endphp
<div class="jel-portal-page">
    @include('front.partials.flash-messages')

    <section class="jel-wallet-page">
        <article class="jel-wallet-card">
            <span class="jel-portal-kicker">Wallet Recharge</span>
            <h1>Pay with QR and submit transaction proof.</h1>
            <p>UPI QR scan karke payment complete kijiye, phir transaction ID aur screenshot upload karke recharge request bhejiye.</p>

            <div class="jel-wallet-proof-grid">
                <section class="jel-qr-card">
                    <div class="jel-result-summary-grid">
                        <article>
                            <span>Chosen Amount</span>
                            <strong>&#8377;{{ number_format($amt, 2) }}</strong>
                        </article>
                        <article>
                            <span>Current Wallet</span>
                            <strong>&#8377;{{ number_format((float) $walletamt, 2) }}</strong>
                        </article>
                    </div>

                    <div class="jel-wallet-proof-preview">
                        <img id="walletQrImage" src="{{ asset('public/frontend/images/logo.png') }}" alt="Wallet recharge QR">
                    </div>

                    <p class="jel-wallet-note">UPI ID: <strong>{{ $upiId }}</strong></p>
                    <div class="jel-code-actions jel-wallet-quick-actions">
                        <a class="jel-portal-button jel-portal-button-secondary" id="walletOpenUpi" href="{{ $upiLink }}">Open UPI App</a>
                        <button class="jel-portal-button jel-portal-button-muted" id="walletCopyUpi" type="button">Copy UPI ID</button>
                    </div>
                    <p class="jel-wallet-helper" id="walletQrFallback" hidden>
                        Agar QR load na ho to UPI ID copy karke manual payment complete kijiye.
                    </p>
                    <div class="jel-wallet-countdown" id="walletCountdown">10:00</div>
                </section>

                <section class="jel-form-panel jel-wallet-proof-card">
                    <div class="jel-form-panel-head">
                        <div>
                            <h2>Submit Payment Proof</h2>
                            <p>Screenshot upload kijiye aur payment transaction ID enter kijiye.</p>
                        </div>
                    </div>

                    <form class="jel-portal-form" action="{{ route('walletamountsave') }}" method="post">
                        @csrf
                        <input type="hidden" name="photoid" id="photoid" value="{{ old('photoid') }}">
                        <input type="hidden" name="rechargeamt" value="{{ $amt }}">

                        <div class="jel-wallet-proof-preview jel-wallet-proof-proofbox">
                            <img id="paymentProofPreview" src="{{ asset('public/frontend/images/logo.png') }}" alt="Payment proof preview">
                        </div>

                        <div id="walletUploadStatus" class="jel-upload-loading" hidden></div>

                        <div class="jel-profile-photo-actions">
                            <button class="jel-portal-button jel-portal-button-secondary" id="walletUploadTrigger" type="button">Upload Screenshot</button>
                        </div>

                        <label class="jel-portal-field">
                            <span>Transaction ID / UTR Number</span>
                            <input type="text" name="transctionid" id="transctionid" value="{{ old('transctionid') }}" maxlength="40" placeholder="Enter transaction reference" required>
                        </label>

                        <div class="jel-code-actions">
                            <button class="jel-portal-button" id="submitbuttinseciton" type="submit">Submit Recharge</button>
                            <a class="jel-portal-button jel-portal-button-muted" href="{{ route('walletrecharge') }}">Back</a>
                        </div>
                    </form>
                </section>
            </div>
        </article>
    </section>

    <form id="walletUploadForm" class="d-none" action="{{ route('student.upload.attachment') }}" method="post" enctype="multipart/form-data">
        @csrf
        <input name="userImage" id="newuploaed" type="file" accept="image/png, image/gif, image/jpeg, image/webp">
        <input type="hidden" name="purpose" value="wallet">
    </form>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const qrImage = document.getElementById('walletQrImage');
    const countdownNode = document.getElementById('walletCountdown');
    const openUpiButton = document.getElementById('walletOpenUpi');
    const copyUpiButton = document.getElementById('walletCopyUpi');
    const qrFallbackNode = document.getElementById('walletQrFallback');
    const uploadTrigger = document.getElementById('walletUploadTrigger');
    const fileInput = document.getElementById('newuploaed');
    const uploadForm = document.getElementById('walletUploadForm');
    const uploadStatus = document.getElementById('walletUploadStatus');
    const photoIdField = document.getElementById('photoid');
    const proofPreview = document.getElementById('paymentProofPreview');
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    const upiId = @json($upiId);
    const upiLink = @json($upiLink);

    if (qrImage) {
        qrImage.addEventListener('error', function () {
            if (qrFallbackNode) {
                qrFallbackNode.hidden = false;
            }
        });

        qrImage.src = 'https://api.qrserver.com/v1/create-qr-code/?size=260x260&data=' + encodeURIComponent(upiLink);
    }

    if (openUpiButton) {
        openUpiButton.setAttribute('href', upiLink);
    }

    if (copyUpiButton) {
        copyUpiButton.addEventListener('click', async function () {
            try {
                await navigator.clipboard.writeText(upiId);
                if (qrFallbackNode) {
                    qrFallbackNode.hidden = false;
                    qrFallbackNode.textContent = 'UPI ID copied. Ab manual payment karke screenshot upload kijiye.';
                }
            } catch (error) {
                if (qrFallbackNode) {
                    qrFallbackNode.hidden = false;
                    qrFallbackNode.textContent = 'UPI ID copy nahi ho paaya. Please manually note this UPI ID: ' + upiId;
                }
            }
        });
    }

    if (countdownNode) {
        let remainingSeconds = 10 * 60;
        const updateCountdown = function () {
            const minutes = Math.floor(remainingSeconds / 60);
            const seconds = remainingSeconds % 60;
            countdownNode.textContent = String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');

            if (remainingSeconds <= 0) {
                window.location.href = '{{ route('walletrecharge') }}';
                return;
            }

            remainingSeconds -= 1;
        };

        updateCountdown();
        window.setInterval(updateCountdown, 1000);
    }

    if (!uploadTrigger || !fileInput || !uploadForm || !uploadStatus || !photoIdField || !proofPreview || !csrfToken) {
        return;
    }

    const setStatus = function (message, state) {
        uploadStatus.hidden = !message;
        uploadStatus.textContent = message || '';
        uploadStatus.dataset.state = state || 'idle';
    };

    uploadTrigger.addEventListener('click', function () {
        fileInput.click();
    });

    fileInput.addEventListener('change', async function () {
        if (!fileInput.files || fileInput.files.length === 0) {
            return;
        }

        setStatus('Uploading payment screenshot...', 'loading');

        try {
            const response = await fetch(uploadForm.action, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest',
                },
                body: new FormData(uploadForm),
            });

            const payload = await response.json();

            if (!response.ok) {
                throw new Error(payload.message || 'Upload failed. Please try again.');
            }

            photoIdField.value = payload.attachment_id || '';

            if (payload.preview_url) {
                proofPreview.src = payload.preview_url;
            }

            setStatus('Proof uploaded. Ab transaction ID ke saath recharge submit kijiye.', 'success');
        } catch (error) {
            setStatus(error.message || 'Upload failed. Please try again.', 'error');
        }
    });
});
</script>
@endpush
@endsection
