<?php
    $prefix = auth()->user()->role === 'admin' ? 'admin.' : 'user.';
    $brands = \App\Models\Brand::where('status', 1)->get();
    $activeBrandId = request()->query('brand_id'); // This will be set by the controller redirect if empty
    if (!$activeBrandId) {
        $user = auth()->user();
        if ($user) {
            $activeBrandId = \App\Models\Brand::where('user_id', $user->id)->where('status', 1)->first()?->id;
        }
    }
?>

<?php $__env->startSection('content'); ?>
     <?php $__env->slot('header', null, []); ?> 
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            <?php echo e(__($walletName . ' Settings')); ?>

        </h2>
     <?php $__env->endSlot(); ?>

    <div class="py-12" x-data="walletSettings()">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
                <!-- Horizontal Scrollable Wallet List -->
                <div class="p-2 border-b border-gray-200 dark:border-gray-700">
                    <ul x-ref="walletList" class="flex space-x-1 overflow-x-auto pb-2">
                        <template x-for="item in sidebarItems" :key="item.id">
                            <li class="flex-shrink-0">
                                <a :href="item.href"
                                    :class="item.active ? 'bg-blue-50 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300' :
                                        'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700'"
                                    class="flex flex-col items-center justify-center gap-2 p-4 rounded-lg transition-all font-medium text-sm w-28 h-28">
                                    <img :src="item.icon" class="w-10 h-10 object-contain">
                                    <span x-text="item.label" class="whitespace-nowrap text-center"></span>
                                </a>
                            </li>
                        </template>
                    </ul>
                </div>

                <!-- Tab Header -->
                <div class="border-b border-gray-200 dark:border-gray-700">
                    <ul class="flex -mb-px px-4 sm:px-6 overflow-x-auto">
                        <?php if($brands->isNotEmpty()): ?>
                            <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <li class="flex-shrink-0">
                                    <a href="<?php echo e(request()->url()); ?>?brand_id=<?php echo e($brand->id); ?>"
                                       x-on:click="activeBrandId = '<?php echo e($brand->id); ?>'"
                                        class="<?php echo \Illuminate\Support\Arr::toCssClasses([
                                            'inline-block px-6 py-4 -mb-px text-base font-semibold text-center whitespace-nowrap border-b-2 transition-colors duration-200',
                                            'border-blue-500 text-blue-600 dark:border-blue-400 dark:text-blue-300 bg-blue-50 dark:bg-gray-700/50' =>
                                                $brand->id == $activeBrandId,
                                            'border-transparent text-gray-500 dark:text-gray-400 hover:text-blue-600 hover:border-blue-500 dark:hover:text-blue-300 dark:hover:border-blue-400' =>
                                                $brand->id != $activeBrandId,
                                        ]); ?>">
                                        <?php echo e($brand->name); ?>

                                    </a>
                                </li>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        <?php endif; ?>
                    </ul>
                </div>

                <!-- Form Content -->
                <div class="p-6">
                    <div class="flex items-center gap-3 mb-6">
                        <i class="fas fa-wallet text-blue-500 text-xl"></i>
                        <h3 class="text-xl font-bold text-gray-900 dark:text-gray-100"><?php echo e($walletName); ?> Setup for
                            <?php echo e($brands->find($activeBrandId)?->name ?? ''); ?>

                        </h3>
                    </div>

                    <!-- Success/Error Messages -->
                    <div x-show="message"
                        :class="messageType === 'success' ? 'bg-green-100 border-green-400 text-green-700' :
                            'bg-red-100 border-red-400 text-red-700'"
                        class="border px-4 py-3 rounded relative mb-4" role="alert" x-cloak>
                        <strong class="font-bold" x-text="messageType === 'success' ? 'Success!' : 'Error!'"></strong>
                        <span class="block sm:inline" x-text="message"></span>
                    </div>

                    <?php if($brands->isEmpty()): ?>
                        <div class="text-center py-12">
                            <i class="fas fa-store-slash text-5xl text-gray-400 mb-4"></i>
                            <h3 class="text-xl font-bold text-gray-800 dark:text-gray-200">No Brands Found</h3>
                            <p class="text-gray-600 dark:text-gray-400 mt-2">You need to create a brand before you can
                                configure wallet settings.</p>
                            <a href="<?php echo e(route($prefix . 'brands.index')); ?>"
                                class="mt-6 inline-flex items-center px-4 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition ease-in-out duration-150">
                                <i class="fas fa-plus mr-2"></i>
                                Create Your First Brand
                            </a>
                        </div>
                    <?php else: ?>
                        <form @submit.prevent="submitForm" method="POST"
                            :action="`<?php echo e(route($prefix . 'wallets.update', ['wallet' => $wallet])); ?>`" class="space-y-6">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="brand_id" x-model="form.brand_id">

                            <!-- Status -->
                            <div class="grid grid-cols-1 gap-6">
                                <div>
                                    <label
                                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Status</label>
                                    <select name="status" x-model="form.status"
                                        class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                        <option value="0">Inactive</option>
                                        <option value="1">Active</option>
                                    </select>
                                </div>
                            </div>

                            <?php if($isMobileBanking): ?>
                                <!-- Active Payment Types for Mobile Banking -->
                                <div>
                                    <p class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Active Payment Type
                                    </p>
                                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                                        <label class="flex items-center space-x-3 cursor-pointer">
                                            <input type="checkbox" name="is_personal_active"
                                                x-model="form.is_personal_active"
                                                class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500">
                                            <span class="text-sm font-medium dark:text-gray-300">Personal</span>
                                        </label>
                                        <label class="flex items-center space-x-3 cursor-pointer">
                                            <input type="checkbox" name="is_agent_active" x-model="form.is_agent_active"
                                                class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500">
                                            <span class="text-sm font-medium dark:text-gray-300">Agent</span>
                                        </label>
                                        <label class="flex items-center space-x-3 cursor-pointer">
                                            <input type="checkbox" name="is_merchant_active"
                                                x-model="form.is_merchant_active"
                                                class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500">
                                            <span class="text-sm font-medium dark:text-gray-300">Merchant</span>
                                        </label>
                                        <label class="flex items-center space-x-3 cursor-pointer">
                                            <input type="checkbox" name="is_payment_active" x-model="form.is_payment_active"
                                                class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500">
                                            <span class="text-sm font-medium dark:text-gray-300">Payment</span>
                                        </label>
                                    </div>
                                </div>

                                <!-- Conditional Fields for Mobile Banking -->
                                <div class="space-y-6">
                                    <!-- Personal Number -->
                                    <div x-show="form.is_personal_active" x-transition>
                                        <label
                                            class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?php echo e($walletName); ?>

                                            Personal number</label>
                                        <input type="text" name="personal_number" x-model="form.personal_number"
                                            placeholder="Enter your personal <?php echo e(strtolower($walletName)); ?> number"
                                            class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                    </div>

                                    <!-- Payment Number -->
                                    <div x-show="form.is_payment_active" x-transition style="display: none;">
                                        <label
                                            class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?php echo e($walletName); ?>

                                            Merchant Payment number</label>
                                        <input type="text" name="payment_number" x-model="form.payment_number"
                                            placeholder="Enter your Merchant Payment number"
                                            class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                    </div>

                                    <!-- Agent Number -->
                                    <div x-show="form.is_agent_active" x-transition style="display: none;">
                                        <label
                                            class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?php echo e($walletName); ?>

                                            Agent number</label>
                                        <input type="text" name="agent_number" x-model="form.agent_number"
                                            placeholder="Enter your agent number"
                                            class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                    </div>

                                    <!-- Merchant Settings -->
                                    <div x-show="form.is_merchant_active" x-transition>
                                        <?php echo $__env->make('dashboard.wallet-merchant-settings', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                                    </div>
                                </div>
                            <?php elseif($isBank): ?>
                                <!-- Fields for Banks -->
                                <?php echo $__env->make('dashboard.wallet-bank-settings', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                            <?php elseif($isCrypto): ?>
                                <!-- Fields for Crypto/International -->
                                <?php echo $__env->make('dashboard.wallet-crypto-settings', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                            <?php endif; ?>

                            <!-- Submit Button -->
                            <div class="flex justify-end pt-6">
                                <button type="submit"
                                    class="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition">
                                    Save <?php echo e($walletName); ?> Setting
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
    <script>
        document.head.insertAdjacentHTML('beforeend', `<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">`);

        function walletSettings() {
            const walletData = <?php echo json_encode($walletSetting, 15, 512) ?> || {}; // Pass data from controller, fallback to empty object

            return {
                wallet: '<?php echo e($wallet); ?>',
                walletName: '<?php echo e($walletName); ?>',
                isMobileBanking: <?php echo json_encode($isMobileBanking, 15, 512) ?>,
                isBank: <?php echo json_encode($isBank, 15, 512) ?>,
                isCrypto: <?php echo json_encode($isCrypto, 15, 512) ?>,
                message: '',
                messageType: '', // 'success' or 'error'
                sidebarItems: [{
                        id: 1,
                        label: 'Bkash',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'bkash'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/bKash.svg')); ?>'
                    },
                    {
                        id: 2,
                        label: 'Nagad',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'nagad'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/Nagad.svg')); ?>'
                    },
                    {
                        id: 3,
                        label: 'Rocket',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'rocket'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/Rocket.svg')); ?>'
                    },
                    {
                        id: 4,
                        label: 'Upay',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'upay'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/Upay.svg')); ?>'
                    },
                    {
                        id: 5,
                        label: 'Cellfin',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'cellfin'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/Cellfin.svg')); ?>'
                    },
                    {
                        id: 6,
                        label: 'Tap',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'tap'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/tapnpay.svg')); ?>'
                    },
                    {
                        id: 7,
                        label: 'Islamic Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'ibl'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/islami-bank.svg')); ?>'
                    },
                    {
                        id: 8,
                        label: 'AB Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'abbank'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/ab-bank.svg')); ?>'
                    },
                    {
                        id: 9,
                        label: 'City Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'citybank'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/city-bank.png')); ?>'
                    },
                    {
                        id: 10,
                        label: 'Sonali Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'sonali'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/Sonali-Bank.png')); ?>'
                    },
                    {
                        id: 11,
                        label: 'DBBL Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'dbbl'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/dbbl-bank.png')); ?>'
                    },
                    {
                        id: 12,
                        label: 'Basic Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'basic'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/basic-bank.png')); ?>'
                    },
                    {
                        id: 13,
                        label: 'EBL Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'ebl'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/ebl.png')); ?>'
                    },
                    {
                        id: 14,
                        label: 'Brac Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'bbrac'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/brac-bank.png')); ?>'
                    },
                    {
                        id: 15,
                        label: 'Bank Asia',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'basia'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/bank-asia.png')); ?>'
                    },
                    {
                        id: 16,
                        label: 'Agrani Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'agrani'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/agrani-bank.png')); ?>'
                    },
                    {
                        id: 17,
                        label: 'Jamuna Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'jamuna'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/jamuna-bank.svg')); ?>'
                    },
                    {
                        id: 18,
                        label: 'IFIC Bank',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'ific'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/ific-bank.png')); ?>'
                    },
                    {
                        id: 19,
                        label: 'Binance',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'binance'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/Binance.png')); ?>'
                    },
                    {
                        id: 20,
                        label: 'Payeer',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'payeer'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/Payeer.png')); ?>'
                    },
                    {
                        id: 21,
                        label: 'Ipay',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'ipay'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/iPay.svg')); ?>'
                    },
                    {
                        id: 22,
                        label: 'Ok Wallet',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'okwallet'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/okwallet.svg')); ?>'
                    },
                    {
                        id: 23,
                        label: 'Sure Cash',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'surecash'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/SureCash.svg')); ?>'
                    },
                    {
                        id: 24,
                        label: 'MCash',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'mcash'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/mCash.svg')); ?>'
                    },
                    {
                        id: 25,
                        label: 'myCash',
                        href: '<?php echo e(route($prefix . 'wallets.settings', ['wallet' => 'mycash'])); ?>',
                        icon: '<?php echo e(asset('assets/image/bank-img/mycash.svg')); ?>'
                    },
                ],
                form: {
                    brand_id: '<?php echo e($activeBrandId); ?>',
                    status: String(walletData.status == 1 ? 1 : 0),
                    is_personal_active: walletData.is_personal_active == 1,
                    is_agent_active: walletData.is_agent_active == 1,
                    is_merchant_active: walletData.is_merchant_active == 1,
                    is_payment_active: walletData.is_payment_active == 1,
                    personal_number: walletData.personal_number || '',
                    payment_number: walletData.payment_number || '',
                    agent_number: walletData.agent_number || '',
                    sandbox: String(walletData.sandbox == 1 ? 1 : 0),
                    logs: String(walletData.logs == 1 ? 1 : 0),
                    username: walletData.username || '',
                    password: '', // Password should not be pre-filled for security
                    app_key: walletData.app_key || '',
                    app_secret: '', // App secret should not be pre-filled for security
                    account_number: walletData.account_number || '',
                    account_name: walletData.account_name || '',
                    branch_name: walletData.branch_name || '',
                    wallet_address: walletData.wallet_address || '',
                    api_key: walletData.api_key || ''
                },
                init() {
                    // Highlight active sidebar item
                    this.sidebarItems = this.sidebarItems.map(item => ({
                        ...item,
                        active: item.href.includes(this.wallet)
                    }));

                    // Enable horizontal scrolling with mouse wheel
                    const walletList = this.$refs.walletList;
                    if (walletList) {
                        walletList.addEventListener('wheel', (e) => {
                            if (e.deltaY !== 0) {
                                e.preventDefault();
                                walletList.scrollLeft += e.deltaY;
                            }
                        });
                    }
                },
                async submitForm() {
                    this.message = ''; // Clear previous messages
                    this.messageType = '';

                    // Create a payload and convert boolean values to integers for the backend.
                    const payload = {
                        ...this.form
                    };
                    payload.status = parseInt(payload.status || 0);

                    if (this.isMobileBanking) {
                        payload.is_personal_active = payload.is_personal_active ? 1 : 0;
                        payload.is_agent_active = payload.is_agent_active ? 1 : 0;
                        payload.is_merchant_active = payload.is_merchant_active ? 1 : 0;
                        payload.is_payment_active = payload.is_payment_active ? 1 : 0;
                        payload.sandbox = parseInt(payload.sandbox || 0);
                        payload.logs = parseInt(payload.logs || 0);
                    }

                    try {
                        const response = await fetch(this.$el.action, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute(
                                    'content')
                            },
                            body: JSON.stringify(payload)
                        });

                        const data = await response.json();

                        if (response.ok) {
                            this.message = data.message;
                            this.messageType = 'success';
                            // Optionally update form with fresh data from server if needed
                            setTimeout(() => {
                                const currentUrl = new URL(window.location.href);
                                currentUrl.searchParams.set('brand_id', payload.brand_id);
                                window.location.href = currentUrl.href;
                            }, 1500);
                            // this.form = { ...this.form, ...data.walletSetting };
                        } else {
                            this.message = data.message || 'An error occurred during submission.';
                            this.messageType = 'error';
                            if (data.errors) {
                                // Display validation errors
                                for (const key in data.errors) {
                                    this.message += `\n- ${data.errors[key][0]}`;
                                }
                            }
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        this.message = 'Network error or server unreachable.';
                        this.messageType = 'error';
                    }

                    // Scroll to top to show message
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                }
            }
        }
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\hilnexpay\resources\views/dashboard/wallets.blade.php ENDPATH**/ ?>