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

// Ensure columns exist (safe to run multiple times)
try {
    $pdo->exec("ALTER TABLE settings
        ADD COLUMN IF NOT EXISTS xtralogtools_api_key  VARCHAR(255) NOT NULL DEFAULT '',
        ADD COLUMN IF NOT EXISTS xtralogtools_api_url  VARCHAR(255) NOT NULL DEFAULT 'https://xtralogstools.com/api/v1',
        ADD COLUMN IF NOT EXISTS xtralogtools_enabled  TINYINT(1)   NOT NULL DEFAULT 0,
        ADD COLUMN IF NOT EXISTS xtralogtools_markup   DECIMAL(6,2) NOT NULL DEFAULT 10.00");
} catch (PDOException $e) { /* columns already exist */ }

// Ensure xtralog_products table exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS xtralog_products (
        id           INT AUTO_INCREMENT PRIMARY KEY,
        product_id   VARCHAR(100) NOT NULL UNIQUE,
        product_name VARCHAR(255) NOT NULL,
        description  TEXT,
        server       TINYINT(1)   NOT NULL DEFAULT 1,
        api_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        our_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        category     VARCHAR(100) NOT NULL DEFAULT '',
        status       TINYINT(1)   NOT NULL DEFAULT 1,
        synced_at    TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        KEY idx_status   (status),
        KEY idx_category (category)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (PDOException $e) { /* table already exists */ }

// Ensure xtralog_orders table exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS xtralog_orders (
        id           INT AUTO_INCREMENT PRIMARY KEY,
        user_id      INT           NOT NULL,
        product_id   VARCHAR(100)  NOT NULL,
        product_name VARCHAR(255)  NOT NULL,
        server       TINYINT(1)    NOT NULL DEFAULT 1,
        quantity     INT           NOT NULL DEFAULT 1,
        unit_price   DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        total_charge DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        order_ref    VARCHAR(100)  NOT NULL UNIQUE,
        api_response TEXT,
        logs_data    LONGTEXT,
        status       ENUM('pending','completed','failed') NOT NULL DEFAULT 'pending',
        created_at   TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at   TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        KEY idx_user_id  (user_id),
        KEY idx_status   (status),
        KEY idx_product  (product_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (PDOException $e) { /* table already exists */ }

// Reload fresh settings
$fresh = $pdo->query("SELECT xtralogtools_api_key, xtralogtools_api_url, xtralogtools_enabled, xtralogtools_markup FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
$xtl_key     = $fresh['xtralogtools_api_key']  ?? '';
$xtl_url     = $fresh['xtralogtools_api_url']  ?? '';
$xtl_enabled = (int)($fresh['xtralogtools_enabled'] ?? 0);
$xtl_markup  = (float)($fresh['xtralogtools_markup'] ?? 10.00);

// Normalise URL
$correct_url = 'https://xtralogstools.com/api/v1';
if (empty($xtl_url) || !filter_var($xtl_url, FILTER_VALIDATE_URL)) {
    $xtl_url = $correct_url;
}
// Always persist the corrected URL back to DB
try {
    $pdo->prepare("UPDATE settings SET xtralogtools_api_url = :url WHERE id = 1")
        ->execute(['url' => $xtl_url]);
} catch (PDOException $e) { /* non-fatal */ }

// Fetch synced products
try {
    $products = $pdo->query("SELECT * FROM xtralog_products ORDER BY category, product_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $products = []; }

// Fetch recent orders
try {
    $orders = $pdo->query("
        SELECT o.*, u.username, u.email
        FROM xtralog_orders o
        LEFT JOIN users u ON o.user_id = u.id
        ORDER BY o.created_at DESC
        LIMIT 50
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $orders = []; }
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<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">
      <i class="fas fa-terminal mr-2 text-primary"></i>TLogs Marketplace — Logs API Settings
    </h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active">Logs API Settings</li>
    </ol>
  </div>

  <!-- ── Status Banner ── -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="card border-left-<?php echo $xtl_enabled ? 'success' : 'warning'; ?> shadow py-2">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
            <div class="d-flex align-items-center gap-3">
              <div>
                <div class="text-xs font-weight-bold text-<?php echo $xtl_enabled ? 'success' : 'warning'; ?> text-uppercase mb-1">
                  XtraLogTools API — <?php echo $xtl_enabled ? 'ENABLED' : 'DISABLED'; ?>
                </div>
                <div class="h6 mb-0 text-gray-700">
                  Endpoint: <code><?php echo htmlspecialchars($xtl_url ?: 'https://xtralogstools.com/api/v1'); ?></code>
                </div>
                <?php if (!empty($xtl_key)): ?>
                <div class="text-xs text-muted mt-1">
                  API Key: <code><?php echo htmlspecialchars(substr($xtl_key, 0, 8) . '••••••••' . substr($xtl_key, -4)); ?></code>
                </div>
                <?php endif; ?>
              </div>
            </div>
            <div class="d-flex gap-2 flex-wrap">
              <button class="btn btn-sm btn-outline-info" onclick="checkBalance()">
                <i class="fas fa-wallet mr-1"></i>Check Balance
              </button>
              <button class="btn btn-sm btn-primary" onclick="syncProducts()">
                <i class="fas fa-sync mr-1"></i>Sync Products
              </button>
              <button class="btn btn-sm btn-outline-warning" onclick="debugRawResponse()">
                <i class="fas fa-bug mr-1"></i>Debug Raw API
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="row">

    <!-- ── Settings Form ── -->
    <div class="col-xl-5 col-lg-5 mb-4">
      <div class="card shadow">
        <div class="card-header py-3 bg-primary text-white">
          <h6 class="m-0 font-weight-bold"><i class="fas fa-cog mr-2"></i>API Configuration</h6>
        </div>
        <div class="card-body">
          <form id="xtlSettingsForm">

            <div class="form-group">
              <div class="custom-control custom-switch">
                <input type="checkbox" class="custom-control-input" id="xtralogtools_enabled"
                       name="xtralogtools_enabled" value="1"
                       <?php echo $xtl_enabled ? 'checked' : ''; ?>>
                <label class="custom-control-label font-weight-bold" for="xtralogtools_enabled">
                  Enable Logs API
                </label>
              </div>
              <small class="text-muted">When enabled, users can buy logs from TLogs Marketplace on the Buy Logs page.</small>
            </div>

            <div class="form-group">
              <label class="font-weight-bold">API Key <span class="text-danger">*</span></label>
              <div class="input-group">
                <input type="password" class="form-control" id="xtralogtools_api_key"
                       name="xtralogtools_api_key"
                       value="<?php echo htmlspecialchars($xtl_key); ?>"
                       placeholder="Your XtraLogTools API key">
                <div class="input-group-append">
                  <button class="btn btn-outline-secondary" type="button"
                          onclick="toggleVis('xtralogtools_api_key', this)">
                    <i class="fas fa-eye"></i>
                  </button>
                </div>
              </div>
              <small class="text-muted">Get your API key from <a href="https://xtralogstools.com" target="_blank">xtralogstools.com</a></small>
            </div>

            <div class="form-group">
              <label class="font-weight-bold">API Base URL</label>
              <input type="url" class="form-control" id="xtralogtools_api_url"
                     name="xtralogtools_api_url"
                     value="<?php echo htmlspecialchars($xtl_url); ?>"
                     placeholder="https://xtralogstools.com/api/v1">
              <small class="text-muted">Default: <code>https://xtralogstools.com/api/v1</code></small>
            </div>

            <div class="form-group">
              <label class="font-weight-bold">Markup Percentage (%)</label>
              <div class="input-group">
                <input type="number" class="form-control" id="xtralogtools_markup"
                       name="xtralogtools_markup"
                       value="<?php echo $xtl_markup; ?>"
                       min="0" max="500" step="0.01">
                <div class="input-group-append"><span class="input-group-text">%</span></div>
              </div>
              <small class="text-muted">Added on top of the API price when syncing products. E.g. 10% on ₦1000 = ₦1100 charged to user.</small>
            </div>

            <button type="button" class="btn btn-primary btn-block" onclick="saveSettings()">
              <i class="fas fa-save mr-1"></i>Save Settings
            </button>
          </form>
        </div>
      </div>

      <!-- ── API Info Card ── -->
      <div class="card shadow mt-4">
        <div class="card-header py-3 bg-info text-white">
          <h6 class="m-0 font-weight-bold"><i class="fas fa-info-circle mr-2"></i>API Reference</h6>
        </div>
        <div class="card-body small">
          <p class="font-weight-bold mb-1">Buy Logs — Required Parameters (POST):</p>
          <table class="table table-sm table-bordered mb-3">
            <thead class="thead-light"><tr><th>Param</th><th>Required</th><th>Description</th></tr></thead>
            <tbody>
              <tr><td><code>api_key</code></td><td><span class="badge badge-danger">YES</span></td><td>Your API Key</td></tr>
              <tr><td><code>action</code></td><td><span class="badge badge-danger">YES</span></td><td>Must be <code>buy</code></td></tr>
              <tr><td><code>productid</code></td><td><span class="badge badge-danger">YES</span></td><td>Product ID to buy</td></tr>
              <tr><td><code>amount</code></td><td><span class="badge badge-danger">YES</span></td><td>Quantity to buy</td></tr>
              <tr><td><code>coupon</code></td><td><span class="badge badge-secondary">NO</span></td><td>Discount code if available</td></tr>
            </tbody>
          </table>
          <p class="font-weight-bold mb-1">Success Response:</p>
          <pre class="bg-light p-2 rounded" style="font-size:.75rem;">{"status": "success", "msg": "Order created!", "trans_id": "...", "data": ["account1|token1", ...]}</pre>
        </div>
      </div>
    </div>

    <!-- ── Products Table ── -->
    <div class="col-xl-7 col-lg-7 mb-4">
      <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-list mr-2"></i>Synced Products
            <span class="badge badge-primary ml-1"><?php echo count($products); ?></span>
          </h6>
          <div class="d-flex gap-2">
            <button class="btn btn-sm btn-success" onclick="syncProducts()">
              <i class="fas fa-sync mr-1"></i>Sync Now
            </button>
            <button class="btn btn-sm btn-danger ml-2" onclick="deleteAllProducts()">
              <i class="fas fa-trash mr-1"></i>Delete All
            </button>
          </div>
        </div>
        <div class="table-responsive">
          <table class="table table-hover table-sm align-items-center mb-0" id="productsTable">
            <thead class="thead-light">
              <tr>
                <th>Product ID</th>
                <th>Name</th>
                <th>Category</th>
                <th>Server</th>
                <th>API Price</th>
                <th>Our Price</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($products)): ?>
              <tr>
                <td colspan="8" class="text-center text-muted py-4">
                  <i class="fas fa-box-open fa-2x mb-2 d-block"></i>
                  No products synced yet. Click <strong>Sync Now</strong> to fetch from the API.
                </td>
              </tr>
              <?php else: ?>
              <?php foreach ($products as $p): ?>
              <tr>
                <td><code class="small"><?php echo htmlspecialchars($p['product_id']); ?></code></td>
                <td class="font-weight-bold small"><?php echo htmlspecialchars($p['product_name']); ?></td>
                <td><span class="badge badge-light"><?php echo htmlspecialchars($p['category'] ?: '—'); ?></span></td>
                <td><span class="badge badge-info">S<?php echo (int)$p['server']; ?></span></td>
                <td class="small">₦<?php echo number_format($p['api_price'], 2); ?></td>
                <td>
                  <input type="number" class="form-control form-control-sm price-input"
                         style="width:90px;"
                         data-id="<?php echo (int)$p['id']; ?>"
                         value="<?php echo number_format($p['our_price'], 2, '.', ''); ?>"
                         min="0" step="0.01">
                </td>
                <td>
                  <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input status-toggle"
                           id="st_<?php echo $p['id']; ?>"
                           data-id="<?php echo (int)$p['id']; ?>"
                           <?php echo $p['status'] ? 'checked' : ''; ?>>
                    <label class="custom-control-label" for="st_<?php echo $p['id']; ?>"></label>
                  </div>
                </td>
                <td>
                  <button class="btn btn-xs btn-primary save-price-btn"
                          data-id="<?php echo (int)$p['id']; ?>">
                    <i class="fas fa-save"></i>
                  </button>
                </td>
              </tr>
              <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- ── Recent Orders ── -->
      <div class="card shadow mt-4">
        <div class="card-header py-3">
          <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-receipt mr-2"></i>Recent API Log Orders
            <span class="badge badge-secondary ml-1"><?php echo count($orders); ?></span>
          </h6>
        </div>
        <div class="table-responsive">
          <table class="table table-hover table-sm mb-0">
            <thead class="thead-light">
              <tr>
                <th>#</th>
                <th>User</th>
                <th>Product</th>
                <th>Qty</th>
                <th>Charged</th>
                <th>Status</th>
                <th>Date</th>
                <th>Logs</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($orders)): ?>
              <tr><td colspan="8" class="text-center text-muted py-3">No orders yet.</td></tr>
              <?php else: ?>
              <?php foreach ($orders as $o):
                $badge = match($o['status']) {
                    'completed' => 'success',
                    'failed'    => 'danger',
                    default     => 'warning',
                };
              ?>
              <tr>
                <td><?php echo (int)$o['id']; ?></td>
                <td class="small">
                  <strong><?php echo htmlspecialchars($o['username'] ?? '—'); ?></strong><br>
                  <span class="text-muted"><?php echo htmlspecialchars($o['email'] ?? ''); ?></span>
                </td>
                <td class="small">
                  <?php echo htmlspecialchars($o['product_name']); ?><br>
                  <code class="text-muted" style="font-size:.7rem;"><?php echo htmlspecialchars($o['product_id']); ?></code>
                </td>
                <td><?php echo (int)$o['quantity']; ?></td>
                <td class="font-weight-bold">₦<?php echo number_format($o['total_charge'], 2); ?></td>
                <td><span class="badge badge-<?php echo $badge; ?>"><?php echo ucfirst($o['status']); ?></span></td>
                <td class="small text-muted"><?php echo date('M d, Y H:i', strtotime($o['created_at'])); ?></td>
                <td>
                  <?php if ($o['status'] === 'completed' && !empty($o['logs_data'])): ?>
                  <button class="btn btn-xs btn-outline-primary"
                          onclick='viewLogs(<?php echo $o["id"]; ?>, <?php echo json_encode($o["logs_data"]); ?>)'>
                    <i class="fas fa-eye"></i>
                  </button>
                  <?php else: ?>
                  <span class="text-muted">—</span>
                  <?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- ── View Logs Modal ── -->
<div class="modal fade" id="viewLogsModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title font-weight-bold text-primary">
          <i class="fas fa-key mr-2"></i>Log Credentials — Order #<span id="modal_order_id"></span>
        </h5>
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-warning small py-2">
          <i class="fas fa-triangle-exclamation mr-1"></i>
          Keep these credentials confidential. Do not share outside of the platform.
        </div>
        <pre id="modal_logs_content"
             style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:6px;
                    padding:14px;white-space:pre-wrap;word-break:break-all;
                    font-size:.82rem;max-height:400px;overflow-y:auto;"></pre>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" onclick="copyLogs()">
          <i class="fas fa-copy mr-1"></i>Copy
        </button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// ── Toggle password visibility ────────────────────────────────────────────────
function toggleVis(id, btn) {
    var inp = document.getElementById(id);
    if (inp.type === 'password') {
        inp.type = 'text';
        btn.innerHTML = '<i class="fas fa-eye-slash"></i>';
    } else {
        inp.type = 'password';
        btn.innerHTML = '<i class="fas fa-eye"></i>';
    }
}

// ── Save Settings ─────────────────────────────────────────────────────────────
function saveSettings() {
    var data = {
        action:                  'save_xtralogtools_settings',
        xtralogtools_api_key:    $('#xtralogtools_api_key').val().trim(),
        xtralogtools_api_url:    $('#xtralogtools_api_url').val().trim(),
        xtralogtools_enabled:    $('#xtralogtools_enabled').is(':checked') ? 1 : 0,
        xtralogtools_markup:     $('#xtralogtools_markup').val(),
    };

    if (!data.xtralogtools_api_key) {
        Swal.fire('Validation', 'API Key is required.', 'warning');
        return;
    }

    $.ajax({
        url: 'ajax/logs_api_handler.php',
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(res) {
            if (res.status === '1') {
                Swal.fire({ title: 'Saved!', text: res.msg, icon: 'success', timer: 1800, showConfirmButton: false })
                    .then(function() { location.reload(); });
            } else {
                Swal.fire('Error', res.msg || 'Failed to save settings.', 'error');
            }
        },
        error: function() { Swal.fire('Error', 'Request failed.', 'error'); }
    });
}

// ── Check Balance ─────────────────────────────────────────────────────────────
function checkBalance() {
    var key = $('#xtralogtools_api_key').val().trim();
    var url = $('#xtralogtools_api_url').val().trim();
    if (!key) { Swal.fire('Missing', 'Enter your API key first.', 'warning'); return; }

    Swal.fire({ title: 'Checking balance...', allowOutsideClick: false, didOpen: function() { Swal.showLoading(); } });

    $.ajax({
        url: 'ajax/logs_api_handler.php',
        type: 'POST',
        data: { action: 'check_xtralogtools_balance', api_key: key, api_url: url },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1') {
                Swal.fire({ title: 'Balance', html: '<strong>' + res.balance + '</strong>', icon: 'success' });
            } else {
                Swal.fire('Error', res.msg || 'Could not fetch balance.', 'error');
            }
        },
        error: function() { Swal.fire('Error', 'Request failed.', 'error'); }
    });
}

// ── Sync Products ─────────────────────────────────────────────────────────────
function syncProducts() {
    var key    = $('#xtralogtools_api_key').val().trim();
    var url    = $('#xtralogtools_api_url').val().trim();
    var markup = parseFloat($('#xtralogtools_markup').val()) || 0;

    if (!key) { Swal.fire('Missing', 'Enter and save your API key first.', 'warning'); return; }

    Swal.fire({ title: 'Syncing products...', text: 'Fetching from TLogs Marketplace API...', allowOutsideClick: false, didOpen: function() { Swal.showLoading(); } });

    $.ajax({
        url: 'ajax/logs_api_handler.php',
        type: 'POST',
        data: { action: 'sync_xtralogtools_products', api_key: key, api_url: url, markup: markup },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1') {
                Swal.fire({ title: 'Synced!', text: res.msg, icon: 'success' })
                    .then(function() { location.reload(); });
            } else {
                Swal.fire('Sync Failed', res.msg || 'Could not sync products.', 'error');
            }
        },
        error: function() { Swal.fire('Error', 'Request failed.', 'error'); }
    });
}

