<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/classes/SMMProviderAPI.php';
requireLogin();

$auth = new Auth();
$userModel = new User();
$currentBalance = $auth->refreshBalance($_SESSION['user_id']);
$pdo = getDBConnection();

$error = '';
$success = '';

// Get active SMM categories (only ones you've enabled)
$categories = $pdo->query("SELECT * FROM smm_categories WHERE status = 'active' ORDER BY sort_order ASC, name ASC")->fetchAll();

// Get active SMM services (only ones you've enabled, and only from active categories)
$services = $pdo->query("
    SELECT s.* FROM smm_services s 
    INNER JOIN smm_categories c ON s.category_id = c.id 
    WHERE s.status = 'active' AND c.status = 'active' 
    ORDER BY c.sort_order ASC, s.custom_name ASC
")->fetchAll();

$api = new SMMProviderAPI();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'order') {
        $serviceId = intval($_POST['service_id'] ?? 0);
        $link = trim($_POST['link'] ?? '');
        $quantity = intval($_POST['quantity'] ?? 0);
        
        $stmt = $pdo->prepare("SELECT * FROM smm_services WHERE id = ? AND status = 'active'");
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch();
        
        if (!$service) {
            $error = 'Invalid service selected';
        } elseif (empty($link)) {
            $error = 'Please enter a valid link';
        } elseif ($quantity < $service['custom_min'] || $quantity > $service['custom_max']) {
            $error = "Quantity must be between {$service['custom_min']} and {$service['custom_max']}";
        } else {
            $totalPrice = ($service['custom_rate'] / 1000) * $quantity;
            
            if ($currentBalance < $totalPrice) {
                $error = 'Insufficient balance. Please add funds.';
            } elseif (!$api->hasApiKey()) {
                $error = 'SMM API not configured. Please contact admin.';
            } else {
                $result = $api->createOrder($service['api_service_id'], $link, $quantity);
                
                if (isset($result['order'])) {
                    $userModel->updateBalance($_SESSION['user_id'], $totalPrice, 'subtract');
                    $currentBalance = $auth->refreshBalance($_SESSION['user_id']);
                    
                    $stmt = $pdo->prepare("INSERT INTO smm_orders (user_id, service_id, api_order_id, link, quantity, charge, status, created_at) VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())");
                    $stmt->execute([
                        $_SESSION['user_id'],
                        $serviceId,
                        $result['order'],
                        $link,
                        $quantity,
                        $totalPrice
                    ]);
                    
                    $success = 'Order placed successfully! Order ID: ' . $result['order'];
                } else {
                    $error = 'Order failed: ' . ($result['error'] ?? json_encode($result));
                }
            }
        }
    }
}

