{% include 'header.twig' %}

<div class="wrapper-content">
    <div class="container-fluid mt-4">
        
        <!-- Dashboard Statistics -->
        <div class="row mb-4">
            <!-- Welcome Card -->
            <div class="col-md-4 mb-3 mb-md-0">
                <div class="stats-card" style="background: rgba(20, 20, 30, 0.6); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.1); border-radius: 16px; padding: 20px; position: relative; overflow: hidden;">
                    <div style="position: absolute; top: -10px; right: -10px; width: 80px; height: 80px; background: rgba(30, 144, 255, 0.15); border-radius: 50%;"></div>
                    <div style="position: relative; z-index: 1;">
                        <div style="color: rgba(255,255,255,0.7); font-size: 14px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 5px;">Welcome to {{ site['site_name'] }}</div>
                        <div style="color: #fff; font-size: 24px; font-weight: 700;">{{ user['username'] }}</div>
                    </div>
                </div>
            </div>

            <!-- Balance Card -->
            <div class="col-md-4 mb-3 mb-md-0">
                <div class="stats-card" style="background: rgba(20, 20, 30, 0.6); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.1); border-radius: 16px; padding: 20px; position: relative; overflow: hidden;">
                    <div style="position: absolute; top: -10px; right: -10px; width: 80px; height: 80px; background: rgba(50, 205, 50, 0.15); border-radius: 50%;"></div>
                    <div style="position: relative; z-index: 1;">
                        <div style="color: rgba(255,255,255,0.7); font-size: 14px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 5px;">Total Balance</div>
                        <div style="color: #fff; font-size: 28px; font-weight: 700;">{{ user['balance'] }}</div>
                    </div>
                </div>
            </div>

            <!-- Spent Card -->
            <div class="col-md-4">
                <div class="stats-card" style="background: rgba(20, 20, 30, 0.6); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.1); border-radius: 16px; padding: 20px; position: relative; overflow: hidden;">
                    <div style="position: absolute; top: -10px; right: -10px; width: 80px; height: 80px; background: rgba(255, 69, 0, 0.15); border-radius: 50%;"></div>
                    <div style="position: relative; z-index: 1;">
                        <div style="color: rgba(255,255,255,0.7); font-size: 14px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 5px;">Total Spent</div>
                        <div style="color: #fff; font-size: 28px; font-weight: 700;">{{ user['spent'] }}</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">

            <!-- Left Column: Tabs & Order Form -->
            <div class="col-lg-8">
                
                <!-- Top Tabs & Balance Row -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <ul class="nav nav-tabs-custom">
                        <li class="nav-item">
                            <a class="nav-link active" href="/"><img src="https://cdn-icons-png.flaticon.com/512/862/862856.png" width="20" class="mr-2"> New Order</a>
                        </li>
                    </ul>
                </div>

                <!-- Order Form Card -->
                <div class="card border-0 shadow-lg mb-4" style="border-radius: 16px; min-height: 600px; background: rgba(20, 20, 30, 0.6); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.1); color: #fff;">
                    <div class="card-body p-4">
                        
                        <!-- Error / Success Alerts -->
                        {% if error %}
                          <div class="alert alert-dismissible alert-danger">
                            {{ errorText }}
                          </div>
                        {% endif %}
                    
                        {% if data["order"]["success"] == 1 %}
                          <div class="alert alert-dismissible alert-success">
                              <h4><i class="fas fa-check-circle"></i> Your Order Received</h4>
                              <strong> {{ lang["neworder.success.id"] }}: </strong> {{ data['order']['id'] }} <br>
                              <strong> {{ lang["neworder.success.service"] }}: </strong> {{ data['order']['service'] }} <br>
                              <strong> {{ lang["neworder.success.link"] }}: </strong> {{ data['order']['link'] }} <br>
                              <strong> {{ lang["neworder.success.quantity"] }}: </strong> {{ data['order']['quantity'] }} <br>
                              <strong> {{ lang["neworder.success.charge"] }}: </strong> {{ currency['symbol'] }}{{ data['order']['price'] }} <br>
                              <strong> {{ lang["neworder.success.balance"] }}: </strong>{{ data['order']['balance'] }} <br>
                          </div>
                        {% endif %}

                        {% if settings.search_enabled == 1 %}
                            <div class="form-group mb-4">
                              <div class="search_services_content">
                                <div class="input-group">
                                  <input type="search" id="search_services_field" class="form-control form-control-lg" placeholder="Search by Service ID or Name" style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #fff;">
                                  <div class="input-group-append">
                                      <span class="input-group-text border-0" style="background: rgba(255,255,255,0.1); color: #fff;"><i class="fas fa-search"></i></span>
                                  </div>
                                </div>
                              </div>
                              <div id="dropdown_for_search" class="dropdown glass-dropdown" style="display: none; max-height: 300px; overflow-y: auto; margin-top: 5px;"></div>
                            </div>
                        {% endif %} 

                        <form method="post" action="">
                            
                            <!-- Category Select -->
                            <div class="form-group">
                                <label for="neworder_category" class="font-weight-bold" style="color: rgba(255,255,255,0.8);">{{ lang["neworder.category"] }}</label>
                                <select class="form-control form-control-lg" id="neworder_category" name="categories" style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #fff; height: 50px;">
                                    {{ category_html_simplify }}
                                </select>
                            </div>

                            <!-- Service Select -->
                            <div class="form-group">
                                <label for="neworder_services" class="font-weight-bold" style="color: rgba(255,255,255,0.8);">{{ lang["neworder.service"] }}</label>
                                <select class="form-control form-control-lg" id="neworder_services" name="services" style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #fff; height: 50px;">
                                    <option value="1">No services found in this category</option>
                                </select>
                            </div>

                            <!-- Custom Service Description Trigger -->
                            <div id="service_desc_trigger_wrapper" style="display:none; margin-bottom: 20px;">
                                <button type="button" class="btn btn-block" onclick="$('#serviceDetailModal').modal('show')" style="background: rgba(255,255,255,0.1); color: #fff; border: 1px solid rgba(255,255,255,0.2); border-radius: 10px; padding: 10px; font-weight: 600; transition: all 0.3s;">
                                    <i class="fas fa-list-alt mr-2"></i> Service Details
                                </button>
                            </div>

                            <!-- Dynamic Fields Container -->
                            <div id="neworder_fields"></div>

                            <!-- Charge Field -->
                            <div class="form-group" id="charge_div">
                                <label for="charge" class="font-weight-bold" style="color: rgba(255,255,255,0.8);">{{ lang["neworder.charge"] }}</label>
                                <input type="text" class="form-control form-control-lg" id="charge" readonly style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #fff; height: 50px;">
                            </div>

                            <!-- Terms Checkbox (Optional but good for UX) -->
                            <div class="form-group form-check mt-3">
                                <input type="checkbox" class="form-check-input" id="confirm_order" checked>
                                <label class="form-check-label" for="confirm_order" style="color: rgba(255,255,255,0.6);">I have confirmed my order, I have read and I confirm.</label>
                            </div>

                            <!-- Submit Button -->
                            <input type="hidden" name="csrf_token" value="{{ csrfToken }}">
                            <button type="submit" class="btn btn-danger btn-block btn-lg font-weight-bold mt-4 shadow" style="background: #ff0000; border: none; padding: 15px;">Place Order</button>
                        
                        </form>
                    </div>
                </div>

            </div>

            <!-- Right Column: Announcements -->
            <div class="col-lg-4">
                 
                 <!-- Announcements Tab Pill -->
                 <div class="mb-3">
                    <span class="badge badge-light px-3 py-2" style="font-size: 14px; background: #fff; color: #007bff;"><i class="fas fa-newspaper mr-1"></i> Announcements</span>
                 </div>

                 <!-- Announcements Card -->
                 {% if news %}
                 <div class="card border-0 shadow-lg" style="border-radius: 16px; min-height: 400px;">
                    <div class="card-body p-0">
                        <!-- Header for Table -->
                        <div class="d-flex justify-content-between p-3 border-bottom text-muted font-weight-bold small">
                            <span style="width: 25%">Title</span>
                            <span style="width: 50%">Content</span>
                            <span style="width: 25%" class="text-right">Date</span>
                        </div>
                        
                        <div class="news-list" style="max-height: 600px; overflow-y: auto;">
                           {% for new in news %}
                           <div class="news-item border-bottom p-3 hover-bg-light">
                               <div class="d-flex justify-content-between align-items-start">
                                   <!-- Title + Icon -->
                                   <div style="width: 25%" class="pr-2">
                                       <div class="badge badge-soft-primary mb-1">{{ new['news_title'] }}</div>
                                       {% if new['news_icon'] %}
                                        <img src="{{ new['news_icon'] }}" width="20" class="d-block mt-1">
                                       {% endif %}
                                   </div>
                                   
                                   <!-- Content -->
                                   <div style="width: 50%" class="text-muted small pr-2">
                                       {{ new['news_content'] }}
                                   </div>
                                   
                                   <!-- Date -->
                                   <div style="width: 25%" class="text-right small text-muted">
                                       {{ new['news_date'] }}
                                   </div>
                               </div>
                           </div>
                           {% endfor %}
                        </div>
                    </div>
                 </div>
                 {% endif %}

            </div>

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