// ── Save individual product price ─────────────────────────────────────────────
$(document).on('click', '.save-price-btn', function() {
    var id    = $(this).data('id');
    var price = $('input.price-input[data-id="' + id + '"]').val();
    var btn   = $(this);

    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');

    $.ajax({
        url: 'ajax/logs_api_handler.php',
        type: 'POST',
        data: { action: 'update_xtralog_product_price', product_db_id: id, our_price: price },
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-save"></i>');
            if (res.status === '1') {
                btn.removeClass('btn-primary').addClass('btn-success');
                setTimeout(function() { btn.removeClass('btn-success').addClass('btn-primary'); }, 2000);
            } else {
                Swal.fire('Error', res.msg, 'error');
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-save"></i>');
            Swal.fire('Error', 'Request failed.', 'error');
        }
    });
});

// ── Toggle product status ─────────────────────────────────────────────────────
$(document).on('change', '.status-toggle', function() {
    var id      = $(this).data('id');
    var enabled = $(this).is(':checked') ? 1 : 0;
    var toggle  = $(this);

    $.ajax({
        url: 'ajax/logs_api_handler.php',
        type: 'POST',
        data: { action: 'toggle_xtralog_product', product_db_id: id, status: enabled },
        dataType: 'json',
        success: function(res) {
            if (res.status !== '1') {
                toggle.prop('checked', !enabled); // revert
                Swal.fire('Error', res.msg, 'error');
            }
        },
        error: function() {
            toggle.prop('checked', !enabled);
            Swal.fire('Error', 'Request failed.', 'error');
        }
    });
});

