<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | Server1 (smspva) Services";

// Fetch all smspva countries
try {
    $stmt_countries = $pdo->query(
        "SELECT s.*, (SELECT COUNT(*) FROM smspva_service ss WHERE ss.smspva_server_id = s.id) AS svc_count
           FROM smspva_server s
          ORDER BY s.country_name ASC"
    );
    $countries = $stmt_countries->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $countries = []; }

// Price settings for display
try {
    $ps = $pdo->query("SELECT setting_key, setting_value FROM price_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (PDOException $e) { $ps = []; }
$markup_pct = $ps['markup_percent'] ?? '35';
$usd_to_ngn = $ps['usd_to_ngn']    ?? '1600';
?>
<title>Server1 (smspva) Services — <?php echo $site_data['web_name']; ?></title>
<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

<div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">
            <span class="badge badge-primary mr-2" style="font-size:.7rem;">Server 1</span>smspva.com Services
        </h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">smspva Services</li>
        </ol>
    </div>

    <!-- Info Banner -->
    <div class="alert alert-info d-flex align-items-start mb-4">
        <i class="fas fa-info-circle fa-2x mr-3 mt-1"></i>
        <div>
            <strong>Server 1 — smspva.com</strong><br>
            Manage countries and services for the smspva.com provider.
            Add countries with their ISO codes, then <strong>Sync Services</strong> to auto-import
            the standard smspva service catalogue with prices calculated from your exchange rate
            and markup settings. You can also add/edit services manually.<br>
            <small class="text-muted">Current rate: <strong>$1 = ₦<?php echo number_format((float)$usd_to_ngn, 2); ?></strong>
            &nbsp;|&nbsp; Markup: <strong><?php echo $markup_pct; ?>%</strong>
            &nbsp;|&nbsp; <a href="sync-services.php">Adjust in Sync Services page</a></small>
        </div>
    </div>

    <!-- Country Management Card -->
    <div class="row mb-4">
        <div class="col-lg-12">
            <div class="card shadow">
                <div class="card-header py-3 d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-globe mr-2"></i>Countries (Server 1)
                        <span class="badge badge-secondary ml-2"><?php echo count($countries); ?></span>
                    </h6>
                    <button class="btn btn-sm btn-primary" onclick="openAddCountryModal()">
                        <i class="fas fa-plus mr-1"></i>Add Country
                    </button>
                </div>

                <!-- Search -->
                <div class="px-3 pt-3 pb-2 bg-light border-bottom">
                    <div class="input-group input-group-sm" style="max-width:300px;">
                        <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-search"></i></span></div>
                        <input type="text" id="countrySearch" class="form-control" placeholder="Search country...">
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover align-items-center mb-0">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th><th>Flag</th><th>Country</th><th>ISO Code</th>
                                <th>Operator</th><th>Services</th><th>Status</th><th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="countriesTableBody">
                        <?php foreach ($countries as $idx => $c): ?>
                        <tr class="country-row" data-name="<?php echo strtolower($c['country_name']); ?>" data-code="<?php echo strtolower($c['country']); ?>">
                            <td><?php echo $idx + 1; ?></td>
                            <td>
                                <?php if (!empty($c['flag_url'])): ?>
                                <img src="<?php echo htmlspecialchars($c['flag_url']); ?>" alt=""
                                     style="width:36px;height:22px;object-fit:contain;border:1px solid #e3e6f0;border-radius:3px;background:#fff;"
                                     onerror="this.style.display='none'">
                                <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                            </td>
                            <td><strong><?php echo htmlspecialchars($c['country_name']); ?></strong></td>
                            <td><code><?php echo htmlspecialchars($c['country']); ?></code></td>
                            <td><small class="text-muted"><?php echo htmlspecialchars($c['operator'] ?: 'Random'); ?></small></td>
                            <td>
                                <span class="badge badge-<?php echo $c['svc_count'] > 0 ? 'primary' : 'secondary'; ?>"
                                      id="svcCount_<?php echo $c['id']; ?>">
                                    <?php echo $c['svc_count']; ?> services
                                </span>
                            </td>
                            <td>
                                <span class="badge badge-<?php echo $c['status'] ? 'success' : 'danger'; ?>">
                                    <?php echo $c['status'] ? 'Active' : 'Inactive'; ?>
                                </span>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-success"
                                            id="syncBtn_<?php echo $c['id']; ?>"
                                            onclick="syncCountry(<?php echo $c['id']; ?>, '<?php echo addslashes($c['country_name']); ?>')"
                                            <?php echo !$c['status'] ? 'disabled' : ''; ?>>
                                        <i class="fas fa-sync-alt mr-1"></i>Sync
                                    </button>
                                    <button class="btn btn-sm btn-info"
                                            onclick="viewServices(<?php echo $c['id']; ?>, '<?php echo addslashes($c['country_name']); ?>')">
                                        <i class="fas fa-list mr-1"></i>Services
                                    </button>
                                    <button class="btn btn-sm btn-warning"
                                            onclick="openEditCountryModal(<?php echo $c['id']; ?>, '<?php echo addslashes($c['country']); ?>', '<?php echo addslashes($c['country_name']); ?>', '<?php echo addslashes($c['flag_url']); ?>', '<?php echo addslashes($c['operator']); ?>', '<?php echo $c['status']; ?>')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger"
                                            onclick="deleteCountry(<?php echo $c['id']; ?>, '<?php echo addslashes($c['country_name']); ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($countries)): ?>
                        <tr><td colspan="8" class="text-center py-5 text-muted">
                            <i class="fas fa-globe fa-3x d-block mb-3"></i>
                            No countries yet. Click <strong>Add Country</strong> to get started.
                        </td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Services Table (shown when a country is selected) -->
    <div class="row" id="servicesPanel" style="display:none!important;">
        <div class="col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-info">
                        <i class="fas fa-list mr-2"></i>Services for <strong id="servicesPanelTitle"></strong>
                    </h6>
                    <div>
                        <button class="btn btn-sm btn-primary mr-2" onclick="openAddServiceModal()">
                            <i class="fas fa-plus mr-1"></i>Add Service
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="$('#servicesPanel').hide()">
                            <i class="fas fa-times mr-1"></i>Close
                        </button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="servicesTable">
                        <thead class="thead-light">
                            <tr><th>#</th><th>Service Name</th><th>Code</th><th>Price (₦)</th><th>Status</th><th>Actions</th></tr>
                        </thead>
                        <tbody id="servicesTableBody">
                            <tr><td colspan="6" class="text-center py-3 text-muted">Select a country above.</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ====== ADD COUNTRY MODAL ====== -->
<div class="modal fade" id="addCountryModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-primary"><i class="fas fa-plus-circle mr-2"></i>Add Country (Server 1)</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Country ISO Code</strong> <small class="text-danger">*</small></label>
                            <input type="text" class="form-control" id="add_country" placeholder="e.g. NG, US, GB" maxlength="5">
                            <small class="text-muted">ISO 3166-1 alpha-2, uppercase</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Country Name</strong> <small class="text-danger">*</small></label>
                            <input type="text" class="form-control" id="add_country_name" placeholder="e.g. Nigeria">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Operator</strong> <small class="text-muted">(optional)</small></label>
                    <input type="text" class="form-control" id="add_operator" placeholder="e.g. Grameenphone_BD  — leave blank for random">
                </div>
                <div class="form-group">
                    <label><strong>Flag URL</strong> <small class="text-muted">(auto-generated if blank)</small></label>
                    <input type="text" class="form-control" id="add_flag_url" placeholder="https://flagcdn.com/w160/ng.png">
                </div>
                <div class="form-group">
                    <label><strong>Status</strong></label>
                    <select class="form-control" id="add_country_status">
                        <option value="1">Active</option>
                        <option value="0">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" id="submitAddCountry"><i class="fas fa-plus mr-1"></i>Add Country</button>
            </div>
        </div>
    </div>
</div>

<!-- ====== EDIT COUNTRY MODAL ====== -->
<div class="modal fade" id="editCountryModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-warning"><i class="fas fa-edit mr-2"></i>Edit Country</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="edit_country_id">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>ISO Code</strong></label>
                            <input type="text" class="form-control" id="edit_country" maxlength="5">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Country Name</strong></label>
                            <input type="text" class="form-control" id="edit_country_name">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Operator</strong></label>
                    <input type="text" class="form-control" id="edit_operator" placeholder="Leave blank for random">
                </div>
                <div class="form-group">
                    <label><strong>Flag URL</strong></label>
                    <input type="text" class="form-control" id="edit_flag_url">
                </div>
                <div class="form-group">
                    <label><strong>Status</strong></label>
                    <select class="form-control" id="edit_country_status">
                        <option value="1">Active</option>
                        <option value="0">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-warning" id="submitEditCountry"><i class="fas fa-save mr-1"></i>Save Changes</button>
            </div>
        </div>
    </div>
</div>

<!-- ====== ADD SERVICE MODAL ====== -->
<div class="modal fade" id="addServiceModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-primary"><i class="fas fa-plus-circle mr-2"></i>Add Service</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="add_svc_server_id">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Service Code</strong> <small class="text-danger">*</small></label>
                            <input type="text" class="form-control" id="add_svc_code" placeholder="e.g. opt20">
                            <small class="text-muted">smspva service code</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Service Name</strong> <small class="text-danger">*</small></label>
                            <input type="text" class="form-control" id="add_svc_name" placeholder="e.g. Whatsapp">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Price (₦)</strong></label>
                    <div class="input-group">
                        <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                        <input type="number" step="0.01" min="0" class="form-control" id="add_svc_price" placeholder="e.g. 500.00">
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Status</strong></label>
                    <select class="form-control" id="add_svc_status">
                        <option value="1">Active</option>
                        <option value="0">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" id="submitAddService"><i class="fas fa-plus mr-1"></i>Add Service</button>
            </div>
        </div>
    </div>
</div>

<!-- ====== EDIT SERVICE MODAL ====== -->
<div class="modal fade" id="editServiceModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-warning"><i class="fas fa-edit mr-2"></i>Edit Service</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="edit_svc_id">
                <input type="hidden" id="edit_svc_server_id">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Service Code</strong></label>
                            <input type="text" class="form-control" id="edit_svc_code">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Service Name</strong></label>
                            <input type="text" class="form-control" id="edit_svc_name">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Price (₦)</strong></label>
                    <div class="input-group">
                        <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                        <input type="number" step="0.01" min="0" class="form-control" id="edit_svc_price">
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Status</strong></label>
                    <select class="form-control" id="edit_svc_status">
                        <option value="1">Active</option>
                        <option value="0">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-warning" id="submitEditService"><i class="fas fa-save mr-1"></i>Save Changes</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const AJAX_URL = 'ajax/smspva_data.php';
let currentServerId = null;

// ── Country search ────────────────────────────────────────────────────────────
$('#countrySearch').on('keyup', function(){
    const q = $(this).val().toLowerCase();
    $('.country-row').each(function(){
        const match = $(this).data('name').includes(q) || $(this).data('code').includes(q);
        $(this).toggle(match);
    });
});

// ── ADD COUNTRY ───────────────────────────────────────────────────────────────
function openAddCountryModal(){
    $('#add_country,#add_country_name,#add_operator,#add_flag_url').val('');
    $('#add_country_status').val('1');
    $('#addCountryModal').modal('show');
}

$('#submitAddCountry').on('click', function(){
    const country      = $('#add_country').val().trim().toUpperCase();
    const country_name = $('#add_country_name').val().trim();
    if (!country || !country_name){ Swal.fire('Error','Country code and name are required.','warning'); return; }
    $(this).prop('disabled',true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Adding...');
    $.ajax({ url:AJAX_URL, type:'POST',
        data:{ action:'add_country', country, country_name,
               operator:$('#add_operator').val().trim(),
               flag_url:$('#add_flag_url').val().trim(),
               status:$('#add_country_status').val() },
        dataType:'json',
        success:function(d){
            $('#submitAddCountry').prop('disabled',false).html('<i class="fas fa-plus mr-1"></i>Add Country');
            if(d.status=='1'){ $('#addCountryModal').modal('hide'); Swal.fire({title:'Added!',text:d.msg,icon:'success',confirmButtonColor:'#1cc88a'}).then(()=>location.reload()); }
            else Swal.fire('Error',d.msg,'error');
        },
        error:function(){ $('#submitAddCountry').prop('disabled',false).html('<i class="fas fa-plus mr-1"></i>Add Country'); Swal.fire('Error','Request failed.','error'); }
    });
});

// ── EDIT COUNTRY ──────────────────────────────────────────────────────────────
function openEditCountryModal(id, country, name, flag, operator, status){
    $('#edit_country_id').val(id);
    $('#edit_country').val(country);
    $('#edit_country_name').val(name);
    $('#edit_flag_url').val(flag);
    $('#edit_operator').val(operator);
    $('#edit_country_status').val(status);
    $('#editCountryModal').modal('show');
}

$('#submitEditCountry').on('click', function(){
    const id = $('#edit_country_id').val();
    const country = $('#edit_country').val().trim().toUpperCase();
    const country_name = $('#edit_country_name').val().trim();
    if (!id || !country || !country_name){ Swal.fire('Error','All required fields must be filled.','warning'); return; }
    $(this).prop('disabled',true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Saving...');
    $.ajax({ url:AJAX_URL, type:'POST',
        data:{ action:'edit_country', id, country, country_name,
               flag_url:$('#edit_flag_url').val().trim(),
               operator:$('#edit_operator').val().trim(),
               status:$('#edit_country_status').val() },
        dataType:'json',
        success:function(d){
            $('#submitEditCountry').prop('disabled',false).html('<i class="fas fa-save mr-1"></i>Save Changes');
            if(d.status=='1'){ $('#editCountryModal').modal('hide'); Swal.fire({title:'Updated!',text:d.msg,icon:'success',confirmButtonColor:'#1cc88a'}).then(()=>location.reload()); }
            else Swal.fire('Error',d.msg,'error');
        },
        error:function(){ $('#submitEditCountry').prop('disabled',false).html('<i class="fas fa-save mr-1"></i>Save Changes'); Swal.fire('Error','Request failed.','error'); }
    });
});

// ── DELETE COUNTRY ────────────────────────────────────────────────────────────
function deleteCountry(id, name){
    Swal.fire({ title:'Delete Country?', html:`Delete <strong>${name}</strong> and all its services?`, icon:'warning',
        showCancelButton:true, confirmButtonColor:'#e74a3b', confirmButtonText:'Yes, Delete' })
    .then(r=>{ if(!r.isConfirmed) return;
        Swal.fire({title:'Deleting...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
        $.ajax({ url:AJAX_URL, type:'POST', data:{action:'delete_country',id}, dataType:'json',
            success:function(d){ Swal.close();
                if(d.status=='1') Swal.fire({title:'Deleted!',text:d.msg,icon:'success',confirmButtonColor:'#1cc88a'}).then(()=>location.reload());
                else Swal.fire('Error',d.msg,'error'); },
            error:function(){ Swal.close(); Swal.fire('Error','Request failed.','error'); }
        });
    });
}

// ── SYNC single country ───────────────────────────────────────────────────────
function syncCountry(id, name){
    const btn = $('#syncBtn_'+id);
    btn.prop('disabled',true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Syncing...');
    $.ajax({ url:AJAX_URL, type:'POST', data:{action:'sync_services',server_id:id}, dataType:'json', timeout:120000,
        success:function(d){
            btn.prop('disabled',false).html('<i class="fas fa-sync-alt mr-1"></i>Sync');
            if(d.status=='1'){
                const cnt = (parseInt(d.inserted)||0) + (parseInt(d.updated)||0);
                $('#svcCount_'+id).text(cnt+' services').removeClass('badge-secondary').addClass('badge-primary');
                Swal.fire({ title:'Sync Complete!', html:d.msg, icon:'success', confirmButtonColor:'#1cc88a' });
            } else Swal.fire('Sync Failed',d.msg,'error');
        },
        error:function(){ btn.prop('disabled',false).html('<i class="fas fa-sync-alt mr-1"></i>Sync'); Swal.fire('Error','Request timed out.','error'); }
    });
}

// ── VIEW & MANAGE SERVICES ────────────────────────────────────────────────────
function viewServices(id, name){
    currentServerId = id;
    $('#servicesPanelTitle').text(name);
    $('#servicesPanel').show();
    $('html,body').animate({scrollTop:$('#servicesPanel').offset().top - 60}, 400);

    $('#servicesTableBody').html('<tr><td colspan="6" class="text-center py-3"><i class="fas fa-spinner fa-spin mr-1"></i>Loading...</td></tr>');
    $.ajax({ url:AJAX_URL, type:'POST', data:{action:'get_services',server_id:id}, dataType:'json',
        success:function(res){
            const tbody = $('#servicesTableBody');
            tbody.empty();
            if(res.status=='1' && res.services.length > 0){
                $.each(res.services, function(i, s){
                    const statusBadge = s.status=='1'
                        ? '<span class="badge badge-success">Active</span>'
                        : '<span class="badge badge-danger">Inactive</span>';
                    tbody.append(`<tr>
                        <td>${i+1}</td>
                        <td><strong>${escHtml(s.service_name)}</strong></td>
                        <td><code>${escHtml(s.service_code)}</code></td>
                        <td><strong>₦${parseFloat(s.service_price).toLocaleString('en-NG',{minimumFractionDigits:2})}</strong></td>
                        <td>${statusBadge}</td>
                        <td>
                            <button class="btn btn-sm btn-warning mr-1"
                                    onclick="openEditServiceModal(${s.id},${id},'${jsEsc(s.service_code)}','${jsEsc(s.service_name)}',${parseFloat(s.service_price)},${s.status})">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteService(${s.id},'${jsEsc(s.service_name)}')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td></tr>`);
                });
            } else {
                tbody.html('<tr><td colspan="6" class="text-center py-4 text-muted"><i class="fas fa-inbox fa-2x d-block mb-2"></i>No services yet. Click <strong>Sync</strong> or <strong>Add Service</strong>.</td></tr>');
            }
        },
        error:function(){ $('#servicesTableBody').html('<tr><td colspan="6" class="text-center text-danger">Load error.</td></tr>'); }
    });
}

// ── ADD SERVICE ───────────────────────────────────────────────────────────────
function openAddServiceModal(){
    if(!currentServerId){ Swal.fire('Select Country','Click "Services" on a country first.','info'); return; }
    $('#add_svc_server_id').val(currentServerId);
    $('#add_svc_code,#add_svc_name,#add_svc_price').val('');
    $('#add_svc_status').val('1');
    $('#addServiceModal').modal('show');
}

$('#submitAddService').on('click', function(){
    const code = $('#add_svc_code').val().trim();
    const name = $('#add_svc_name').val().trim();
    if(!code||!name){ Swal.fire('Error','Code and name are required.','warning'); return; }
    $(this).prop('disabled',true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Adding...');
    $.ajax({ url:AJAX_URL, type:'POST',
        data:{ action:'add_service', server_id:$('#add_svc_server_id').val(),
               service_code:code, service_name:name,
               service_price:$('#add_svc_price').val()||'0', status:$('#add_svc_status').val() },
        dataType:'json',
        success:function(d){
            $('#submitAddService').prop('disabled',false).html('<i class="fas fa-plus mr-1"></i>Add Service');
            if(d.status=='1'){ $('#addServiceModal').modal('hide'); Swal.fire({title:'Added!',text:d.msg,icon:'success',confirmButtonColor:'#1cc88a'}).then(()=>viewServices(currentServerId,$('#servicesPanelTitle').text())); }
            else Swal.fire('Error',d.msg,'error');
        },
        error:function(){ $('#submitAddService').prop('disabled',false).html('<i class="fas fa-plus mr-1"></i>Add Service'); }
    });
});

// ── EDIT SERVICE ──────────────────────────────────────────────────────────────
function openEditServiceModal(id, serverId, code, name, price, status){
    $('#edit_svc_id').val(id);
    $('#edit_svc_server_id').val(serverId);
    $('#edit_svc_code').val(code);
    $('#edit_svc_name').val(name);
    $('#edit_svc_price').val(price);
    $('#edit_svc_status').val(status);
    $('#editServiceModal').modal('show');
}

$('#submitEditService').on('click', function(){
    const id = $('#edit_svc_id').val();
    const code = $('#edit_svc_code').val().trim();
    const name = $('#edit_svc_name').val().trim();
    if(!id||!code||!name){ Swal.fire('Error','All fields required.','warning'); return; }
    $(this).prop('disabled',true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Saving...');
    $.ajax({ url:AJAX_URL, type:'POST',
        data:{ action:'edit_service', id, server_id:$('#edit_svc_server_id').val(),
               service_code:code, service_name:name,
               service_price:$('#edit_svc_price').val()||'0', status:$('#edit_svc_status').val() },
        dataType:'json',
        success:function(d){
            $('#submitEditService').prop('disabled',false).html('<i class="fas fa-save mr-1"></i>Save Changes');
            if(d.status=='1'){ $('#editServiceModal').modal('hide'); Swal.fire({title:'Updated!',text:d.msg,icon:'success',confirmButtonColor:'#1cc88a'}).then(()=>viewServices(currentServerId,$('#servicesPanelTitle').text())); }
            else Swal.fire('Error',d.msg,'error');
        },
        error:function(){ $('#submitEditService').prop('disabled',false).html('<i class="fas fa-save mr-1"></i>Save Changes'); }
    });
});

// ── DELETE SERVICE ────────────────────────────────────────────────────────────
function deleteService(id, name){
    Swal.fire({ title:'Delete Service?', html:`Delete <strong>${name}</strong>?`, icon:'warning',
        showCancelButton:true, confirmButtonColor:'#e74a3b', confirmButtonText:'Delete' })
    .then(r=>{ if(!r.isConfirmed) return;
        $.ajax({ url:AJAX_URL, type:'POST', data:{action:'delete_service',id}, dataType:'json',
            success:function(d){
                if(d.status=='1') Swal.fire({title:'Deleted!',text:d.msg,icon:'success',confirmButtonColor:'#1cc88a'}).then(()=>viewServices(currentServerId,$('#servicesPanelTitle').text()));
                else Swal.fire('Error',d.msg,'error');
            }
        });
    });
}

function escHtml(str){ if(!str) return ''; return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function jsEsc(str){ if(!str) return ''; return String(str).replace(/\\/g,'\\\\').replace(/'/g,"\\'"); }
</script>

<style>
code { color:#e83e8c; background:#f8f9fc; padding:2px 5px; border-radius:3px; font-size:.85em; }
.modal-header { border-bottom:2px solid #e3e6f0; }
</style>

<?php include('include/footer.php'); ?>