<!-- Service Detail Modal (Bootstrap Style) -->
<div class="modal fade" id="serviceDetailModal" tabindex="-1" role="dialog" aria-labelledby="serviceDetailModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content" style="background: #fff; color: #333; border-radius: 8px;">
      <div class="modal-header" style="border-bottom: 1px solid #eee;">
        <h5 class="modal-title" id="serviceDetailModalLabel" style="font-weight: 600; color: #000;">Service Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true" style="color: #000;">&times;</span>
        </button>
      </div>
      <div class="modal-body text-left" id="serviceDetailModalBody" style="font-size: 14px; line-height: 1.6; color: #555;">
        <!-- Content injected via JS -->
      </div>
      <div class="modal-footer" style="border-top: 1px solid #eee;">
        <button type="button" class="btn btn-primary" data-dismiss="modal" style="background: #007bff; border-color: #007bff;">Create Order</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal" style="background: #6c757d; border-color: #6c757d;">Okay</button>
      </div>
    </div>
  </div>
</div>

<style>
    /* Hide original description and average time */
    #description, #average_time {
        display: none !important;
    }
    
    /* Modal Backdrop Blur */
    .modal-backdrop.show {
        opacity: 0.7 !important;
        backdrop-filter: blur(5px) !important;
        -webkit-backdrop-filter: blur(5px) !important;
    }
    
    /* Responsive Modal Card */
    #serviceDetailModal .modal-content {
        border: none;
        box-shadow: 0 15px 35px rgba(0,0,0,0.2);
    }

    /* Custom Dropdown Styles (Glassmorphism) */
    .custom-select-wrapper {
        position: relative;
        user-select: none;
        width: 100%;
    }
    .custom-select-trigger {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 22px;
        font-size: 16px;
        font-weight: 300;
        color: #fff; /* Text Color */
        height: 50px;
        line-height: 50px;
        background: rgba(255, 255, 255, 0.05); /* Glass Background */
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 8px; /* Slightly rounded */
        cursor: pointer;
        transition: all 0.3s ease;
    }
    .custom-select-trigger:hover {
        background: rgba(255, 255, 255, 0.08);
        border-color: rgba(255, 255, 255, 0.2);
    }
    .custom-select-trigger::after {
        content: '\25BC'; /* Down Arrow */
        font-size: 10px;
        transition: transform 0.3s;
    }
    .custom-select-wrapper.open .custom-select-trigger::after {
        transform: rotate(180deg);
    }
    .custom-options {
        position: absolute;
        display: block;
        top: 100%;
        left: 0;
        right: 0;
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-top: 0;
        background: rgba(20, 20, 30, 0.95); /* Dark Glass Background */
        backdrop-filter: blur(15px);
        -webkit-backdrop-filter: blur(15px);
        border-radius: 0 0 8px 8px;
        box-shadow: 0 10px 20px rgba(0,0,0,0.3);
        z-index: 100;
        opacity: 0;
        visibility: hidden;
        pointer-events: none;
        transform: translateY(-15px);
        transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55); /* Bounce effect */
        max-height: 300px;
        overflow-y: auto;
    }
    .custom-select-wrapper.open .custom-options {
        opacity: 1;
        visibility: visible;
        pointer-events: all;
        transform: translateY(10px); /* Small Gap */
    }
    .custom-option {
        position: relative;
        display: block;
        padding: 12px 22px; /* Increased padding */
        font-size: 14px;
        font-weight: 300;
        color: rgba(255, 255, 255, 0.8);
        border-bottom: 1px solid rgba(255, 255, 255, 0.05); /* Separator */
        cursor: pointer;
        transition: all 0.2s;
    }
    .custom-option:last-of-type {
        border-bottom: 0;
    }
    .custom-option:hover {
        background: rgba(255, 255, 255, 0.1);
        color: #fff;
        padding-left: 28px; /* Slide effect */
    }
    .custom-option.selected {
        background: rgba(255, 255, 255, 0.15); /* Highlight selected */
        color: #fff;
        font-weight: 500; /* Bold selected */
    }
    .custom-option-icon {
        display: inline-block;
        width: 20px;
        height: 20px;
        margin-right: 10px;
        vertical-align: middle;
        object-fit: contain;
    }

    /* Scrollbar styling for dropdown */
    .custom-options::-webkit-scrollbar {
        width: 8px;
    }
    .custom-options::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.05);
    }
    .custom-options::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.2);
        border-radius: 4px;
    }
    .custom-options::-webkit-scrollbar-thumb:hover {
        background: rgba(255, 255, 255, 0.4);
    }
