@extends('layouts.front')
@section('title', 'Fraud Checker Pro')
@section('contents')

{{-- ১. SweetAlert2 CDN (পপআপ এর জন্য এটি যুক্ত করা হলো) --}}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

{{-- Tailwind CSS & Config --}}
<script src="https://cdn.tailwindcss.com"></script>
<script>
    tailwind.config = {
        prefix: 'tw-', 
        theme: { 
            extend: { 
                fontFamily: { sans: ['Inter', 'sans-serif'], },
                colors: { 
                    brand: { light: '#818cf8', DEFAULT: '#4f46e5', dark: '#3730a3' },
                    success: '#10b981', 
                    danger: '#ef4444',
                    warning: '#f59e0b'
                },
                boxShadow: {
                    'pro': '0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03)',
                }
            } 
        }
    }
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
    body { font-family: 'Inter', sans-serif; background-color: #f8fafc; }

    /* --- সাইডবার ডিজাইন --- */
    .sidebar-card { background: #fff; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); overflow: hidden; border: 1px solid #edf2f7; }
    .user-profile-box { text-align: center; padding: 35px 20px; background: #fff; border-bottom: 1px solid #f1f5f9; }
    .user-avatar-wrapper { position: relative; width: 100px; height: 100px; margin: 0 auto 15px; }
    .user-avatar { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; border: 3px solid #4e73df; background-color: #eee; }
    .menu-link { display: flex; align-items: center; padding: 14px 20px; color: #64748b; text-decoration: none; border-radius: 12px; margin: 5px 15px; transition: 0.3s; font-weight: 500; }
    .menu-link i { width: 30px; font-size: 18px; }
    .menu-link:hover, .menu-link.active { background: #f1f5f9; color: #4e73df; }
    .menu-link.active i { color: #4e73df; }
    .menu-link.text-danger:hover { background: #fff1f2; color: #e11d48; }

    /* --- প্রফেশনাল ডিজাইন স্টাইল --- */
    .pro-card {
        background: #fff;
        border-radius: 16px;
        border: 1px solid #e2e8f0;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
        overflow: hidden;
    }

    /* Info Bar */
    .info-bar {
        background: #fff; border-radius: 12px; padding: 15px 20px;
        border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between;
        flex-wrap: wrap; gap: 10px; margin-bottom: 25px;
    }
    .info-item { display: inline-flex; align-items: center; font-size: 13px; font-weight: 600; color: #475569; }
    .info-item i { color: #4f46e5; margin-right: 8px; }

    /* Search Input */
    .modern-search-container { position: relative; display: flex; align-items: center; }
    .modern-search-input {
        width: 100%; padding: 16px 20px 16px 50px; border-radius: 12px;
        border: 2px solid #e2e8f0; background: #f8fafc; font-size: 16px;
        transition: all 0.3s ease; outline: none;
    }
    .modern-search-input:focus { border-color: #4f46e5; background: #fff; box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1); }
    .search-icon-box { position: absolute; left: 20px; color: #94a3b8; }
    .modern-search-btn {
        position: absolute; right: 10px; top: 10px; bottom: 10px;
        background: #4f46e5; color: #fff; border: none; padding: 0 25px;
        border-radius: 8px; font-weight: 600; transition: 0.3s; cursor: pointer;
    }
    .modern-search-btn:hover { background: #4338ca; }

    /* Stat Boxes */
    .stat-box-modern {
        background: #fff; border-radius: 12px; padding: 20px;
        border: 1px solid #e2e8f0; text-align: left;
        display: flex; align-items: center; justify-content: space-between;
    }
    .stat-icon-wrap { width: 50px; height: 50px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; }
    .stat-label { font-size: 13px; font-weight: 600; color: #64748b; display: block; margin-bottom: 4px; }
    .stat-value { font-size: 24px; font-weight: 800; color: #1e293b; line-height: 1; }

    /* Progress Circle */
    .circular-progress-sleek { 
        width: 150px; height: 150px; border-radius: 50%; 
        display: flex; justify-content: center; align-items: center; 
        background: conic-gradient(#e2e8f0 0%, #e2e8f0 0%); 
        margin: 20px auto; position: relative;
        box-shadow: inset 0 0 10px rgba(0,0,0,0.05);
    }
    .inner-circle-sleek { 
        position: absolute; background-color: #fff; border-radius: 50%; 
        width: 120px; height: 120px; display: flex; justify-content: center; align-items: center; flex-direction: column;
    }
    .percentage-sleek { font-size: 2rem; font-weight: 800; line-height: 1; }
    .percentage-label { font-size: 11px; font-weight: 600; color: #94a3b8; text-transform: uppercase; margin-top: 5px;}

    /* Table */
    .pro-table th { background: #f8fafc; color: #475569; font-weight: 600; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; padding: 16px; }
    .pro-table td { padding: 16px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; color: #334155; font-weight: 500;}
    .pro-table tr:hover td { background: #fcfdff; }
    .pro-table tr:last-child td { border-bottom: none; }
</style>

<div class="section-padding py-5">
    <div class="container-fluid tw-max-w-7xl tw-mx-auto">
        <div class="row g-4">
            
            {{-- সাইডবার --}}
            <div class="col-lg-3 col-md-4 d-none d-md-block">
                <div class="sidebar-card">
                    <div class="user-profile-box">
                        <div class="user-avatar-wrapper">
                            <img src="{{ Auth::user()->photo ? asset('assets/images/users/'.Auth::user()->photo) : 'https://cdn-icons-png.flaticon.com/512/149/149071.png' }}" class="user-avatar">
                        </div>
                        <h6 class="fw-bold text-dark mb-0">{{ Auth::user()->name }}</h6>
                        <span class="badge bg-light text-primary border mt-2">ক্লায়েন্ট</span>
                    </div>
                    <div class="py-3">
                        <a href="{{ route('user.dashboard') }}" class="menu-link"><i class="fa-solid fa-table-columns"></i> ড্যাশবোর্ড</a>
						
												<a href="{{ route('user.domains.index') }}" class="menu-link {{ request()->routeIs('user.domains.index') ? 'active' : '' }}">
    <i class="fa-solid fa-globe"></i> আমার ডোমেইন
</a>
{{-- আমার হোস্টিং মেনু লিংক --}}
<a href="{{ route('user.hostings.index') }}" class="menu-link {{ request()->routeIs('user.hostings.index') ? 'active' : '' }}">
    <i class="fa-solid fa-server"></i> আমার হোস্টিং
</a>
                     			<div class="menu-item-group">
    <a href="javascript:void(0);" class="menu-link d-flex justify-content-between align-items-center" onclick="toggleSubMenu(event, 'fraudSubMenu')">
        <span><i class="fa-solid fa-shield-halved"></i> ফ্রড সার্ভিস</span>
        <i class="fa-solid fa-chevron-down mt-1" style="font-size: 12px;"></i>
    </a>
    
    <div id="fraudSubMenu" class="submenu-container" style="{{ request()->is('user/fraud*') || request()->is('user/api*') ? 'display: block;' : 'display: none;' }}">
        <a href="{{ route('user.fraud.check') }}" class="menu-link ps-5 {{ request()->routeIs('user.fraud.check') ? 'active' : '' }}">
            <i class="fa-solid fa-user-shield"></i> ফ্রড চেকার
        </a>
        
        <a href="{{ route('user.fraud.pricing') }}" class="menu-link ps-5 {{ request()->routeIs('user.fraud.pricing') ? 'active' : '' }}">
            <i class="fa-solid fa-tags"></i> প্যাকেজ কিনুন
        </a>
        
        <a href="{{ route('user.api.docs') }}" class="menu-link ps-5 {{ request()->routeIs('user.api.docs') ? 'active' : '' }}">
            <i class="fa-solid fa-code"></i> API ডকুমেন্টেশন
        </a>
    </div>
</div>
<style>
    .submenu-container {
    background: #fdfdfd; /* সাব-মেনুর জন্য হালকা আলাদা ব্যাকগ্রাউন্ড */
    border-radius: 12px;
    margin: 2px 15px;
}

.ps-5 {
    padding-left: 45px !important; /* সাব-মেনু আইটেমগুলোকে একটু ভেতরে সরানোর জন্য */
    font-size: 14px !important;    /* সাব-মেনু ফন্ট একটু ছোট */
}

.menu-link i.fa-chevron-down {
    transition: transform 0.3s ease;
}

.menu-link.open i.fa-chevron-down {
    transform: rotate(180deg);
}
</style>
<script>
    function toggleSubMenu(event, menuId) {
        event.preventDefault();
        const menu = document.getElementById(menuId);
        const link = event.currentTarget;
        
        if (menu.style.display === "none") {
            menu.style.display = "block";
            link.classList.add('open');
        } else {
            menu.style.display = "none";
            link.classList.remove('open');
        }
    }
</script>

<div class="menu-item-group">
    {{-- প্যারেন্ট মেনু --}}
    <a href="javascript:void(0);" class="menu-link d-flex justify-content-between align-items-center {{ request()->is('user/sms*') || request()->is('user/recharge*') ? 'open' : '' }}" onclick="toggleSubMenu(event, 'smsSubMenu')">
        <span><i class="fa-solid fa-comment-sms"></i> এসএমএস সার্ভিস</span>
        <i class="fa-solid fa-chevron-down mt-1" style="font-size: 12px;"></i>
    </a>
    
    {{-- সাব-মেনু --}}
    <div id="smsSubMenu" class="submenu-container" style="{{ request()->is('user/sms*') || request()->is('user/recharge*') ? 'display: block;' : 'display: none;' }}">
        
        <a href="{{ route('user.sms.panel') }}" class="menu-link ps-5 {{ request()->routeIs('user.sms.panel') ? 'active' : '' }}">
            <i class="fa-solid fa-paper-plane"></i> এসএমএস পাঠান
        </a>
        {{-- ২. এসএমএস হিস্ট্রি --}}
<a href="{{ route('user.sms.history') }}" class="menu-link ps-5 {{ request()->routeIs('user.sms.history') ? 'active' : '' }}">
    <i class="fa-solid fa-history"></i> এসএমএস হিস্ট্রি
</a>
        <a href="{{ route('user.recharge.index') }}" class="menu-link ps-5 {{ request()->routeIs('user.recharge.index') ? 'active' : '' }}">
            <i class="fa-solid fa-wallet"></i> রিচার্জ করুন
        </a>
<a href="{{ route('user.sms.api_docs') }}" class="menu-link ps-5 {{ request()->routeIs('user.sms.api_docs') ? 'active' : '' }}">
    <i class="fa-solid fa-code"></i> এপিআই ডকুমেন্টেশন
</a>
    </div>
</div>
                        <a href="{{ route('user.fraud.pricing') }}" class="menu-link"><i class="fa-solid fa-tags"></i> প্যাকেজ কিনুন</a>
                        <a href="{{ route('user.licenses') }}" class="menu-link"><i class="fa-solid fa-key"></i> আমার লাইসেন্স</a>
                        <a href="{{ route('user.support') }}" class="menu-link"><i class="fa-solid fa-headset"></i> সাপোর্ট টিকেট</a>
                        <a href="{{ route('user.profile') }}" class="menu-link"><i class="fa-solid fa-user-gear"></i> প্রোফাইল সেটিংস</a>
                        <a href="{{ route('user.logout') }}" class="menu-link text-danger mt-4"><i class="fa-solid fa-right-from-bracket"></i> লগআউট</a>
                    </div>
                </div>
            </div>

            {{-- মেইন কন্টেন্ট এরিয়া --}}
            <div class="col-lg-9 col-md-8">
                
                {{-- ইনফো বার --}}
                <div class="info-bar shadow-sm">
                    <div class="d-flex align-items-center">
                        <span class="tw-bg-indigo-100 tw-text-indigo-600 tw-p-2 tw-rounded-lg tw-mr-3">
                            <i class="fa-solid fa-database"></i>
                        </span>
                        <div>
                            <h5 class="mb-0 tw-font-bold tw-text-gray-800">Courier Intelligence Hub</h5>
                            <p class="mb-0 tw-text-xs tw-text-gray-500">Supported Networks: Pathao, Steadfast, RedX, Paperfly</p>
                        </div>
                    </div>
                    <div class="d-none d-md-flex tw-gap-4">
                        <span class="info-item"><i class="fa-solid fa-shield-check"></i> রিয়েল-টাইম ভেরিফিকেশন</span>
                        <span class="info-item"><i class="fa-solid fa-headset"></i> 24/7 সাপোর্ট</span>
                    </div>
                </div>

                <div class="row g-4">
                    {{-- বাম পাশের কার্ড (Risk Profile) --}}
                    <div class="col-xl-4 col-lg-5">
                        <div class="pro-card tw-p-6 tw-text-center tw-sticky tw-top-24">
                            <div>
                                <h6 class="tw-font-bold tw-text-gray-700 tw-uppercase tw-tracking-wider tw-text-sm mb-1">Customer Risk Profile</h6>
                                <p class="tw-text-gray-400 tw-text-xs mb-4">Delivery Success Probability</p>
                            </div>
                            
                            <div class="circular-progress-sleek">
                                <div class="inner-circle-sleek">
                                    <span class="percentage-sleek tw-text-gray-300" id="circle-percent">--</span>
                                    <span class="percentage-label">Success Rate</span>
                                </div>
                            </div>
                            
                            <div class="mt-4">
                                <span id="risk-badge" class="tw-px-4 tw-py-2 tw-rounded-full tw-font-bold tw-text-sm tw-bg-gray-100 tw-text-gray-500">
                                    <i class="fa-solid fa-circle-question tw-mr-2"></i> অপেক্ষা করুন
                                </span>
                            </div>
                            <p class="tw-text-gray-400 tw-text-xs mt-3">ডাটা দেখতে ডানপাশের ফর্মটি ব্যবহার করুন।</p>
                        </div>
                    </div>

                    {{-- ডান পাশের কার্ড (Search & Detailed Results) --}}
                    <div class="col-xl-8 col-lg-7">
                        <div class="pro-card tw-p-6">
                            
                            {{-- সার্চ ফর্ম --}}
                            <form id="checkForm" class="mb-8">
                                <div class="modern-search-container">
                                    <div class="search-icon-box">
                                        <i class="fa-solid fa-magnifying-glass"></i>
                                    </div>
                                    <input type="tel" id="phoneInput" class="modern-search-input" placeholder="কাস্টমারের মোবাইল নাম্বার লিখুন (017xxxxxxxx)" maxlength="11" required>
                                    <button type="submit" class="modern-search-btn">
                                        <i class="fa-solid fa-paper-plane-top tw-mr-2"></i> চেক করুন
                                    </button>
                                </div>
                            </form>

                            {{-- লোডার --}}
                            <div id="loader" class="text-center py-12 d-none">
                                <div class="spinner-border tw-text-indigo-600" role="status" style="width: 3rem; height: 3rem;"></div>
                                <p class="tw-text-gray-500 tw-font-medium mt-4">একাধিক কুরিয়ার ডাটাবেজ সার্চ করা হচ্ছে...</p>
                            </div>

                            {{-- রেজাল্ট এরিয়া --}}
                            <div id="result-area" class="tw-transition-opacity tw-duration-300">
                                
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h5 class="tw-font-bold tw-text-gray-800 mb-0">Report Analysis</h5>
                                    <span id="res-phone" class="tw-bg-indigo-50 tw-text-indigo-700 tw-px-3 tw-py-1 tw-rounded-lg tw-font-bold tw-text-sm d-none"></span>
                                </div>
                                
                                {{-- সামারি বক্স --}}
                                <div class="row g-3 mb-6">
                                    <div class="col-md-4 col-sm-6">
                                        <div class="stat-box-modern">
                                            <div>
                                                <span class="stat-label">মোট পার্সেল</span>
                                                <span class="stat-value" id="total-val">0</span>
                                            </div>
                                            <div class="stat-icon-wrap tw-bg-blue-50 tw-text-blue-500">
                                                <i class="fa-solid fa-boxes-stacked"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 col-sm-6">
                                        <div class="stat-box-modern">
                                            <div>
                                                <span class="stat-label">সফল পার্সেল</span>
                                                <span class="stat-value tw-text-emerald-600" id="success-val">0</span>
                                            </div>
                                            <div class="stat-icon-wrap tw-bg-emerald-50 tw-text-emerald-500">
                                                <i class="fa-solid fa-circle-check"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 col-sm-12">
                                        <div class="stat-box-modern">
                                            <div>
                                                <span class="stat-label">বাতিল/রিটার্ন</span>
                                                <span class="stat-value tw-text-rose-600" id="cancel-val">0</span>
                                            </div>
                                            <div class="stat-icon-wrap tw-bg-rose-50 tw-text-rose-500">
                                                <i class="fa-solid fa-circle-xmark"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                {{-- টেবিল --}}
                                <div class="tw-overflow-x-auto tw-rounded-xl tw-border tw-border-gray-200">
                                    <table class="table-auto tw-w-full pro-table">
                                        <thead>
                                            <tr>
                                                <th class="text-start pl-4">কুরিয়ার নেটওয়ার্ক</th>
                                                <th class="text-center">মোট অর্ডার</th>
                                                <th class="text-center">সাকসেস</th>
                                                <th class="text-center">রিটার্ন</th>
                                                <th class="text-end pr-4">সাকসেস রেট</th>
                                            </tr>
                                        </thead>
                                        <tbody id="table-body" class="tw-bg-white">
                                            <tr>
                                                <td colspan="5" class="py-12 text-center text-muted">
                                                    <img src="https://cdn-icons-png.flaticon.com/512/7486/7486747.png" width="60" class="tw-opacity-50 tw-mx-auto tw-mb-3">
                                                    <p class="mb-0 tw-font-medium">কোনো তথ্য দেখানো হচ্ছে না।</p>
                                                    <p class="tw-text-xs">অনুগ্রহ করে একটি মোবাইল নাম্বার দিয়ে সার্চ করুন।</p>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<script>
    const checkUrl = "{{ route('user.fraud.check.process') }}";
    const pricingUrl = "{{ route('user.fraud.pricing') }}"; // প্যাকেজ কেনার লিংক
    const csrf = "{{ csrf_token() }}";

    // লোগো কনফিগারেশন
    const myLogos = {
        'pathao': "{{ asset('assets/images/couriers/pathao.png') }}",
        'steadfast': "{{ asset('assets/images/couriers/steadfast.png') }}",
        'parceldex': "{{ asset('assets/images/couriers/parceldex.png') }}",
        'redx': "{{ asset('assets/images/couriers/redx.png') }}",
        'paperfly': "{{ asset('assets/images/couriers/paperfly.png') }}",
        'carrybee': "{{ asset('assets/images/couriers/carrybee.png') }}"
    };

    document.getElementById('checkForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const phone = document.getElementById('phoneInput').value.trim();
        const btn = document.querySelector('.modern-search-btn');

        if(!/^01[3-9]\d{8}$/.test(phone)) {
            Swal.fire({
                icon: 'warning',
                title: 'ভুল নাম্বার!',
                text: 'দয়া করে সঠিক ১১ ডিজিটের বাংলাদেশী মোবাইল নাম্বার দিন।',
                confirmButtonColor: '#4f46e5'
            });
            return;
        }

        document.getElementById('loader').classList.remove('d-none');
        document.getElementById('result-area').style.opacity = '0.2';
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin tw-mr-2"></i> হচ্ছে...';

        fetch(checkUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf },
            body: JSON.stringify({ phoneNumber: phone })
        })
        .then(res => res.json())
        .then(response => {
            if(response.status === 'success') {
                updateUI(response.data, phone);
            } else {
                // ============================================
                // 🔥 আধুনিক পপ-আপ ডিজাইন (Modern Popup) 🔥
                // ============================================

                if (response.error_type === 'new_user') {
                    // ১. নতুন ইউজার - ওয়েলকাম মেসেজ
                    Swal.fire({
                        title: '<h3 style="color:#4e73df; font-weight:bold;">' + response.title + '</h3>',
                        html: `<p style="font-size:15px; color:#555;">${response.message}</p>`,
                        imageUrl: 'https://cdn-icons-png.flaticon.com/512/8690/8690059.png', // সুন্দর 3D আইকন
                        imageWidth: 100,
                        imageHeight: 100,
                        imageAlt: 'Welcome',
                        confirmButtonText: '🚀 প্যাকেজ কিনুন',
                        confirmButtonColor: '#4e73df',
                        showCancelButton: true,
                        cancelButtonText: 'পরে দেখব',
                        background: '#fff',
                        backdrop: `rgba(0,0,123,0.4)`, // ব্লার ব্যাকগ্রাউন্ড
                        allowOutsideClick: false, 
                        customClass: {
                            popup: 'rounded-4 shadow-lg border-0',
                            confirmButton: 'px-4 py-2 rounded-pill',
                            cancelButton: 'px-4 py-2 rounded-pill'
                        }
                    }).then((result) => {
                        if (result.isConfirmed) window.location.href = pricingUrl;
                    });

                } else if (response.error_type === 'total_limit_over') {
                    // ২. মোট লিমিট শেষ
                    Swal.fire({
                        icon: 'warning',
                        title: '<h3 style="color:#e74a3b;">' + response.title + '</h3>',
                        text: response.message,
                        confirmButtonText: '⚡ এখনই রিনিউ করুন',
                        confirmButtonColor: '#e74a3b',
                        showCancelButton: true,
                        cancelButtonText: 'বাতিল',
                        background: '#fff',
                        customClass: { popup: 'rounded-4' }
                    }).then((result) => {
                        if (result.isConfirmed) window.location.href = pricingUrl;
                    });

                } else if (response.error_type === 'expired') {
                    // ৩. মেয়াদ শেষ
                    Swal.fire({
                        icon: 'error',
                        title: response.title,
                        text: response.message,
                        confirmButtonText: '📅 মেয়াদ বাড়ান',
                        confirmButtonColor: '#e74a3b',
                        showCancelButton: true,
                        cancelButtonText: 'ক্লোজ',
                        customClass: { popup: 'rounded-4' }
                    }).then((result) => {
                        if (result.isConfirmed) window.location.href = pricingUrl;
                    });

                } else if (response.error_type === 'daily_limit_over') {
                    // ৪. দৈনিক লিমিট শেষ
                    Swal.fire({
                        icon: 'info',
                        title: response.title,
                        html: `${response.message}<br><br><span class="badge bg-warning text-dark p-2">💡 টিপস: আনলিমিটেড চেকের জন্য প্যাকেজ আপগ্রেড করুন।</span>`,
                        confirmButtonText: 'প্যাকেজ আপগ্রেড',
                        confirmButtonColor: '#36b9cc',
                        showCancelButton: true,
                        cancelButtonText: 'আগামীকাল দেখব',
                        customClass: { popup: 'rounded-4' }
                    }).then((result) => {
                        if (result.isConfirmed) window.location.href = pricingUrl;
                    });

                } else {
                    // ৫. সাধারণ এরর
                    Swal.fire({
                        icon: 'error',
                        title: 'দুঃখিত!',
                        text: response.message || 'কোথাও সমস্যা হয়েছে।',
                        confirmButtonColor: '#e74a3b',
                        customClass: { popup: 'rounded-4' }
                    });
                    resetCounters();
                }
            }
        })
        .catch(err => {
            console.error(err);
            Swal.fire('Error', 'সার্ভারে সংযোগ সমস্যা হয়েছে।', 'error');
        })
        .finally(() => {
            document.getElementById('loader').classList.add('d-none');
            document.getElementById('result-area').style.opacity = '1';
            btn.disabled = false;
            btn.innerHTML = '<i class="fa-solid fa-paper-plane-top tw-mr-2"></i> চেক করুন';
        });
    });

    function updateUI(data, phone) {
        const tbody = document.getElementById('table-body');
        tbody.innerHTML = '';
        
        const phoneLabel = document.getElementById('res-phone');
        phoneLabel.innerText = phone;
        phoneLabel.classList.remove('d-none');

        // Summary Data
        const summary = data.summary || { total_parcel: 0, success_parcel: 0, cancelled_parcel: 0, success_ratio: 0 };

        document.getElementById('total-val').innerText = summary.total_parcel;
        document.getElementById('success-val').innerText = summary.success_parcel;
        document.getElementById('cancel-val').innerText = summary.cancelled_parcel;

        // Table Data Generation
        let hasRows = false;
        
        Object.keys(data).forEach(key => {
            if (key !== 'summary' && key !== 'reports') {
                const courier = data[key];
                hasRows = true;
                
                const ratio = Math.round(courier.success_ratio);
                let badgeClass = 'tw-bg-gray-100 tw-text-gray-600';
                if(ratio >= 90) badgeClass = 'tw-bg-emerald-100 tw-text-emerald-700';
                else if(ratio >= 70) badgeClass = 'tw-bg-blue-100 tw-text-blue-700';
                else if(ratio >= 50) badgeClass = 'tw-bg-amber-100 tw-text-amber-700';
                else badgeClass = 'tw-bg-rose-100 tw-text-rose-700';

                let cName = courier.name.toLowerCase(); 
                let finalLogo = courier.logo; 

                if(cName.includes('pathao')) finalLogo = myLogos['pathao'];
                else if(cName.includes('steadfast')) finalLogo = myLogos['steadfast'];
                else if(cName.includes('parceldex')) finalLogo = myLogos['parceldex'];
                else if(cName.includes('redx')) finalLogo = myLogos['redx'];
                else if(cName.includes('paperfly')) finalLogo = myLogos['paperfly'];
                else if(cName.includes('carrybee')) finalLogo = myLogos['carrybee'];

                if(!finalLogo) finalLogo = 'https://placehold.co/40x40?text=Logo';

                tbody.innerHTML += `
                    <tr>
                        <td class="tw-py-4 tw-pl-4 text-start">
                            <div class="d-flex align-items-center">
                                <div class="tw-p-2 tw-bg-white tw-rounded-lg tw-border tw-border-gray-100 tw-mr-3 tw-shadow-sm">
                                    <img src="${finalLogo}" class="tw-w-8 tw-h-8 tw-object-contain" onerror="this.src='https://placehold.co/40x40?text=N/A'">
                                </div>
                                <span class="tw-font-bold tw-text-gray-700 tw-capitalize">${courier.name}</span>
                            </div>
                        </td>
                        <td class="text-center tw-font-bold tw-text-gray-600">${courier.total_parcel}</td>
                        <td class="text-center tw-font-bold tw-text-emerald-600">${courier.success_parcel}</td>
                        <td class="text-center tw-font-bold tw-text-rose-500">${courier.cancelled_parcel}</td>
                        <td class="text-end pr-4">
                            <span class="tw-px-3 tw-py-1 tw-rounded-full tw-text-xs tw-font-bold ${badgeClass}">
                                ${ratio}%
                            </span>
                        </td>
                    </tr>`;
            }
        });

        if (!hasRows) {
            tbody.innerHTML = '<tr><td colspan="5" class="py-12 text-center text-muted"><p class="mb-0 tw-font-medium">কোনো কুরিয়ার ডাটা পাওয়া যায়নি।</p></td></tr>';
        }

        // Circle Progress Logic...
        const finalRate = Math.round(summary.success_ratio);
        const circlePercent = document.getElementById('circle-percent');
        circlePercent.innerText = finalRate;
        
        let color = '#ef4444';
        let badgeHtml = '<i class="fa-solid fa-triangle-exclamation tw-mr-2"></i> অত্যন্ত ঝুঁকিপূর্ণ';
        let badgeBg = 'tw-bg-rose-100 tw-text-rose-700';
        
        if(finalRate >= 90) { 
            color = '#10b981';
            badgeHtml = '<i class="fa-solid fa-shield-check tw-mr-2"></i> খুবই নিরাপদ';
            badgeBg = 'tw-bg-emerald-100 tw-text-emerald-700';
        } else if(finalRate >= 75) {
            color = '#4f46e5';
            badgeHtml = '<i class="fa-solid fa-check-circle tw-mr-2"></i> নিরাপদ';
            badgeBg = 'tw-bg-indigo-100 tw-text-indigo-700';
        } else if(finalRate >= 50) {
            color = '#f59e0b';
            badgeHtml = '<i class="fa-solid fa-circle-exclamation tw-mr-2"></i> মাঝারি ঝুঁকি';
            badgeBg = 'tw-bg-amber-100 tw-text-amber-700';
        }

        document.querySelector('.circular-progress-sleek').style.background = `conic-gradient(${color} ${finalRate}%, #e2e8f0 ${finalRate}%)`;
        circlePercent.style.color = color;
        
        const riskBadge = document.getElementById('risk-badge');
        riskBadge.innerHTML = badgeHtml;
        riskBadge.className = `tw-px-4 tw-py-2 tw-rounded-full tw-font-bold tw-text-sm ${badgeBg}`;
    }

    function resetCounters() {
        document.getElementById('res-phone').classList.add('d-none');
        document.getElementById('total-val').innerText = '0';
        document.getElementById('success-val').innerText = '0';
        document.getElementById('cancel-val').innerText = '0';
        document.getElementById('circle-percent').innerText = '--';
        document.getElementById('circle-percent').style.color = '#cbd5e1';
        document.querySelector('.circular-progress-sleek').style.background = `conic-gradient(#e2e8f0 0%, #e2e8f0 0%)`;
        
        const riskBadge = document.getElementById('risk-badge');
        riskBadge.innerHTML = '<i class="fa-solid fa-circle-question tw-mr-2"></i> অপেক্ষা করুন';
        riskBadge.className = 'tw-px-4 tw-py-2 tw-rounded-full tw-font-bold tw-text-sm tw-bg-gray-100 tw-text-gray-500';
    }
</script>
@endsection