// ── View Logs Modal ───────────────────────────────────────────────────────────
function viewLogs(orderId, logsData) {
    document.getElementById('modal_order_id').textContent = orderId;
    document.getElementById('modal_logs_content').textContent = logsData;
    $('#viewLogsModal').modal('show');
}

// ── Delete All Products ───────────────────────────────────────────────────────
function deleteAllProducts() {
    Swal.fire({
        title: 'Delete All Products?',
        text: 'This will remove all ' + <?php echo count($products); ?> + ' synced products from the database. This cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        confirmButtonText: 'Yes, delete all',
        cancelButtonText: 'Cancel'
    }).then(function(result) {
        if (!result.isConfirmed) return;

        Swal.fire({ title: 'Deleting...', allowOutsideClick: false, didOpen: function() { Swal.showLoading(); } });

        $.ajax({
            url: 'ajax/logs_api_handler.php',
            type: 'POST',
            data: { action: 'delete_all_xtralog_products' },
            dataType: 'json',
            success: function(res) {
                if (res.status === '1') {
                    Swal.fire({ title: 'Deleted!', text: res.msg, icon: 'success', timer: 1800, showConfirmButton: false })
                        .then(function() { location.reload(); });
                } else {
                    Swal.fire('Error', res.msg || 'Failed to delete products.', 'error');
                }
            },
            error: function() { Swal.fire('Error', 'Request failed.', 'error'); }
        });
    });
}