</style>

<script>
    // Custom Select Implementation
    function createCustomSelect(selectElementId) {
        var elParams = typeof selectElementId === 'string' ? document.getElementById(selectElementId) : selectElementId;
        if (!elParams) return;
        
        // Hide original select element
        elParams.style.display = 'none';
        
        // Remove existing custom select if any (for updates)
        var parent = elParams.parentNode;
        var existingWrapper = parent.querySelector('.custom-select-wrapper');
        if (existingWrapper) {
            existingWrapper.remove();
        }

        // Create wrapper
        var wrapper = document.createElement('div');
        wrapper.className = 'custom-select-wrapper';
        
        // Create trigger (selected option display)
        var trigger = document.createElement('div');
        trigger.className = 'custom-select-trigger';
        var initialOption = elParams.options[elParams.selectedIndex];
        
        // Initial text - check data-content attribute first (PHP stores service names there)
        var initialText = 'Select Option';
        if (initialOption) {
            initialText = initialOption.getAttribute('data-content') || initialOption.text || initialOption.textContent || initialOption.innerHTML || 'Select Option';
        }
        trigger.innerHTML = '<span>' + initialText + '</span>';
        
        // Create options container
        var optionsDiv = document.createElement('div');
        optionsDiv.className = 'custom-options';
        
        // Loop through options
        Array.from(elParams.options).forEach(function(option, index) {
            var optionDiv = document.createElement('div');
            optionDiv.className = 'custom-option' + (index === elParams.selectedIndex ? ' selected' : '');
            optionDiv.setAttribute('data-value', option.value);
            // CRITICAL: PHP stores service display text in data-content attribute
            var optText = option.getAttribute('data-content') || option.text || option.textContent || option.innerHTML || '';
            optionDiv.innerHTML = optText;
            
            // Click handler
            optionDiv.addEventListener('click', function() {
                // Update trigger text
                trigger.querySelector('span').innerHTML = this.innerHTML;
                
                // Update original select value
                elParams.value = this.getAttribute('data-value');
                
                // Dispatch native event
                var nativeEvent = new Event('change', { bubbles: true });
                elParams.dispatchEvent(nativeEvent);
                
                // DIRECTLY call the AJAX functions from script.js
                // This is more reliable than event chains since jQuery may be re-loaded
                if (elParams.id === 'neworder_category') {
                    if (typeof category_detail === 'function') {
                        category_detail();
                    }
                } else if (elParams.id === 'neworder_services') {
                    if (typeof service_detail === 'function') {
                        service_detail();
                    }
                }
                
                // Also try jQuery trigger as backup
                if (typeof jQuery !== 'undefined') {
                    $(elParams).trigger('change');
                }
                
                // Update selected class
                optionsDiv.querySelectorAll('.custom-option').forEach(function(opt) {
                    opt.classList.remove('selected');
                });
                this.classList.add('selected');
                
                // Close dropdown
                wrapper.classList.remove('open');
            });
            
            optionsDiv.appendChild(optionDiv);
        });
        
        wrapper.appendChild(trigger);
        wrapper.appendChild(optionsDiv);
        
        // Insert wrapper after select
        elParams.parentNode.insertBefore(wrapper, elParams.nextSibling);
        
        // Toggle open/close
        trigger.addEventListener('click', function(e) {
            document.querySelectorAll('.custom-select-wrapper.open').forEach(function(otherWrapper) {
                if (otherWrapper !== wrapper) {
                    otherWrapper.classList.remove('open');
                }
            });
            wrapper.classList.toggle('open');
            e.stopPropagation();
        });
        
        // Close on click outside
        document.addEventListener('click', function(e) {
            if (!wrapper.contains(e.target)) {
                wrapper.classList.remove('open');
            }
        });
    }

    // Modal update function (service description / avg time)
    var descModalBody = document.getElementById('serviceDetailModalBody');
    var triggerWrapper = document.getElementById('service_desc_trigger_wrapper');

    function updateModal() {
        if (!descModalBody || !triggerWrapper) return;
        var combinedContent = '';
        var hasContent = false;
        
        var fieldsContainer = document.getElementById('neworder_fields');
        if (!fieldsContainer) return;

        var groups = fieldsContainer.querySelectorAll('.form-group');
        
        groups.forEach(function(group) {
            var hasInput = group.querySelector('input:not([type="hidden"]), select, textarea');
            var text = (group.textContent || group.innerText || '').trim();

            if (!hasInput && text.length > 0) {
                var inner = group.querySelector('.panel-body')?.innerHTML || group.innerHTML;
                
                if (text.toLowerCase().indexOf('average time') > -1) {
                    group.style.display = 'none';
                    combinedContent += '<div class="mb-3 p-3 rounded" style="background:rgba(245,245,245,1); color:#333; border: 1px solid #ddd;"><h6 class="text-primary" style="margin-top:0;"><i class="fas fa-clock mr-2"></i> Average Time</h6>' + inner + '</div>';
                    hasContent = true;
                } else {
                    if (group.id !== 'charge_div' && !group.classList.contains('hidden')) {
                        group.style.display = 'none';
                        inner = inner.replace(/<label.*?>.*?Description.*?<\/label>/i, '');
                        combinedContent += '<div class="mb-4">' + inner + '</div>';
                        hasContent = true;
                    }
                }
            }
        });

        if (hasContent) {
            if (descModalBody.innerHTML !== combinedContent) {
                descModalBody.innerHTML = combinedContent;
            }
            if (typeof jQuery !== 'undefined') {
                var serviceName = $('#neworder_services option:selected').text();
                if (serviceName) {
                    $('#serviceDetailModalLabel').text(serviceName);
                }
            }
            triggerWrapper.style.display = 'block';
        } else {
            triggerWrapper.style.display = 'none';
        }
    }

    // Initialize custom dropdowns + observers
    function initCustomDropdowns() {
        createCustomSelect('neworder_category');
        createCustomSelect('neworder_services');
        
        // Watch for AJAX updates to the services select (options change)
        var servicesSelect = document.getElementById('neworder_services');
        if (servicesSelect && !servicesSelect.dataset.observerSet) {
            var servicesObserver = new MutationObserver(function() {
                // Rebuild the custom services dropdown when AJAX updates options
                createCustomSelect('neworder_services');
                setTimeout(updateModal, 500);
            });
            
            servicesObserver.observe(servicesSelect, { 
                childList: true,
                subtree: true 
            });
            servicesSelect.dataset.observerSet = "true";
        }
    }

    // Boot everything on DOM ready
    if (typeof jQuery !== 'undefined') {
        $(document).ready(function() {
            initCustomDropdowns();
            setTimeout(initCustomDropdowns, 1000);
            setTimeout(initCustomDropdowns, 2500);

            // Watch for dynamic field changes (description, avg time)
            var bodyObserver = new MutationObserver(function() {
                bodyObserver.disconnect();
                updateModal();
                bodyObserver.observe(document.body, { childList: true, subtree: true });
            });
            bodyObserver.observe(document.body, { childList: true, subtree: true });

            // Bind to service select change for modal update
            $('#neworder_services').on('change', function() {
                setTimeout(updateModal, 500);
                setTimeout(updateModal, 1500);
            });

            setTimeout(updateModal, 1000);
        });
    } else {
        document.addEventListener("DOMContentLoaded", function() {
            initCustomDropdowns();
            setTimeout(initCustomDropdowns, 1000);
            setTimeout(updateModal, 1000);
        });
    }

    // CRITICAL: Also init after ALL scripts load (script.js loads in footer AFTER this)
    window.addEventListener('load', function() {
        setTimeout(function() {
            initCustomDropdowns();
            // Trigger initial category load if category_detail exists
            if (typeof category_detail === 'function') {
                category_detail();
            }
        }, 500);
    });
</script>

{% include 'footer.twig' %}