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

// Fetch all smspva countries
try {
    $stmt = $pdo->prepare("SELECT * FROM smspva_server ORDER BY server_name ASC");
    $stmt->execute();
    $countries = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $countries = [];
    error_log("Error fetching smspva countries: " . $e->getMessage());
}

// Fetch price settings
try {
    $ps_rows = $pdo->query("SELECT setting_key, setting_value FROM smspva_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (PDOException $e) {
    $ps_rows = [];
}

$markup_pct   = $ps_rows['markup_percent']        ?? '35';
$current_rate = $ps_rows['usd_to_ngn']            ?? '1600';
$rate_updated = $ps_rows['rate_updated_at']       ?? 'Never';
$auto_refresh = $ps_rows['auto_refresh_enabled']  ?? '0';
$smspva_key   = $ps_rows['api_key']               ?? 'Vdn58zFGMmHDvBwPcucP1067M6422u';

// Service counts per country
$service_counts = [];
try {
    $sc_stmt = $pdo->query("SELECT server_id, COUNT(*) as cnt FROM smspva_service GROUP BY server_id");
    foreach ($sc_stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $service_counts[(int)$row['server_id']] = (int)$row['cnt'];
    }
} catch (PDOException $e) {}
?>
<title>SMSPVA Countries - <?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-warning mr-2" style="font-size:0.65rem;vertical-align:middle;">Server1</span>
            SMSPVA Countries
        </h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">SMSPVA Countries</li>
        </ol>
    </div>

    <!-- Provider Info Banner -->
    <div class="alert alert-warning d-flex align-items-center mb-4" style="border-left:4px solid #f6c23e;">
        <i class="fas fa-server fa-2x mr-3 text-warning"></i>
        <div>
            <strong>Provider: smspva.com (Server1)</strong><br>
            <small class="text-muted">
                Manages countries and services from <strong>smspva.com</strong> API.
                smscodes.io remains as <strong>Server2</strong>.
                Both providers are available to users when purchasing virtual numbers.
            </small>
        </div>
    </div>

    <!-- ══ PRICE SETTINGS CARD ══════════════════════════════════════════════ -->
    <div class="row mb-4">
        <div class="col-lg-12">
            <div class="card border-left-warning shadow">
                <div class="card-header py-3 d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-warning">
                        <i class="fas fa-sliders-h mr-2"></i>SMSPVA Live Pricing Settings
                    </h6>
                    <span class="badge badge-info px-3 py-2" style="font-size:0.82rem;">
                        <i class="fas fa-info-circle mr-1"></i>
                        Prices are auto-converted from USD to ₦ with your markup at purchase time
                    </span>
                </div>
                <div class="card-body">
                    <div class="row align-items-end">
                        <!-- API Key -->
                        <div class="col-md-4">
                            <label class="font-weight-bold text-gray-700 small">
                                <i class="fas fa-key mr-1 text-warning"></i>SMSPVA API Key
                            </label>
                            <div class="input-group input-group-sm">
                                <input type="text" id="smspva_api_key_input" class="form-control"
                                       value="<?php echo htmlspecialchars($smspva_key); ?>"
                                       placeholder="Your smspva.com API key">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button"
                                            onclick="toggleKeyVisibility()" title="Show/Hide">
                                        <i class="fas fa-eye" id="toggleKeyIcon"></i>
                                    </button>
                                </div>
                            </div>
                            <small class="text-muted">Used as <code>apikey</code> header in smspva requests</small>
                        </div>

                        <!-- Markup % -->
                        <div class="col-md-2">
                            <label class="font-weight-bold text-gray-700 small">
                                <i class="fas fa-percent mr-1 text-warning"></i>Markup %
                            </label>
                            <div class="input-group input-group-sm">
                                <input type="number" id="smspva_markup_input" class="form-control"
                                       value="<?php echo htmlspecialchars($markup_pct); ?>"
                                       min="0" max="10000" step="0.1" placeholder="35">
                                <div class="input-group-append">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                            <small class="text-muted">Added on top of ₦ price</small>
                        </div>

                        <!-- Exchange Rate -->
                        <div class="col-md-3">
                            <label class="font-weight-bold text-gray-700 small">
                                <i class="fas fa-exchange-alt mr-1 text-success"></i>USD → NGN Rate
                            </label>
                            <div class="input-group input-group-sm">
                                <div class="input-group-prepend">
                                    <span class="input-group-text" style="font-size:.75rem;">$1 =</span>
                                </div>
                                <input type="number" id="smspva_usd_rate_input" class="form-control"
                                       value="<?php echo htmlspecialchars($current_rate); ?>"
                                       min="0" step="0.01" placeholder="1600">
                                <div class="input-group-append">
                                    <span class="input-group-text">₦</span>
                                </div>
                            </div>
                            <small class="text-muted">
                                <i class="fas fa-clock mr-1"></i>
                                Updated: <span id="smspva_rate_updated_time"><?php echo htmlspecialchars($rate_updated); ?></span>
                            </small>
                        </div>

                        <!-- Auto-Refresh Toggle -->
                        <div class="col-md-2">
                            <label class="font-weight-bold text-gray-700 small">
                                <i class="fas fa-sync-alt mr-1 text-info"></i>Auto Refresh Rate
                            </label>
                            <div class="custom-control custom-switch mt-1">
                                <input type="checkbox" class="custom-control-input" id="smspva_auto_refresh_toggle"
                                       <?php echo ($auto_refresh == '1') ? 'checked' : ''; ?>>
                                <label class="custom-control-label" for="smspva_auto_refresh_toggle">
                                    Auto every hour
                                </label>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="col-md-1">
                            <div class="d-flex flex-column" style="gap:4px;">
                                <button class="btn btn-sm btn-warning" onclick="smspvaTestApiKey()" title="Test API connection">
                                    <i class="fas fa-plug mr-1"></i>Test
                                </button>
                                <button class="btn btn-sm btn-primary" onclick="smspvaSaveSettings()" title="Save all settings">
                                    <i class="fas fa-save mr-1"></i>Save
                                </button>
                                <button class="btn btn-sm btn-success" onclick="smspvaRefreshRateLive()" title="Fetch live rate">
                                    <i class="fas fa-sync-alt mr-1"></i>Rate
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Price Example Row -->
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <div class="alert alert-light border-left-warning mb-0">
                                <strong><i class="fas fa-calculator mr-2 text-warning"></i>Example Calculation (smspva.com):</strong>
                                <p class="mb-0" style="font-size:1rem;font-weight:600;color:#1cc88a;">
                                    A service priced at $0.15 USD would cost:
                                    <span id="smspva_price_example_value">₦0.00</span>
                                    <br>
                                    <small class="text-muted">
                                        (base + <span id="smspva_markup_display"><?php echo htmlspecialchars($markup_pct); ?></span>% markup)
                                    </small>
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Resync Button -->
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <button class="btn btn-warning w-100" onclick="smspvaResyncAllPrices()">
                                <i class="fas fa-tags mr-2"></i>
                                Resync All SMSPVA Service Prices (with current rates)
                            </button>
                            <small class="text-muted d-block mt-1">
                                <i class="fas fa-info-circle mr-1"></i>
                                Re-fetches live USD prices from smspva.com for all services and recalculates ₦ prices.
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- ══ END PRICE SETTINGS ══════════════════════════════════════════════ -->

    <!-- ══ COUNTRIES TABLE ══════════════════════════════════════════════════ -->
    <div class="row">
        <div class="col-lg-12">
            <div class="card mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-warning">
                        <i class="fas fa-globe mr-2"></i>
                        SMSPVA Countries
                        <span class="badge badge-secondary ml-2"><?php echo count($countries); ?></span>
                    </h6>
                    <div>
                        <button class="btn btn-sm btn-success mr-2" onclick="openSmspvaSyncModal()">
                            <i class="fas fa-sync-alt mr-1"></i> Sync Countries from smspva.com
                        </button>
                        <a href="smspva-services.php" class="btn btn-sm btn-info mr-2">
                            <i class="fas fa-list mr-1"></i> Manage Services
                        </a>
                        <button class="btn btn-sm btn-primary" onclick="openSmspvaAddCountryModal()">
                            <i class="fas fa-plus mr-1"></i> Add Country
                        </button>
                    </div>
                </div>

                <div class="table-responsive p-3">
                    <table class="table align-items-center table-flush table-hover" id="smspvaDataTable">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Flag</th>
                                <th>Country Name</th>
                                <th>Country Code</th>
                                <th>Services</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; foreach ($countries as $data):
                                $sid         = (int)$data['id'];
                                $svc_count   = $service_counts[$sid] ?? 0;
                                $status_class = ($data['status'] == '1') ? 'badge badge-success' : 'badge badge-danger';
                                $status_label = ($data['status'] == '1') ? 'Active' : 'Inactive';
                                $js_name      = addslashes(htmlspecialchars($data['server_name'], ENT_QUOTES));
                                $js_code      = addslashes(htmlspecialchars($data['server_code'], ENT_QUOTES));
                                $js_flag      = addslashes(htmlspecialchars($data['flag_url'] ?? '', ENT_QUOTES));
                                $js_status    = (int)$data['status'];
                            ?>
                            <tr>
                                <td><?php echo $i; ?></td>
                                <td>
                                    <?php if (!empty($data['flag_url'])): ?>
                                        <img src="<?php echo htmlspecialchars($data['flag_url']); ?>"
                                             alt="<?php echo htmlspecialchars($data['server_name']); ?>"
                                             class="flag-img-sm"
                                             onerror="this.style.display='none'">
                                    <?php else: ?>
                                        <i class="fas fa-flag text-muted"></i>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?php echo htmlspecialchars($data['server_name']); ?></strong></td>
                                <td>
                                    <code><?php echo htmlspecialchars($data['server_code']); ?></code>
                                    <small class="text-muted d-block">(smspva format: uppercase)</small>
                                </td>
                                <td>
                                    <span class="badge badge-<?php echo $svc_count > 0 ? 'primary' : 'secondary'; ?>">
                                        <?php echo $svc_count; ?> service<?php echo $svc_count !== 1 ? 's' : ''; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="<?php echo $status_class; ?>"><?php echo $status_label; ?></span>
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button type="button"
                                                class="btn btn-sm btn-primary dropdown-toggle"
                                                data-toggle="dropdown"
                                                aria-haspopup="true"
                                                aria-expanded="false">
                                            <i class="fas fa-cog"></i> Actions
                                        </button>
                                        <div class="dropdown-menu">
                                            <a class="dropdown-item" href="smspva-services.php?server_id=<?php echo $sid; ?>">
                                                <i class="fas fa-list text-info"></i> View Services
                                            </a>
                                            <a class="dropdown-item" href="#"
                                               onclick="syncSmspvaCountryServices(<?php echo $sid; ?>, '<?php echo $js_code; ?>', '<?php echo $js_name; ?>')">
                                                <i class="fas fa-sync-alt text-success"></i> Sync Services
                                            </a>
                                            <div class="dropdown-divider"></div>
                                            <a class="dropdown-item" href="#"
                                               onclick="openSmspvaEditCountryModal(<?php echo $sid; ?>, '<?php echo $js_name; ?>', '<?php echo $js_code; ?>', '<?php echo $js_flag; ?>', <?php echo $js_status; ?>)">
                                                <i class="fas fa-edit text-primary"></i> Edit Country
                                            </a>
                                            <div class="dropdown-divider"></div>
                                            <a class="dropdown-item" href="#"
                                               onclick="deleteSmspvaCountry(<?php echo $sid; ?>, '<?php echo $js_name; ?>')">
                                                <i class="fas fa-trash text-danger"></i> Delete Country
                                            </a>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php $i++; endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <!-- ══ END COUNTRIES TABLE ═════════════════════════════════════════════ -->

</div>
<!-- End Container Fluid -->


<!-- ═══════════════════════ SYNC COUNTRIES MODAL ════════════════════════ -->
<div class="modal fade" id="smspvaSyncModal" tabindex="-1" role="dialog" aria-labelledby="smspvaSyncModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-success" id="smspvaSyncModalLabel">
                    <i class="fas fa-sync-alt mr-2"></i>Sync Countries from smspva.com
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle mr-2"></i>
                    This syncs countries from <strong>smspva.com</strong> by checking which countries have available numbers.
                    The API is queried using the service price endpoint. New countries will be added;
                    existing ones will have their names updated.
                </div>

                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    <strong>Note:</strong> smspva.com does not have a single "list all countries" endpoint.
                    This sync uses a comprehensive predefined country list and verifies availability.
                    You can also manually add countries using the <strong>Add Country</strong> button.
                </div>

                <div class="form-group">
                    <label><strong>Sync Method</strong></label>
                    <select class="form-control" id="smspva_sync_method">
                        <option value="predefined">Use Predefined Country List (Recommended)</option>
                        <option value="manual_list">Specify Country Codes Manually</option>
                    </select>
                </div>

                <!-- Manual country codes input (shown conditionally) -->
                <div class="form-group d-none" id="smspva_manual_codes_wrapper">
                    <label><strong>Enter Country Codes</strong> <small class="text-muted">(uppercase, comma-separated)</small></label>
                    <textarea class="form-control" id="smspva_manual_codes" rows="3"
                              placeholder="e.g. US, UK, DE, FR, NG, IN, BR"></textarea>
                    <small class="text-muted">smspva.com uses uppercase ISO codes (US, UK, DE, FR, etc.)</small>
                </div>

                <div id="smspvaSyncResult" class="d-none mt-3"></div>

                <!-- Progress bar -->
                <div id="smspvaSyncProgress" class="d-none mt-3">
                    <div class="d-flex justify-content-between mb-1">
                        <small class="font-weight-bold" id="smspvaSyncProgressLabel">Syncing...</small>
                        <small id="smspvaSyncProgressPct">0%</small>
                    </div>
                    <div class="progress mb-2" style="height:18px;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-success"
                             id="smspvaSyncBar" role="progressbar" style="width:0%"></div>
                    </div>
                    <div id="smspvaSyncLog"
                         style="max-height:150px;overflow-y:auto;font-size:.78rem;border:1px solid #e3e6f0;border-radius:6px;padding:8px;background:#f8f9fc;">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="submitSmspvaSync">
                    <i class="fas fa-sync-alt mr-1"></i>Start Sync
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ═══════════════════════ ADD COUNTRY MODAL ═══════════════════════════ -->
<div class="modal fade" id="smspvaAddCountryModal" tabindex="-1" role="dialog" aria-labelledby="smspvaAddCountryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-primary" id="smspvaAddCountryModalLabel">
                    <i class="fas fa-plus-circle mr-2"></i>Add SMSPVA Country
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info py-2">
                    <i class="fas fa-info-circle mr-1"></i>
                    <strong>smspva.com uses UPPERCASE country codes</strong> — e.g. <code>US</code>, <code>UK</code>, <code>DE</code>, <code>NG</code>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Country Name</strong></label>
                            <input type="text" class="form-control" id="smspva_add_server_name"
                                   placeholder="e.g. United States">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label><strong>Country Code (UPPERCASE)</strong></label>
                            <input type="text" class="form-control" id="smspva_add_server_code"
                                   placeholder="e.g. US" maxlength="5" style="text-transform:uppercase;">
                            <small class="text-muted">As used by smspva.com</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label><strong>Status</strong></label>
                            <select class="form-control" id="smspva_add_status">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Country Flag URL</strong></label>
                    <div class="input-group mb-1">
                        <input type="text" class="form-control" id="smspva_add_flag_url"
                               placeholder="e.g. https://flagcdn.com/w160/us.png"
                               oninput="smspvaPreviewFlag('smspva_add_flag_url','smspva_add_flag_preview')">
                        <div class="input-group-append">
                            <button class="btn btn-outline-info" type="button" onclick="smspvaAutoFlag('add')">
                                <i class="fas fa-magic mr-1"></i>Auto
                            </button>
                        </div>
                    </div>
                    <small class="text-muted">
                        <i class="fas fa-info-circle mr-1"></i>
                        Click <strong>Auto</strong> to generate flag URL from the country code, or paste a custom URL.
                    </small>
                    <div class="mt-2">
                        <img id="smspva_add_flag_preview" class="flag-preview-box d-none" src="" alt="Flag Preview">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="submitSmspvaAddCountry">
                    <i class="fas fa-plus mr-1"></i>Add Country
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ═══════════════════════ EDIT COUNTRY MODAL ══════════════════════════ -->
<div class="modal fade" id="smspvaEditCountryModal" tabindex="-1" role="dialog" aria-labelledby="smspvaEditCountryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold text-primary" id="smspvaEditCountryModalLabel">
                    <i class="fas fa-edit mr-2"></i>Edit SMSPVA Country
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="smspva_edit_id">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong>Country Name</strong></label>
                            <input type="text" class="form-control" id="smspva_edit_server_name"
                                   placeholder="e.g. United States">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label><strong>Country Code (UPPERCASE)</strong></label>
                            <input type="text" class="form-control" id="smspva_edit_server_code"
                                   placeholder="e.g. US" maxlength="5" style="text-transform:uppercase;">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label><strong>Status</strong></label>
                            <select class="form-control" id="smspva_edit_status">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Country Flag URL</strong></label>
                    <div class="input-group mb-1">
                        <input type="text" class="form-control" id="smspva_edit_flag_url"
                               placeholder="e.g. https://flagcdn.com/w160/us.png"
                               oninput="smspvaPreviewFlag('smspva_edit_flag_url','smspva_edit_flag_preview')">
                        <div class="input-group-append">
                            <button class="btn btn-outline-info" type="button" onclick="smspvaAutoFlag('edit')">
                                <i class="fas fa-magic mr-1"></i>Auto
                            </button>
                        </div>
                    </div>
                    <div class="mt-2">
                        <img id="smspva_edit_flag_preview" class="flag-preview-box d-none" src="" alt="Flag Preview">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="submitSmspvaEditCountry">
                    <i class="fas fa-save mr-1"></i>Save Changes
                </button>
            </div>
        </div>
    </div>
</div>


<!-- Page level plugins -->
<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// ── Init ─────────────────────────────────────────────────────────────────────
var smspvaCurrentRate   = <?php echo (float)$current_rate; ?>;
var smspvaCurrentMarkup = <?php echo (float)$markup_pct; ?>;
var smspvaAutoRefreshEnabled = <?php echo ($auto_refresh == '1') ? 'true' : 'false'; ?>;
var smspvaAutoRefreshInterval = null;

$(document).ready(function () {
    $('#smspvaDataTable').DataTable({
        ordering: true,
        pageLength: 25,
        order: [[2, 'asc']]
    });
    smspvaUpdatePriceExample();
    if (smspvaAutoRefreshEnabled) { smspvaStartAutoRefresh(); }

    // Show/hide manual codes textarea
    $('#smspva_sync_method').on('change', function () {
        if ($(this).val() === 'manual_list') {
            $('#smspva_manual_codes_wrapper').removeClass('d-none');
        } else {
            $('#smspva_manual_codes_wrapper').addClass('d-none');
        }
    });
});

// ── Price Example ─────────────────────────────────────────────────────────────
function smspvaUpdatePriceExample() {
    var markup = parseFloat($('#smspva_markup_input').val()) || 0;
    var rate   = parseFloat($('#smspva_usd_rate_input').val()) || smspvaCurrentRate;
    // smspva typically cheaper: use $0.15 as example
    var ex     = 0.15;
    var final  = (ex * rate) * (1 + markup / 100);
    $('#smspva_price_example_value').text('₦' + final.toLocaleString('en-NG', {minimumFractionDigits:2, maximumFractionDigits:2}));
    $('#smspva_markup_display').text(markup);
}
$('#smspva_markup_input, #smspva_usd_rate_input').on('input', smspvaUpdatePriceExample);

// ── Toggle API key visibility ─────────────────────────────────────────────────
function toggleKeyVisibility() {
    var input = $('#smspva_api_key_input');
    var icon  = $('#toggleKeyIcon');
    if (input.attr('type') === 'password') {
        input.attr('type', 'text');
        icon.removeClass('fa-eye').addClass('fa-eye-slash');
    } else {
        input.attr('type', 'password');
        icon.removeClass('fa-eye-slash').addClass('fa-eye');
    }
}

// ── Auto Refresh Toggle ───────────────────────────────────────────────────────
$('#smspva_auto_refresh_toggle').on('change', function () {
    var enabled = this.checked ? '1' : '0';
    $.ajax({
        url: 'ajax/smspva_sync.php',
        type: 'POST',
        data: { action: 'toggle_auto_refresh', enabled: enabled },
        dataType: 'json',
        success: function (data) {
            if (data.status == '1') {
                smspvaAutoRefreshEnabled = (enabled == '1');
                if (smspvaAutoRefreshEnabled) { smspvaStartAutoRefresh(); }
                else { smspvaStopAutoRefresh(); }
            }
        }
    });
});

function smspvaStartAutoRefresh() {
    if (smspvaAutoRefreshInterval) clearInterval(smspvaAutoRefreshInterval);
    smspvaAutoRefreshInterval = setInterval(smspvaRefreshRateLive, 3600000);
}
function smspvaStopAutoRefresh() {
    if (smspvaAutoRefreshInterval) clearInterval(smspvaAutoRefreshInterval);
}

// ── Test API Key ──────────���───────────────────────────────────────────────────
function smspvaTestApiKey() {
    var api_key = $.trim($('#smspva_api_key_input').val());
    if (!api_key) { Swal.fire('Missing', 'Please enter an API key first.', 'warning'); return; }

    Swal.fire({
        title: 'Testing API Connection...',
        html: 'Connecting to smspva.com...',
        allowOutsideClick: false,
        didOpen: () => { Swal.showLoading(); }
    });

    $.ajax({
        url: 'ajax/smspva_sync.php',
        type: 'POST',
        data: { action: 'test_api', api_key: api_key },
        dataType: 'json',
        success: function (data) {
            Swal.close();
            if (data.status == '1') {
                Swal.fire({
                    title: 'Connected!',
                    html: 'API key is valid.<br>' +
                          (data.balance !== undefined
                            ? '<strong>Balance: $' + parseFloat(data.balance).toFixed(4) + '</strong>'
                            : ''),
                    icon: 'success',
                    confirmButtonColor: '#1cc88a'
                });
            } else {
                Swal.fire('Connection Failed', data.msg || 'Invalid API key or connection error.', 'error');
            }
        },
        error: function () { Swal.close(); Swal.fire('Error', 'Failed to test API connection.', 'error'); }
    });
}

// ── Save All Settings ─────────────────────────────────────────────────────────
function smspvaSaveSettings() {
    var api_key  = $.trim($('#smspva_api_key_input').val());
    var markup   = $.trim($('#smspva_markup_input').val());
    var usd_rate = $.trim($('#smspva_usd_rate_input').val());

    if (!api_key) { Swal.fire('Validation Error', 'API key is required.', 'warning'); return; }
    if (!markup || isNaN(markup)) { Swal.fire('Validation Error', 'Enter a valid markup percent.', 'warning'); return; }
    if (!usd_rate || isNaN(usd_rate) || parseFloat(usd_rate) <= 0) {
        Swal.fire('Validation Error', 'Enter a valid USD rate.', 'warning'); return;
    }

    $.ajax({
        url: 'ajax/smspva_sync.php',
        type: 'POST',
        data: {
            action: 'save_settings',
            api_key: api_key,
            markup_percent: markup,
            usd_to_ngn: usd_rate
        },
        dataType: 'json',
        success: function (data) {
            if (data.status == '1') {
                smspvaCurrentRate   = parseFloat(usd_rate);
                smspvaCurrentMarkup = parseFloat(markup);
                smspvaUpdatePriceExample();
                Swal.fire({ title: 'Saved!', text: 'SMSPVA settings saved successfully.', icon: 'success', confirmButtonColor: '#1cc88a' });
            } else {
                Swal.fire('Error!', data.msg, 'error');
            }
        },
        error: function () { Swal.fire('Error!', 'An error occurred.', 'error'); }
    });
}

// ── Refresh Rate Live ─────────────────────────────────────────────────────────
function smspvaRefreshRateLive() {
    Swal.fire({
        title: 'Refreshing Rate...',
        html: 'Fetching live USD → NGN rate...',
        allowOutsideClick: false,
        didOpen: () => { Swal.showLoading(); }
    });
    $.ajax({
        url: 'ajax/smspva_sync.php',
        type: 'POST',
        data: { action: 'refresh_rate' },
        dataType: 'json',
        success: function (data) {
            Swal.close();
            if (data.status == '1') {
                smspvaCurrentRate = parseFloat(data.usd_rate) || smspvaCurrentRate;
                $('#smspva_usd_rate_input').val(smspvaCurrentRate.toFixed(2));
                $('#smspva_rate_updated_time').text(new Date().toLocaleString());
                smspvaUpdatePriceExample();
                Swal.fire({
                    title: 'Updated!',
                    html: '$1 = ₦' + smspvaCurrentRate.toLocaleString('en-NG', {minimumFractionDigits: 2}),
                    icon: 'success',
                    confirmButtonColor: '#1cc88a'
                });
            } else {
                Swal.fire('Warning', data.msg, 'warning');
            }
        },
        error: function () { Swal.close(); Swal.fire('Error', 'Failed to refresh rate.', 'error'); }
    });
}

// ── Resync All Prices ─────────────────────────────────────────────────────────
function smspvaResyncAllPrices() {
    Swal.fire({
        title: 'Resync All SMSPVA Prices?',
        html: 'This re-fetches live prices from <strong>smspva.com</strong> for every service ' +
              'and recalculates ₦ prices using the current rate + markup.<br><br>' +
              '<strong>This may take a few minutes.</strong>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#f6c23e',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Resync',
        cancelButtonText: 'Cancel'
    }).then(function (result) {
        if (!result.isConfirmed) return;
        Swal.fire({
            title: 'Resyncing Prices...',
            html: 'Fetching prices from smspva.com...',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });
        $.ajax({
            url: 'ajax/smspva_sync.php',
            type: 'POST',
            data: { action: 'resync_prices' },
            dataType: 'json',
            timeout: 300000,
            success: function (data) {
                Swal.close();
                if (data.status == '1') {
                    Swal.fire({ title: 'Done!', html: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' });
                } else {
                    Swal.fire('Error!', data.msg, 'error');
                }
            },
            error: function () { Swal.close(); Swal.fire('Error!', 'An error occurred.', 'error'); }
        });
    });
}

// ── Open Sync Modal ───────────────────────────────────────────────────────────
function openSmspvaSyncModal() {
    $('#smspvaSyncResult').addClass('d-none').html('');
    $('#smspvaSyncProgress').addClass('d-none');
    $('#smspvaSyncBar').css('width', '0%');
    $('#smspvaSyncLog').html('');
    $('#smspva_sync_method').val('predefined');
    $('#smspva_manual_codes_wrapper').addClass('d-none');
    $('#submitSmspvaSync').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i>Start Sync');
    $('#smspvaSyncModal').modal('show');
}

// ── Submit Sync Countries ─────────────────────────────────────────────────────
$('#submitSmspvaSync').on('click', function () {
    var method = $('#smspva_sync_method').val();
    var manual_codes = '';

    if (method === 'manual_list') {
        manual_codes = $.trim($('#smspva_manual_codes').val());
        if (!manual_codes) {
            Swal.fire('Validation', 'Please enter at least one country code.', 'warning');
            return;
        }
    }

    $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Syncing...');
    $('#smspvaSyncResult').addClass('d-none').html('');
    $('#smspvaSyncProgress').removeClass('d-none');
    $('#smspvaSyncBar').css('width', '10%');
    $('#smspvaSyncProgressLabel').text('Connecting to smspva.com...');
    $('#smspvaSyncLog').html('');

    $.ajax({
        url: 'ajax/smspva_sync.php',
        type: 'POST',
        data: {
            action: 'sync_countries',
            method: method,
            manual_codes: manual_codes
        },
        dataType: 'json',
        timeout: 300000,
        success: function (data) {
            $('#submitSmspvaSync').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i>Start Sync');
            $('#smspvaSyncBar').css('width', '100%').removeClass('progress-bar-animated');
            $('#smspvaSyncProgressLabel').text('Sync complete!');

            if (data.status == '1') {
                if (data.log && data.log.length > 0) {
                    var logHtml = '';
                    data.log.forEach(function(l) {
                        logHtml += '<div>' + l + '</div>';
                    });
                    $('#smspvaSyncLog').html(logHtml);
                }
                $('#smspvaSyncResult')
                    .removeClass('d-none')
                    .html('<div class="alert alert-success"><i class="fas fa-check-circle mr-2"></i>' + data.msg + '</div>');
                setTimeout(function () {
                    $('#smspvaSyncModal').modal('hide');
                    location.reload();
                }, 2500);
            } else {
                $('#smspvaSyncResult')
                    .removeClass('d-none')
                    .html('<div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i>' + data.msg + '</div>');
            }
        },
        error: function () {
            $('#submitSmspvaSync').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i>Start Sync');
            $('#smspvaSyncResult')
                .removeClass('d-none')
                .html('<div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i>An error occurred. Please try again.</div>');
        }
    });
});

// ── Flag helpers ──────────────────────────────────────────────────────────────
function smspvaPreviewFlag(inputId, previewId) {
    var url = $('#' + inputId).val().trim();
    if (url) {
        $('#' + previewId).attr('src', url).removeClass('d-none');
    } else {
        $('#' + previewId).addClass('d-none').attr('src', '');
    }
}

function smspvaAutoFlag(mode) {
    // smspva uses UPPERCASE, flagcdn uses lowercase
    var codeInputId = (mode === 'add') ? 'smspva_add_server_code' : 'smspva_edit_server_code';
    var flagInputId = (mode === 'add') ? 'smspva_add_flag_url'    : 'smspva_edit_flag_url';
    var previewId   = (mode === 'add') ? 'smspva_add_flag_preview' : 'smspva_edit_flag_preview';

    var code = $.trim($('#' + codeInputId).val()).toLowerCase();
    if (code === 'uk') code = 'gb'; // UK -> GB for flagcdn

    if (!code) {
        Swal.fire('Missing Code', 'Please enter a country code first.', 'warning');
        return;
    }

    var flagUrl = 'https://flagcdn.com/w160/' + code + '.png';
    $('#' + flagInputId).val(flagUrl);
    $('#' + previewId).attr('src', flagUrl).removeClass('d-none');
}

// ── Open Add Modal ────────────────────────────────────────────────────────────
function openSmspvaAddCountryModal() {
    $('#smspva_add_server_name').val('');
    $('#smspva_add_server_code').val('');
    $('#smspva_add_flag_url').val('');
    $('#smspva_add_status').val('1');
    $('#smspva_add_flag_preview').addClass('d-none').attr('src', '');
    $('#smspvaAddCountryModal').modal('show');
}

// ── Submit Add Country ────────────────────────────────────────────────────────
$('#submitSmspvaAddCountry').on('click', function () {
    var server_name = $.trim($('#smspva_add_server_name').val());
    var server_code = $.trim($('#smspva_add_server_code').val()).toUpperCase();
    var flag_url    = $.trim($('#smspva_add_flag_url').val());
    var status      = $('#smspva_add_status').val();

    if (!server_name || !server_code) {
        Swal.fire('Validation Error', 'Country Name and Country Code are required.', 'warning');
        return;
    }

    // Auto-generate flag if empty
    if (!flag_url && server_code.length === 2) {
        var fc = server_code.toLowerCase();
        if (fc === 'uk') fc = 'gb';
        flag_url = 'https://flagcdn.com/w160/' + fc + '.png';
    }

    $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Adding...');

    $.ajax({
        url: 'ajax/smspva_countries.php',
        type: 'POST',
        data: { action: 'add', server_name: server_name, server_code: server_code, flag_url: flag_url, status: status },
        dataType: 'json',
        success: function (data) {
            $('#submitSmspvaAddCountry').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Country');
            if (data.status == '1') {
                $('#smspvaAddCountryModal').modal('hide');
                Swal.fire({ title: 'Added!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                    .then(function () { location.reload(); });
            } else {
                Swal.fire('Error!', data.msg, 'error');
            }
        },
        error: function () {
            $('#submitSmspvaAddCountry').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Country');
            Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
        }
    });
});

// ── Open Edit Modal ───────────────────────────────────────────────────────────
function openSmspvaEditCountryModal(id, name, code, flag, status) {
    $('#smspva_edit_id').val(id);
    $('#smspva_edit_server_name').val(name);
    $('#smspva_edit_server_code').val(code);
    $('#smspva_edit_flag_url').val(flag);
    $('#smspva_edit_status').val(status);

    if (flag) {
        $('#smspva_edit_flag_preview').attr('src', flag).removeClass('d-none');
    } else {
        $('#smspva_edit_flag_preview').addClass('d-none').attr('src', '');
    }
    $('#smspvaEditCountryModal').modal('show');
}

// ── Submit Edit Country ───────────────────────────────────────────────────────
$('#submitSmspvaEditCountry').on('click', function () {
    var id          = $('#smspva_edit_id').val();
    var server_name = $.trim($('#smspva_edit_server_name').val());
    var server_code = $.trim($('#smspva_edit_server_code').val()).toUpperCase();
    var flag_url    = $.trim($('#smspva_edit_flag_url').val());
    var status      = $('#smspva_edit_status').val();

    if (!server_name || !server_code) {
        Swal.fire('Validation Error', 'Country Name and Code are required.', 'warning');
        return;
    }

    $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Saving...');

    $.ajax({
        url: 'ajax/smspva_countries.php',
        type: 'POST',
        data: { action: 'edit', id: id, server_name: server_name, server_code: server_code, flag_url: flag_url, status: status },
        dataType: 'json',
        success: function (data) {
            $('#submitSmspvaEditCountry').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Changes');
            if (data.status == '1') {
                $('#smspvaEditCountryModal').modal('hide');
                Swal.fire({ title: 'Updated!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                    .then(function () { location.reload(); });
            } else {
                Swal.fire('Error!', data.msg, 'error');
            }
        },
        error: function () {
            $('#submitSmspvaEditCountry').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Changes');
            Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
        }
    });
});

// ── Delete Country ────────────────────────────────────────────────────────────
function deleteSmspvaCountry(id, countryName) {
    Swal.fire({
        title: 'Delete Country?',
        html: 'Are you sure you want to delete <strong>' + countryName + '</strong>?<br>' +
              '<small class="text-danger">This will also delete all associated services. Cannot be undone.</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        focusCancel: true
    }).then(function (result) {
        if (result.isConfirmed) {
            Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
            $.ajax({
                url: 'ajax/smspva_countries.php',
                type: 'POST',
                data: { action: 'delete', id: id },
                dataType: 'json',
                success: function (data) {
                    Swal.close();
                    if (data.status == '1') {
                        Swal.fire({ title: 'Deleted!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                            .then(function () { location.reload(); });
                    } else {
                        Swal.fire('Error!', data.msg, 'error');
                    }
                },
                error: function () { Swal.close(); Swal.fire('Error!', 'An error occurred.', 'error'); }
            });
        }
    });
}

// ── Sync services for a single country ───────────────────────────────────────
function syncSmspvaCountryServices(serverId, countryCode, countryName) {
    Swal.fire({
        title: 'Sync Services?',
        html: 'Sync all services for <strong>' + countryName + '</strong> (<code>' + countryCode + '</code>) from smspva.com?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#1cc88a',
        confirmButtonText: 'Yes, Sync',
        cancelButtonText: 'Cancel'
    }).then(function (result) {
        if (!result.isConfirmed) return;

        Swal.fire({
            title: 'Syncing Services...',
            html: 'Fetching services for <strong>' + countryName + '</strong>...',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });

        $.ajax({
            url: 'ajax/smspva_sync.php',
            type: 'POST',
            data: { action: 'sync_services', server_id: serverId },
            dataType: 'json',
            timeout: 120000,
            success: function (data) {
                Swal.close();
                if (data.status == '1') {
                    Swal.fire({ title: 'Sync Complete!', html: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                        .then(function () { location.reload(); });
                } else {
                    Swal.fire('Sync Failed', data.msg, 'error');
                }
            },
            error: function () {
                Swal.close();
                Swal.fire('Error', 'Request timed out or failed. Please try again.', 'error');
            }
        });
    });
}
</script>

<style>
    .flag-img-sm {
        width: 44px; height: 28px; object-fit: contain;
        border: 1px solid #e3e6f0; border-radius: 4px; padding: 2px; background: #fff;
    }
    .flag-preview-box {
        width: 100px; height: 62px; object-fit: contain;
        border: 2px solid #e3e6f0; border-radius: 6px; padding: 4px; background: #fff;
    }
    .btn-group { white-space: nowrap; }
    .dropdown-item { cursor: pointer; }
    .dropdown-item i { width: 20px; margin-right: 5px; }
    .modal-header { border-bottom: 2px solid #e3e6f0; }
    .modal-footer { border-top: 1px solid #e3e6f0; }
    .border-left-warning { border-left: 4px solid #f6c23e !important; }
    code { color: #e83e8c; background: #f8f9fc; padding: 2px 5px; border-radius: 3px; font-size: 0.85em; }
    #smspvaSyncLog div { padding: 2px 0; border-bottom: 1px solid #eee; font-size: .78rem; }
    #smspvaSyncLog div:last-child { border-bottom: none; }
</style>

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