function debugRawResponse() {
    var key = $('#xtralogtools_api_key').val().trim();
    var url = $('#xtralogtools_api_url').val().trim();
    if (!key) { Swal.fire('Missing', 'Enter your API key first.', 'warning'); return; }

    Swal.fire({ title: 'Fetching raw API response...', allowOutsideClick: false, didOpen: function() { Swal.showLoading(); } });

    $.ajax({
        url: 'ajax/logs_api_handler.php',
        type: 'POST',
        data: { action: 'debug_xtralogtools_raw', api_key: key, api_url: url },
        dataType: 'json',
        success: function(res) {
            var topKeys = Array.isArray(res.top_keys) ? res.top_keys.join(', ') : res.top_keys;
            var rawStr  = JSON.stringify(res.raw, null, 2);
            // Truncate if huge
            if (rawStr.length > 3000) rawStr = rawStr.substring(0, 3000) + '\n... (truncated)';

            Swal.fire({
                title: 'Raw API Response',
                width: '800px',
                html:
                    '<div class="text-left">' +
                    '<p><strong>URL used:</strong> <code>' + res.url_used + '</code></p>' +
                    '<p><strong>HTTP Code:</strong> ' + res.http_code + ' &nbsp; <strong>Success:</strong> ' + res.success + '</p>' +
                    '<p><strong>Top-level keys:</strong> <code>' + topKeys + '</code></p>' +
                    (res.error ? '<p class="text-danger"><strong>Error:</strong> ' + res.error + '</p>' : '') +
                    '<pre style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:4px;padding:10px;font-size:.75rem;max-height:350px;overflow-y:auto;text-align:left;white-space:pre-wrap;word-break:break-all;">' + rawStr + '</pre>' +
                    '</div>',
                icon: res.success ? 'info' : 'error',
                confirmButtonText: 'Close',
            });
        },
        error: function(xhr) {
            Swal.fire('Error', 'Request failed. Status: ' + xhr.status, 'error');
        }
    });
}

function copyLogs() {
    var text = document.getElementById('modal_logs_content').textContent;
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(function() {
            Swal.fire({ title: 'Copied!', icon: 'success', timer: 1200, showConfirmButton: false });
        });
    } else {
        var ta = document.createElement('textarea');
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        Swal.fire({ title: 'Copied!', icon: 'success', timer: 1200, showConfirmButton: false });
    }
}
</script>

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