<?php include 'header.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">

<style>
    body { font-family: 'Plus Jakarta Sans', sans-serif; background: #f0f2f5; }
    
    /* 🌟 NEW GRID BOX DESIGN (Like your image) */
    .vip-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 30px; }
    .stat-card { border-radius: 15px; padding: 25px; color: #fff; position: relative; overflow: hidden; box-shadow: 0 10px 20px rgba(0,0,0,0.1); transition: 0.3s; border: none; }
    .stat-card:hover { transform: translateY(-5px); }
    .stat-card i { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); font-size: 50px; opacity: 0.2; }
    .stat-card h3 { font-size: 28px; font-weight: 800; margin: 5px 0; }
    .stat-card p { font-size: 14px; font-weight: 600; margin: 0; text-transform: uppercase; letter-spacing: 1px; }
    
    /* Card Colors */
    .bg-blue { background: linear-gradient(135deg, #007bff, #0056b3); }
    .bg-orange { background: linear-gradient(135deg, #ff9800, #f57c00); }
    .bg-green { background: linear-gradient(135deg, #28a745, #1e7e34); }
    .bg-red { background: linear-gradient(135deg, #dc3545, #a71d2a); }

    .glass-card { background: #fff; border-radius: 20px; border: 1px solid #eee; box-shadow: 0 8px 25px rgba(0,0,0,0.05); margin-bottom: 25px; overflow: hidden; }
    .header-vip { background: linear-gradient(135deg, #00b09b, #96c93d); color: #fff; padding: 20px; font-weight: 700; font-size: 18px; }
    
    .vip-input { border: 2px solid #edf2f7; border-radius: 12px; padding: 12px; transition: 0.3s; font-size: 14px; background: #f8fafc; width: 100%; }
    .vip-input:focus { border-color: #00b09b; background: #fff; box-shadow: 0 0 0 4px rgba(0,176,155,0.1); outline: none; }

    /* Search Box UI (Fixed) */
    .search-container { position: relative; padding: 25px; background: #fff; border-bottom: 1px solid #f1f1f1; }
    .search-container i { position: absolute; left: 40px; top: 42px; color: #00b09b; font-size: 20px; z-index: 10; }
    .search-input { padding-left: 55px !important; height: 55px; border-radius: 18px; border: 2px solid #00b09b !important; font-size: 16px; font-weight: 600; width: 100%; }

    .btn-vip { border-radius: 12px; font-weight: 600; padding: 10px 18px; transition: 0.3s; border: none; }
    .btn-buy-api { background: #ffc107; color: #000; box-shadow: 0 4px 10px rgba(255,193,7,0.3); animation: pulse 2s infinite; }
    @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.05); } 100% { transform: scale(1); } }
    
    /* Collapsible Info */
    .api-info { background: #fff9e6; border: 1px dashed #ffc107; border-radius: 12px; padding: 15px; margin-top: 15px; display: none; }
    .badge-price { background: #e6f7f4; color: #00b09b; font-weight: 700; padding: 4px 10px; border-radius: 8px; }
</style>

<div class="container-fluid" style="margin-top: 25px;">

    <div class="vip-grid">
        <div class="stat-card bg-blue">
            <p>Total Services</p>
            <h3><?= count($new_services) ?></h3>
            <i class="fa fa-list-alt"></i>
        </div>
        <div class="stat-card bg-orange">
            <p>API Health</p>
            <h3 id="apiHealth">---</h3>
            <i class="fa fa-heartbeat"></i>
        </div>
        <div class="stat-card bg-green">
            <p>Sender Status</p>
            <h3>ACTIVE</h3>
            <i class="fab fa-whatsapp"></i>
        </div>
        <div class="stat-card bg-red">
            <p>Channel URL</p>
            <h3 style="font-size: 18px;"><?= ($settings['channel_url'] ? 'CONNECTED' : 'MISSING') ?></h3>
            <i class="fa fa-link"></i>
        </div>
    </div>

    <div class="glass-card">
        <div class="header-vip d-flex justify-content-between align-items-center">
            <span><i class="fa fa-robot"></i> Advanced Engine Configuration</span>
            <div class="d-flex align-items-center">
                <button onclick="$('.api-info').slideToggle()" class="btn btn-sm btn-light mr-3 font-weight-bold">Why API Buy?</button>
                <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" id="autoPost" <?= ($settings['auto_post'] == '1') ? 'checked' : '' ?> onchange="toggleAuto(this)">
                    <label class="custom-control-label text-white" for="autoPost">AUTO POST</label>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="api-info mb-3">
                <strong>💡 Why you need to Buy API?</strong><br>
                व्हाट्सएप चैनल ब्रॉडकास्ट सिस्टम MPWA API पर चलता है। जब आप API खरीदते हैं, तो आपका number व्हाट्सएप सर्वर से जुड़ जाता है जिससे बिना ब्लॉक हुए मैसेजेस और अपडेट्स भेज सकते हैं। 🚀
            </div>
            <form id="settingForm">
                <div class="row">
                    <div class="col-md-3"><label class="small font-weight-bold">MPWA API KEY</label><input type="text" name="api" class="form-control vip-input" value="<?= $settings['api_key'] ?>" id="apiKey"></div>
                    <div class="col-md-2"><label class="small font-weight-bold">SENDER NUMBER</label><input type="text" name="sender" class="form-control vip-input" value="<?= $settings['sender_number'] ?>" id="senderNum"></div>
                    <div class="col-md-3"><label class="small font-weight-bold">CHANNEL URL</label><input type="text" name="url" class="form-control vip-input" value="<?= $settings['channel_url'] ?>" id="targetUrl"></div>
                    <div class="col-md-2"><label class="small font-weight-bold">FOOTER TEXT</label><input type="text" name="footer" class="form-control vip-input" value="<?= $settings['footer_text'] ?>"></div>
                    <div class="col-md-2"><label>&nbsp;</label>
                        <div class="d-flex">
                            <button type="button" onclick="saveConfig()" class="btn btn-vip btn-save mr-1"><i class="fa fa-save"></i></button>
                            <button type="button" onclick="testSender()" class="btn btn-vip btn-test mr-1"><i class="fa fa-paper-plane"></i></button>
                            <a href="https://ads.alixdeal.info/en" target="_blank" class="btn btn-vip btn-buy-api w-100"><i class="fa fa-shopping-cart"></i> BUY API</a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="glass-card">
        <div class="search-container">
            <i class="fa fa-search"></i>
            <input type="text" id="mainSearch" class="search-input" placeholder="Type Service ID or Name (e.g. 3539 or Instagram Followers)...">
        </div>
        <div class="table-responsive">
            <table class="table table-hover mb-0" id="serviceDataTable">
                <thead class="bg-light text-uppercase small font-weight-bold">
                    <tr>
                        <th width="10%">ID</th>
                        <th width="50%">Service Name</th>
                        <th width="15%">Price</th>
                        <th width="25%" class="text-right">Actions</th>
                    </tr>
                </thead>
                <tbody id="serviceListBody">
                    <?php foreach($new_services as $log): ?>
                    <tr class="search-row">
                        <td class="text-muted">#<?= $log['service_id'] ?></td>
                        <td><b class="text-dark"><?= $log['service_name'] ?></b></td>
                        <td><span class="badge-price">₹<?= number_format((float)$log['service_price'], 2) ?></span></td>
                        <td class="text-right"> 
                            <button onclick="sendToTopAlert('<?= $log['service_id'] ?>')" class="btn btn-sm btn-light border mr-1" style="background: #111424;" title="Add to Frontend Updates"><i class="fa fa-bell text-warning"></i></button>
                            <button onclick="copyLink('<?= $log['service_id'] ?>')" class="btn btn-sm btn-light border mr-1"><i class="fa fa-copy text-info"></i></button>
                            <button onclick="editService('<?= $log['service_id'] ?>','<?= addslashes($log['service_name']) ?>','<?= $log['service_price'] ?>')" class="btn btn-sm btn-vip mr-1" style="background:#ffc107; color:#000;"><i class="fa fa-edit"></i> Edit</button> 
                            <button onclick="openBroadcastMenu('<?= $log['service_id'] ?>','<?= addslashes($log['service_name']) ?>','<?= $log['service_price'] ?>')" class="btn btn-sm btn-success btn-vip"><i class="fa fa-paper-plane"></i> Send</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){
    $("#mainSearch").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#serviceListBody tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });
    checkAPIStatus();
});

// 🔥 [COMPLETE SYSTEM LOGIC: REAL CONFIRMATION POPUP WITH VALIDATED SQL CHECK]
function sendToTopAlert(serviceId) {
    Swal.fire({
        title: 'Confirm Dynamic Action?',
        html: `<div style="text-align: left; background: #0f172a; padding: 12px; border-radius: 8px; color: #cbd5e0; font-size: 13px;">
                <b>Service ID:</b> <span style="color: #00f0ff;">#${serviceId}</span><br><br>
                <b>Yeh kahan jayega?</b><br>
                ➔ Yeh data direct user ke New Order page ke <b>"Updates Log Box"</b> me chala jayega.
               </div>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#00b09b',
        cancelButtonColor: '#dc3545',
        confirmButtonText: '🚀 Haan, Updates me dalo!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({ 
                title: 'Syncing to Database...', 
                html: 'Please wait, sync ho raha hai...',
                didOpen: () => { Swal.showLoading() } 
            });
            
            // Sending request dynamically to local admin controller action route
            $.post('', { action: 'add_top_service_action', service_id: serviceId, is_ajax: 1 }, function(data) {
                Swal.close();
                try {
                    let response = JSON.parse(data);
                    if (response.status == "success") {
                        Swal.fire({ 
                            icon: 'success', 
                            title: 'Successfully Updated!', 
                            text: 'Service #' + serviceId + ' updates list me sync ho gayi hai.', 
                            confirmButtonColor: '#00b09b' 
                        });
                    } else if (response.status == "exists") {
                        Swal.fire({ 
                            icon: 'info', 
                            title: 'Already Exists!', 
                            text: 'Yeh service pehle se hi Top Updates list me shamil hai.', 
                            confirmButtonColor: '#ffc107' 
                        });
                    } else {
                        Swal.fire({ 
                            icon: 'error', 
                            title: 'SQL Error!', 
                            text: 'Database syncing me dikkat aayi hai.', 
                            confirmButtonColor: '#dc3545' 
                        });
                    }
                } catch(e) {
                    Swal.fire({ 
                        icon: 'error', 
                        title: 'Format Error!', 
                        text: 'Backend engine dynamic response handle nahi kar paya.', 
                        confirmButtonColor: '#dc3545' 
                    });
                }
            });
        }
    });
}

function checkAPIStatus() {
    let key = $('#apiKey').val();
    if(!key) { $('#apiHealth').text('OFFLINE').css('color', '#fff'); return; }
    $.post('admin/whatsapp_settings', { action: 'test', is_ajax: 1 }, function(data) {
        try {
            let res = JSON.parse(data);
            if(res.status) { $('#apiHealth').text('PERFECT').css('color', '#fff'); } 
            else { $('#apiHealth').text('ERROR').css('color', '#fff'); }
        } catch(e) { $('#apiHealth').text('ERROR').css('color', '#fff'); }
    });
}

async function openBroadcastMenu(sid, name, price) {
    const { value: template } = await Swal.fire({
        title: 'Select Message Style',
        input: 'select',
        inputOptions: { '1': 'Emoji Star ⭐ (Flashy)', '2': 'Fire Alert 🔥 (Hot)', '3': 'Official ✅ (Clean)' },
        showCancelButton: true
    });

    if (template) {
        let msg = ""; let footer = "<?= addslashes($settings['footer_text']) ?>";
        if(template == '1') msg = `⭐ *NEW SERVICE ADDED* ⭐\n\n🆔 ID: #${sid}\n📋 Service: ${name}\n💰 Price: ₹${price}\n\n🛒 Order Now: alixdeal.shop`;
        if(template == '2') msg = `🔥 *HOT NEW SERVICE* 🔥\n\n🔹 *Name:* ${name}\n🔸 *Price:* ₹${price}\n🆔 *ID:* #${sid}\n\n🔗 Order: alixdeal.shop`;
        if(template == '3') msg = `📢 *OFFICIAL UPDATE*\n\n✅ *Service:* ${name}\n💸 *Rate:* ₹${price}/1k\n🆔 *ID:* #${sid}\n\n🛒 alixdeal.shop`;

        const { value: text } = await Swal.fire({
            title: 'Confirm Message',
            input: 'textarea',
            inputValue: msg + "\n\n" + footer,
            showCancelButton: true,
            confirmButtonText: '🚀 Broadcast Now'
        });
        if (text) sendBroadcast(text);
    }
}

function sendBroadcast(msg) {
    Swal.fire({ title: 'Broadcasting...', didOpen: () => { Swal.showLoading() } });
    $.post('', { action: 'send_new_service', manual_msg: msg, is_ajax: 1 }, function(data) {
        try {
            let res = JSON.parse(data);
            if(res.status) Swal.fire('Delivered!', 'Successfully posted to channel.', 'success');
            else Swal.fire('Error', 'Check API Connection.', 'error');
        } catch(e) { Swal.fire('Delivered!', 'Successfully executed.', 'success'); }
    });
}

function copyLink(id) {
    let url = "<?= site_url('services?id=') ?>" + id;
    navigator.clipboard.writeText(url);
    const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 1500 });
    Toast.fire({ icon: 'success', title: 'Link Copied: ' + id });
}

function saveConfig() {
    let data = $('#settingForm').serialize() + '&action=save_settings&is_ajax=1';
    $.post('', data, function() {
        Swal.fire({ icon: 'success', title: 'Config Saved!', timer: 1000, showConfirmButton: false });
        checkAPIStatus();
    });
}

function testSender() {
    Swal.fire({
        title: 'Quick Test',
        input: 'text',
        inputPlaceholder: 'Type a hello message...',
        showCancelButton: true
    }).then((res) => { if (res.isConfirmed && res.value) sendBroadcast(res.value); });
}

async function editService(sid, name, price) {
    const { value: formValues } = await Swal.fire({
        title: 'Modify Details',
        html: `<div class='text-left small'>Name:</div><input id="sw-n" class="swal2-input" value="${name}"><div class='text-left small'>Price:</div><input id="sw-p" class="swal2-input" value="${price}">`,
        showCancelButton: true,
        preConfirm: () => { return [document.getElementById('sw-n').value, document.getElementById('sw-p').value] }
    });
    if (formValues) openBroadcastMenu(sid, formValues[0], formValues[1]);
}

function toggleAuto(el) {
    $.post('', { action: 'toggle_auto', value: el.checked ? 1 : 0, is_ajax: 1 });
}
</script>
<?php include 'footer.php'; ?>