// Group services by category
$servicesByCategory = [];
foreach ($services as $service) {
    $catId = $service['category_id'] ?? 0;
    $servicesByCategory[$catId][] = $service;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMM Service - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #0A1628; color: #fff; min-height: 100vh; }
        .header { background: #0F2744; padding: 1rem; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 100; }
        .header-logo { display: flex; align-items: center; gap: 0.5rem; color: #F5A623; font-weight: 700; }
        .header-logo img { width: 48px; height: 48px; min-width: 48px; min-height: 48px; object-fit: contain; }
        .header-balance { background: #F5A623; color: #0A1628; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; }
        .hamburger { background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }
        .menu-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 200; display: none; }
        .menu-overlay.active { display: block; }
        .side-menu { position: fixed; top: 0; left: -280px; width: 280px; height: 100%; background: #0F2744; z-index: 300; transition: left 0.3s; padding: 1.5rem 0; overflow-y: auto; }
        .side-menu.active { left: 0; }
        .menu-header { display: flex; justify-content: space-between; align-items: center; padding: 0 1.5rem 1.5rem; border-bottom: 1px solid #1E3A5F; }
        .menu-close { background: none; border: none; color: #9CA3AF; font-size: 1.5rem; cursor: pointer; }
        .menu-items { padding: 1rem 0; }
        .menu-item { display: flex; align-items: center; gap: 1rem; padding: 1rem 1.5rem; color: #E5E7EB; text-decoration: none; }
        .menu-item:hover, .menu-item.active { background: #1E3A5F; color: #F5A623; }
        .menu-item i { width: 20px; text-align: center; }
        .menu-divider { height: 1px; background: #1E3A5F; margin: 0.5rem 1.5rem; }
        .content { padding: 1rem; max-width: 900px; margin: 0 auto; padding-bottom: 80px; }
        .page-title { font-size: 1.25rem; margin-bottom: 1rem; }
        .page-title i { color: #F5A623; }
        .card { background: #0F2744; border-radius: 12px; padding: 1.5rem; margin-bottom: 1rem; }
        .card-title { font-size: 1rem; color: #F5A623; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; }
        .form-group { margin-bottom: 1rem; }
        .form-label { display: block; color: #E5E7EB; margin-bottom: 0.5rem; font-size: 0.9rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; background: #0A1628; border: 1px solid #1E3A5F; border-radius: 8px; color: #fff; font-size: 1rem; }
        .form-control:focus { outline: none; border-color: #F5A623; }
        .btn { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1.5rem; border: none; border-radius: 8px; font-size: 1rem; font-weight: 600; cursor: pointer; }
        .btn-gold { background: #F5A623; color: #0A1628; width: 100%; justify-content: center; }
        .btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .alert { padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1rem; }
        .alert-success { background: rgba(16,185,129,0.2); border: 1px solid #10B981; color: #10B981; }
        .alert-danger { background: rgba(239,68,68,0.2); border: 1px solid #EF4444; color: #EF4444; }
        .service-info { background: #0A1628; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; display: none; }
        .service-info.active { display: block; }
        .service-detail { display: flex; justify-content: space-between; margin-bottom: 0.5rem; color: #9CA3AF; font-size: 0.9rem; }
        .service-detail span:last-child { color: #F5A623; font-weight: 600; }
        .total-price { font-size: 1.5rem; font-weight: 700; color: #F5A623; text-align: center; margin: 1rem 0; padding: 1rem; background: #0A1628; border-radius: 8px; }
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: #0F2744; display: flex; justify-content: space-around; padding: 0.75rem 0; border-top: 1px solid #1E3A5F; z-index: 100; }
        .bottom-nav a { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: #9CA3AF; font-size: 0.7rem; gap: 0.25rem; }
        .bottom-nav a i { font-size: 1.25rem; }
        .bottom-nav a.active { color: #F5A623; }

        /* Search Styles */
        .search-box { position: relative; margin-bottom: 1rem; }
        .search-box input {
            width: 100%;
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            background: #0A1628;
            border: 1px solid #1E3A5F;
            border-radius: 8px;
            color: #fff;
            font-size: 1rem;
        }
        .search-box input:focus { outline: none; border-color: #F5A623; }
        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #9CA3AF;
        }
        .search-box .clear-btn {
            position: absolute;
            right: 0.75rem;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #9CA3AF;
            cursor: pointer;
            padding: 0.25rem;
            display: none;
        }
        .search-box .clear-btn.visible { display: block; }
        .no-results {
            text-align: center;
            padding: 1rem;
            color: #9CA3AF;
            font-size: 0.9rem;
            display: none;
        }
        .no-results.visible { display: block; }

        /* Custom Category Dropdown */
        .custom-select-wrapper { position: relative; }
        .custom-select-trigger {
            width: 100%;
            padding: 0.75rem 1rem;
            background: #0A1628;
            border: 1px solid #1E3A5F;
            border-radius: 8px;
            color: #fff;
            font-size: 1rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.6rem;
            justify-content: space-between;
            user-select: none;
        }
        .custom-select-trigger:hover { border-color: #F5A623; }
        .custom-select-trigger.open { border-color: #F5A623; }
        .trigger-left { display: flex; align-items: center; gap: 0.6rem; }
        .trigger-left i { font-size: 1rem; width: 18px; text-align: center; flex-shrink: 0; }
        .custom-dropdown {
            display: none;
            position: absolute;
            top: calc(100% + 4px);
            left: 0; right: 0;
            background: #0A1628;
            border: 1px solid #1E3A5F;
            border-radius: 8px;
            z-index: 500;
            max-height: 260px;
            overflow-y: auto;
            box-shadow: 0 4px 20px rgba(0,0,0,0.4);
        }
        .custom-dropdown.open { display: block; }
        .custom-dropdown-item {
            display: flex;
            align-items: center;
            gap: 0.6rem;
            padding: 0.75rem 1rem;
            cursor: pointer;
            color: #E5E7EB;
            font-size: 0.95rem;
            border-bottom: 1px solid #1E3A5F;
        }
        .custom-dropdown-item:last-child { border-bottom: none; }
        .custom-dropdown-item:hover { background: #1E3A5F; color: #F5A623; }
        .custom-dropdown-item.selected { background: rgba(245,166,35,0.1); color: #F5A623; }
        .custom-dropdown-item i { font-size: 1rem; width: 18px; text-align: center; flex-shrink: 0; }
    </style>
    <link rel="stylesheet" href="/assets/css/premium-dark.css">
</head>
<body>
    <header class="header">
        <button class="hamburger" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
        <div class="header-logo"><img src="/assets/images/logo.png" alt="<?php echo SITE_NAME; ?>"></div>
        <div class="header-balance"><?php echo formatCurrency($currentBalance); ?></div>
    </header>
    <div class="menu-overlay" id="menuOverlay" onclick="toggleMenu()"></div>
    <nav class="side-menu" id="sideMenu">
        <div class="menu-header">
            <div class="header-logo"><img src="/assets/images/logo.png" alt="<?php echo SITE_NAME; ?>"></div>
            <button class="menu-close" onclick="toggleMenu()"><i class="fas fa-times"></i></button>
        </div>
        <div class="menu-items">
            <a href="dashboard.php" class="menu-item"><i class="fas fa-home"></i> Dashboard</a>
            <a href="sms.php" class="menu-item"><i class="fas fa-sms"></i> SMS Service</a>
            <a href="smm.php" class="menu-item active"><i class="fas fa-rocket"></i> SMM Service</a>
            <a href="banner.php" class="menu-item"><i class="fas fa-ad"></i> Banner Service</a>
            <a href="orders.php" class="menu-item"><i class="fas fa-history"></i> Orders</a>
            <a href="add-funds.php" class="menu-item"><i class="fas fa-wallet"></i> Add Funds</a>
            <a href="transactions.php" class="menu-item"><i class="fas fa-exchange-alt"></i> Transactions</a>
            <a href="profile.php" class="menu-item"><i class="fas fa-user"></i> Profile</a>
            <div class="menu-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="menu-item"><i class="fas fa-sign-out-alt"></i> Log Out</a>
        </div>
    </nav>
    <main class="content">
        <h1 class="page-title"><i class="fas fa-rocket"></i> SMM Service</h1>
        
        <?php if ($error): ?><div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
        
        <div class="card">
            <h3 class="card-title"><i class="fas fa-shopping-cart"></i> New Order</h3>
            <form method="POST" id="orderForm">
                <?php echo csrfTokenField(); ?>
                <input type="hidden" name="action" value="order">
                
                <!-- Search Box -->
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="categorySearch" placeholder="Search categories..." oninput="searchCategories()">
                    <button type="button" class="clear-btn" id="clearSearch" onclick="clearSearch()"><i class="fas fa-times"></i></button>
                </div>
                <div class="no-results" id="noResults">No categories found</div>

                <!-- Custom Category Dropdown -->
                <div class="form-group">
                    <label class="form-label">Select Category</label>
                    <div class="custom-select-wrapper" id="categoryWrapper">
                        <div class="custom-select-trigger" id="categoryTrigger" onclick="toggleCategoryDropdown()">
                            <div class="trigger-left">
                                <i class="fas fa-th-large" id="triggerIcon" style="color:#F5A623;"></i>
                                <span id="triggerLabel">All Categories</span>
                            </div>
                            <i class="fas fa-chevron-down" style="color:#9CA3AF;font-size:0.8rem;"></i>
                        </div>
                        <div class="custom-dropdown" id="categoryDropdown">
                            <div class="custom-dropdown-item selected" data-id="" onclick="selectCategory(this)">
                                <i class="fas fa-th-large" style="color:#F5A623;"></i>
                                <span>All Categories</span>
                            </div>
                            <?php foreach ($categories as $category): 
                                $icon = !empty($category['icon']) ? $category['icon'] : 'fas fa-folder';
                                $iconColor = !empty($category['icon_color']) ? $category['icon_color'] : '#9CA3AF';
                            ?>
                            <div class="custom-dropdown-item"
                                data-id="<?php echo $category['id']; ?>"
                                data-name="<?php echo strtolower(htmlspecialchars($category['name'])); ?>"
                                data-icon="<?php echo htmlspecialchars($icon); ?>"
                                data-color="<?php echo htmlspecialchars($iconColor); ?>"
                                onclick="selectCategory(this)">
                                <i class="<?php echo htmlspecialchars($icon); ?>" style="color:<?php echo htmlspecialchars($iconColor); ?>;"></i>
                                <span><?php echo htmlspecialchars($category['name']); ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Select Service</label>
                    <select name="service_id" id="serviceSelect" class="form-control" required onchange="updateServiceInfo()">
                        <option value="">Choose a service...</option>
                        <?php foreach ($services as $service): ?>
                        <option value="<?php echo $service['id']; ?>" 
                                data-category="<?php echo $service['category_id']; ?>"
                                data-rate="<?php echo $service['custom_rate']; ?>"
                                data-min="<?php echo $service['custom_min']; ?>"
                                data-max="<?php echo $service['custom_max']; ?>"
                                data-desc="<?php echo htmlspecialchars($service['description'] ?? ''); ?>">
                            <?php echo htmlspecialchars($service['custom_name']); ?> - $<?php echo number_format($service['custom_rate'], 2); ?>/1K
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="service-info" id="serviceInfo">
                    <div class="service-detail"><span>Price per 1000:</span> <span id="infoPrice">-</span></div>
                    <div class="service-detail"><span>Min Quantity:</span> <span id="infoMin">-</span></div>
                    <div class="service-detail"><span>Max Quantity:</span> <span id="infoMax">-</span></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Link</label>
                    <input type="url" name="link" id="linkInput" class="form-control" placeholder="https://instagram.com/username" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Quantity</label>
                    <input type="number" name="quantity" id="quantityInput" class="form-control" placeholder="Enter quantity" required onchange="calculateTotal()" oninput="calculateTotal()">
                </div>
                
                <div class="total-price" id="totalPrice">Total: $0.00</div>
                
                <button type="submit" class="btn btn-gold" id="orderBtn" disabled><i class="fas fa-paper-plane"></i> Place Order</button>
            </form>
        </div>
    </main>
    <nav class="bottom-nav">
        <a href="dashboard.php"><i class="fas fa-home"></i> Home</a>
        <a href="sms.php"><i class="fas fa-sms"></i> SMS</a>
        <a href="smm.php" class="active"><i class="fas fa-rocket"></i> SMM</a>
        <a href="orders.php"><i class="fas fa-history"></i> Orders</a>
        <a href="profile.php"><i class="fas fa-user"></i> Profile</a>
    </nav>
    <script>
        function toggleMenu() { 
            document.getElementById('sideMenu').classList.toggle('active'); 
            document.getElementById('menuOverlay').classList.toggle('active'); 
        }
        
        var currentService = null;
        var userBalance = <?php echo $currentBalance; ?>;
        var selectedCategoryId = '';

        // Store ALL services in JS for dynamic filtering
        var allServices = [
            <?php foreach ($services as $service): ?>
            {
                id: '<?php echo $service['id']; ?>',
                categoryId: '<?php echo $service['category_id']; ?>',
                name: <?php echo json_encode($service['custom_name'] . ' - $' . number_format($service['custom_rate'], 2) . '/1K'); ?>,
                rate: <?php echo $service['custom_rate']; ?>,
                min: <?php echo $service['custom_min']; ?>,
                max: <?php echo $service['custom_max']; ?>,
                desc: <?php echo json_encode($service['description'] ?? ''); ?>
            },
            <?php endforeach; ?>
        ];

        // Custom dropdown functions
        function toggleCategoryDropdown() {
            var dropdown = document.getElementById('categoryDropdown');
            var trigger = document.getElementById('categoryTrigger');
            dropdown.classList.toggle('open');
            trigger.classList.toggle('open');
        }

        function selectCategory(item) {
            // Update selected state
            document.querySelectorAll('.custom-dropdown-item').forEach(function(i) { i.classList.remove('selected'); });
            item.classList.add('selected');

            // Update trigger display
            var iconEl = item.querySelector('i');
            var nameEl = item.querySelector('span');
            var triggerIcon = document.getElementById('triggerIcon');
            triggerIcon.className = (iconEl ? iconEl.className : 'fas fa-folder');
            triggerIcon.style.color = iconEl ? iconEl.style.color : '#F5A623';
            document.getElementById('triggerLabel').textContent = nameEl ? nameEl.textContent : 'All Categories';

            // Close dropdown
            document.getElementById('categoryDropdown').classList.remove('open');
            document.getElementById('categoryTrigger').classList.remove('open');

            // Set selected category and filter services
            selectedCategoryId = item.dataset.id || '';
            filterServices();
        }

        // Close dropdown when clicking outside
        document.addEventListener('click', function(e) {
            var wrapper = document.getElementById('categoryWrapper');
            if (wrapper && !wrapper.contains(e.target)) {
                document.getElementById('categoryDropdown').classList.remove('open');
                document.getElementById('categoryTrigger').classList.remove('open');
            }
        });

        // Search categories - filters the custom dropdown items
        function searchCategories() {
            var searchInput = document.getElementById('categorySearch');
            var searchTerm = searchInput.value.toLowerCase().trim();
            var clearBtn = document.getElementById('clearSearch');
            var noResults = document.getElementById('noResults');

            clearBtn.classList.toggle('visible', searchTerm.length > 0);

            var items = document.querySelectorAll('.custom-dropdown-item');
            var visibleCount = 0;

            items.forEach(function(item) {
                // Always show "All Categories"
                if (!item.dataset.id) { item.style.display = ''; return; }
                var name = (item.dataset.name || '').toLowerCase();
                if (!searchTerm || name.includes(searchTerm)) {
                    item.style.display = '';
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            });

            noResults.classList.toggle('visible', searchTerm.length > 0 && visibleCount === 0);

            // Open dropdown while searching
            if (searchTerm.length > 0) {
                document.getElementById('categoryDropdown').classList.add('open');
                document.getElementById('categoryTrigger').classList.add('open');
            }

            // Auto-select if exactly one match
            if (searchTerm.length > 0) {
                var visible = Array.from(items).filter(function(b) {
                    return b.dataset.id && b.style.display !== 'none';
                });
                if (visible.length === 1) {
                    selectCategory(visible[0]);
                }
            }
        }

        // Clear search
        function clearSearch() {
            document.getElementById('categorySearch').value = '';
            searchCategories();
            document.getElementById('categoryDropdown').classList.remove('open');
            document.getElementById('categoryTrigger').classList.remove('open');
        }

        // Rebuild service dropdown based on selected category
        function filterServices() {
            var serviceSelect = document.getElementById('serviceSelect');

            var filtered = selectedCategoryId
                ? allServices.filter(function(s) { return s.categoryId === selectedCategoryId; })
                : allServices;

            serviceSelect.innerHTML = '<option value="">Choose a service...</option>';
            filtered.forEach(function(s) {
                var opt = document.createElement('option');
                opt.value = s.id;
                opt.textContent = s.name;
                opt.dataset.category = s.categoryId;
                opt.dataset.rate = s.rate;
                opt.dataset.min = s.min;
                opt.dataset.max = s.max;
                opt.dataset.desc = s.desc;
                serviceSelect.appendChild(opt);
            });

            updateServiceInfo();
        }
        
        function updateServiceInfo() {
            var serviceSelect = document.getElementById('serviceSelect');
            var selected = serviceSelect.options[serviceSelect.selectedIndex];
            var infoBox = document.getElementById('serviceInfo');
            var orderBtn = document.getElementById('orderBtn');
            
            if (!selected || !selected.value) {
                infoBox.classList.remove('active');
                currentService = null;
                document.getElementById('quantityInput').value = '';
                orderBtn.disabled = true;
                calculateTotal();
                return;
            }
            
            currentService = {
                rate: parseFloat(selected.dataset.rate),
                min: parseInt(selected.dataset.min),
                max: parseInt(selected.dataset.max)
            };
            
            document.getElementById('infoPrice').textContent = '$' + currentService.rate.toFixed(2);
            document.getElementById('infoMin').textContent = currentService.min.toLocaleString();
            document.getElementById('infoMax').textContent = currentService.max.toLocaleString();
            
            var qtyInput = document.getElementById('quantityInput');
            qtyInput.min = currentService.min;
            qtyInput.max = currentService.max;
            qtyInput.placeholder = currentService.min + ' - ' + currentService.max;
            
            infoBox.classList.add('active');
            calculateTotal();
        }
        
        function calculateTotal() {
            var qty = parseInt(document.getElementById('quantityInput').value) || 0;
            var total = 0;
            var orderBtn = document.getElementById('orderBtn');
            
            if (currentService && qty > 0) {
                total = (currentService.rate / 1000) * qty;
            }
            
            document.getElementById('totalPrice').textContent = 'Total: $' + total.toFixed(2);
            
            if (currentService && qty >= currentService.min && qty <= currentService.max && total <= userBalance) {
                orderBtn.disabled = false;
            } else {
                orderBtn.disabled = true;
            }
        }
    </script>
</body>
</html>