@extends('backend.master')

@section('content')
<div class="container-fluid py-3">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-3">
        <h4 class="mb-2 mb-md-0">
            <i class="bi bi-cash-coin me-1"></i>
            Adjust Balance
        </h4>

        <a href="{{ route('admin.users.balance.index') }}" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-left me-1"></i>
            Back to list
        </a>
    </div>

    {{-- normal redirect flow এর success/error থাকলে --}}
    @if(session('success'))
        <div class="alert alert-success" id="flash-success">
            <i class="bi bi-check-circle me-1"></i>
            {{ session('success') }}
        </div>
    @endif

    @if($errors->any())
        <div class="alert alert-danger" id="flash-errors">
            <i class="bi bi-exclamation-triangle me-1"></i>
            <ul class="mb-0">
                @foreach($errors->all() as $err)
                    <li>{{ $err }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    {{-- AJAX message container --}}
    <div id="ajax-message" style="display:none;" class="alert"></div>

    {{-- User info --}}
    <div class="card mb-3">
        <div class="card-body">
            <h5 class="card-title mb-2">
                <i class="bi bi-person-circle me-1"></i>
                {{ $user->name }} (ID: {{ $user->id }})
            </h5>
            <p class="mb-1"><strong>Phone:</strong> {{ $user->phone ?? 'N/A' }}</p>
            <p class="mb-1"><strong>Email:</strong> {{ $user->email ?? 'N/A' }}</p>
            <p class="mb-1"><strong>Role:</strong> {{ ucfirst($user->role) }}</p>
            <p class="mb-1"><strong>Reward Points:</strong> {{ $user->reward_points }}</p>
            <p class="mb-0">
                <strong>Current Balance:</strong>
                <span class="fw-bold" id="current-balance">{{ number_format($user->balance, 2) }} TK</span>
            </p>
        </div>
    </div>

    {{-- Form --}}
    <div class="card">
        <div class="card-header">
            <i class="bi bi-sliders me-1"></i>
            Manual Balance Adjust (AJAX)
        </div>
        <div class="card-body">
            <form id="balance-adjust-form" method="POST" action="{{ route('admin.users.balance.update', $user) }}">
                @csrf

                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Action</label>
                        <select name="type" class="form-select" required>
                            <option value="add">Add Balance</option>
                            <option value="return">Return / Deduct</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Amount (TK)</label>
                        <input type="number" name="amount" step="0.01" min="0.01"
                               class="form-control" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Note (optional)</label>
                        <input type="text" name="note"
                               class="form-control" placeholder="e.g. bonus, manual adjust, charge">
                    </div>
                </div>

                <div class="mt-3 d-flex flex-wrap gap-2">
                    <button type="submit" class="btn btn-primary" id="submit-btn">
                        <i class="bi bi-check2-circle me-1"></i>
                        Save Change
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm"
                            onclick="document.getElementById('balance-adjust-form').reset();">
                        <i class="bi bi-arrow-counterclockwise me-1"></i>
                        Reset
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const form        = document.getElementById('balance-adjust-form');
        const msgBox      = document.getElementById('ajax-message');
        const currentBal  = document.getElementById('current-balance');
        const submitBtn   = document.getElementById('submit-btn');
        const csrfMeta    = document.querySelector('meta[name="csrf-token"]');
        const csrfToken   = csrfMeta ? csrfMeta.getAttribute('content') : '';

        if (!form) return;

        form.addEventListener('submit', function (e) {
            e.preventDefault();

            // clear old messages
            if (msgBox) {
                msgBox.style.display = 'none';
                msgBox.classList.remove('alert-success', 'alert-danger');
                msgBox.innerHTML = '';
            }

            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Processing...';

            const formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json',
                },
                body: formData
            })
            .then(async (res) => {
                const data = await res.json().catch(() => ({}));
                if (!res.ok || !data.success) {
                    let text = data.message || 'Something went wrong.';
                    showAjaxMessage(text, false);
                } else {
                    const newBalance = data.new_balance !== undefined
                        ? parseFloat(data.new_balance).toFixed(2) + ' TK'
                        : currentBal.textContent;

                    if (currentBal) {
                        currentBal.textContent = newBalance;
                    }

                    form.amount.value = '';
                    form.note.value   = '';

                    showAjaxMessage(data.message || 'Balance updated successfully.', true);
                }
            })
            .catch((err) => {
                console.error('AJAX error:', err);
                showAjaxMessage('Network error. Please try again.', false);
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Save Change';
            });
        });

        function showAjaxMessage(text, isSuccess) {
            if (!msgBox) return;
            msgBox.style.display = 'block';
            msgBox.classList.add(isSuccess ? 'alert-success' : 'alert-danger');
            msgBox.innerHTML = (isSuccess
                    ? '<i class="bi bi-check-circle me-1"></i>'
                    : '<i class="bi bi-exclamation-triangle me-1"></i>'
                ) + text;
        }
    });
</script>
@endsection
