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

// Load settings
$cfg = $pdo->query("SELECT * FROM settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);

// Pagination for products
$per_page    = 50;
$current_pg  = max(1, (int)($_GET['page'] ?? 1));
$offset      = ($current_pg - 1) * $per_page;
$search      = trim($_GET['q'] ?? '');
$filter_cc   = trim($_GET['cc'] ?? '');
$filter_stat = $_GET['status'] ?? '';

$where  = [];
$params = [];
if ($search !== '') {
    $where[]          = "(product_name LIKE :q OR brand_name LIKE :q2)";
    $params[':q']     = "%{$search}%";
    $params[':q2']    = "%{$search}%";
}
if ($filter_cc !== '') {
    $where[]         = "country_code = :cc";
    $params[':cc']   = $filter_cc;
}
if ($filter_stat !== '') {
    $where[]           = "status = :st";
    $params[':st']     = (int)$filter_stat;
}
$sql_where = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$total_stmt = $pdo->prepare("SELECT COUNT(*) FROM gift_card_products {$sql_where}");
$total_stmt->execute($params);
$total_rows  = (int)$total_stmt->fetchColumn();
$total_pages = max(1, ceil($total_rows / $per_page));

$prod_stmt = $pdo->prepare("SELECT * FROM gift_card_products {$sql_where} ORDER BY product_name ASC LIMIT {$per_page} OFFSET {$offset}");
$prod_stmt->execute($params);
$products = $prod_stmt->fetchAll(PDO::FETCH_ASSOC);

// Country list for filter
$countries = $pdo->query("SELECT DISTINCT country_code, country_name FROM gift_card_products ORDER BY country_name ASC")->fetchAll(PDO::FETCH_ASSOC);
?>

<title>Gift Cards – Reloadly | <?php echo htmlspecialchars($cfg['web_name']); ?></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">🎁 Gift Cards – Reloadly</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
      <li class="breadcrumb-item active">Reloadly</li>
    </ol>
  </div>

  <!-- ══════════════════════════════════════════
       RELOADLY API SETTINGS CARD
  ══════════════════════════════════════════ -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex align-items-center justify-content-between" style="background:linear-gradient(135deg,#6f42c1,#4e2d8e);color:#fff;">
      <h6 class="m-0 font-weight-bold"><i class="fas fa-key mr-2"></i>Reloadly API Settings</h6>
      <button class="btn btn-sm btn-light" type="button" data-toggle="collapse" data-target="#reloadlySettingsBody">
        <i class="fas fa-chevron-down"></i>
      </button>
    </div>
    <div class="collapse show" id="reloadlySettingsBody">
      <div class="card-body">
        <form id="reloadlySettingsForm">
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Client ID</strong></label>
                <input type="text" class="form-control" name="reloadly_client_id" id="reloadly_client_id"
                  value="<?php echo htmlspecialchars($cfg['reloadly_client_id'] ?? ''); ?>" placeholder="Reloadly Client ID" autocomplete="off">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Client Secret</strong></label>
                <div class="input-group">
                  <input type="password" class="form-control" name="reloadly_client_secret" id="reloadly_client_secret"
                    value="<?php echo htmlspecialchars($cfg['reloadly_client_secret'] ?? ''); ?>" placeholder="Reloadly Client Secret" autocomplete="off">
                  <div class="input-group-append">
                    <button class="btn btn-outline-secondary" type="button" onclick="toggleVis('reloadly_client_secret',this)">
                      <i class="fas fa-eye"></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Mode</strong></label>
                <select class="form-control" name="reloadly_sandbox">
                  <option value="0" <?php echo empty($cfg['reloadly_sandbox']) ? 'selected' : ''; ?>>🟢 Live</option>
                  <option value="1" <?php echo !empty($cfg['reloadly_sandbox']) ? 'selected' : ''; ?>>🧪 Sandbox</option>
                </select>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Enable Gift Cards</strong></label>
                <select class="form-control" name="reloadly_enabled">
                  <option value="1" <?php echo !empty($cfg['reloadly_enabled']) ? 'selected' : ''; ?>>✅ Enabled</option>
                  <option value="0" <?php echo empty($cfg['reloadly_enabled']) ? 'selected' : ''; ?>>❌ Disabled</option>
                </select>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Markup % (on top of cost)</strong></label>
                <div class="input-group">
                  <input type="number" step="0.01" min="0" class="form-control" name="reloadly_markup" id="reloadly_markup"
                    value="<?php echo htmlspecialchars($cfg['reloadly_markup'] ?? '10'); ?>">
                  <div class="input-group-append"><span class="input-group-text">%</span></div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>USD → NGN Rate</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="1" class="form-control" name="reloadly_ngn_rate" id="reloadly_ngn_rate"
                    value="<?php echo htmlspecialchars($cfg['reloadly_ngn_rate'] ?? '1600'); ?>">
                </div>
              </div>
            </div>
          </div>

          <div class="row align-items-center mt-2">
            <div class="col-auto">
              <button type="submit" class="btn btn-primary px-4">
                <i class="fas fa-save mr-1"></i> Save API Settings
              </button>
            </div>
            <div class="col-auto">
              <button type="button" class="btn btn-success px-4" onclick="syncGiftCards(this)">
                <i class="fas fa-sync-alt mr-1"></i> Sync Products from Reloadly
              </button>
            </div>
            <div class="col-auto">
              <button type="button" class="btn btn-warning px-4" onclick="recalcPrices(this)">
                <i class="fas fa-calculator mr-1"></i> Recalculate All Prices
              </button>
            </div>
            <?php if (!empty($cfg['reloadly_last_sync'])): ?>
            <div class="col-auto text-muted small">
              <i class="fas fa-clock mr-1"></i> Last sync: <span id="lastSyncLabel"><?php echo $cfg['reloadly_last_sync']; ?></span>
            </div>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- ══════════════════════════════════════════
       PRODUCT LIST CARD
  ══════════════════════════════════════════ -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex align-items-center justify-content-between" style="background:linear-gradient(135deg,#1cc88a,#17a673);color:#fff;">
      <h6 class="m-0 font-weight-bold"><i class="fas fa-gift mr-2"></i>Product Catalog
        <span class="badge badge-light ml-2"><?php echo number_format($total_rows); ?> products</span>
      </h6>
    </div>
    <div class="card-body pb-2">
      <!-- Filters -->
      <form method="GET" action="" class="row mb-3">
        <div class="col-md-4 mb-2">
          <div class="input-group">
            <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-search"></i></span></div>
            <input type="text" class="form-control" name="q" placeholder="Search product or brand…" value="<?php echo htmlspecialchars($search); ?>">
          </div>
        </div>
        <div class="col-md-3 mb-2">
          <select class="form-control" name="cc">
            <option value="">All Countries</option>
            <?php foreach ($countries as $c): ?>
              <option value="<?php echo htmlspecialchars($c['country_code']); ?>" <?php echo $filter_cc === $c['country_code'] ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($c['country_name'] . ' (' . $c['country_code'] . ')'); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2 mb-2">
          <select class="form-control" name="status">
            <option value="">All Status</option>
            <option value="1" <?php echo $filter_stat === '1' ? 'selected' : ''; ?>>Active</option>
            <option value="0" <?php echo $filter_stat === '0' ? 'selected' : ''; ?>>Hidden</option>
          </select>
        </div>
        <div class="col-md-3 mb-2 d-flex gap-2">
          <button class="btn btn-primary mr-2" type="submit"><i class="fas fa-filter mr-1"></i>Filter</button>
          <a href="reloadly-settings" class="btn btn-secondary">Reset</a>
        </div>
      </form>

      <!-- Table -->
      <div class="table-responsive">
        <table class="table table-hover table-sm table-bordered align-middle" id="productsTable">
          <thead class="thead-dark">
            <tr>
              <th width="50">#</th>
              <th width="55">Image</th>
              <th>Product Name</th>
              <th>Brand</th>
              <th width="55">Country</th>
              <th width="55">Currency</th>
              <th>Denominations / Range</th>
              <th width="75">Markup %</th>
              <th width="80">NGN Rate</th>
              <th width="65">Status</th>
              <th width="110">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($products)): ?>
              <tr><td colspan="11" class="text-center text-muted py-4">
                <i class="fas fa-box-open fa-2x mb-2 d-block"></i>No products found. Try syncing from Reloadly.
              </td></tr>
            <?php else: ?>
              <?php foreach ($products as $i => $p): ?>
                <?php
                  $denoms = '';
                  if ($p['is_range']) {
                      $denoms = '<span class="text-info">Range: ' . htmlspecialchars($p['min_amount']) . ' – ' . htmlspecialchars($p['max_amount']) . ' ' . htmlspecialchars($p['currency_code']) . '</span>';
                  } else {
                      $arr = json_decode($p['denominations'] ?? '[]', true);
                      $denoms = implode(', ', array_map(fn($v) => htmlspecialchars($v), array_slice($arr, 0, 5)));
                      if (count($arr) > 5) $denoms .= ' <span class="text-muted">+' . (count($arr) - 5) . ' more</span>';
                  }
                ?>
                <tr>
                  <td><?php echo $offset + $i + 1; ?></td>
                  <td>
                    <?php if ($p['image_url']): ?>
                      <img src="<?php echo htmlspecialchars($p['image_url']); ?>" width="36" height="36" style="object-fit:contain;border-radius:4px;" onerror="this.src='images/no-image.png'">
                    <?php else: ?>
                      <span class="text-muted">—</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <strong><?php echo htmlspecialchars($p['product_name']); ?></strong>
                    <br><small class="text-muted">ID: <?php echo $p['product_id']; ?></small>
                  </td>
                  <td><?php echo htmlspecialchars($p['brand_name'] ?? '—'); ?></td>
                  <td><span class="badge badge-secondary"><?php echo htmlspecialchars($p['country_code']); ?></span></td>
                  <td><?php echo htmlspecialchars($p['currency_code']); ?></td>
                  <td><small><?php echo $denoms; ?></small></td>
                  <td><?php echo $p['markup_percent']; ?>%</td>
                  <td>₦<?php echo number_format($p['ngn_sell_rate'], 2); ?></td>
                  <td>
                    <?php if ($p['status']): ?>
                      <span class="badge badge-success">Active</span>
                    <?php else: ?>
                      <span class="badge badge-danger">Hidden</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <button class="btn btn-xs btn-primary mb-1"
                      onclick="editProduct(<?php echo htmlspecialchars(json_encode($p)); ?>)"
                      title="Edit"><i class="fas fa-edit"></i> Edit</button>
                    <button class="btn btn-xs btn-danger"
                      onclick="deleteProduct(<?php echo $p['id']; ?>, '<?php echo addslashes($p['product_name']); ?>')"
                      title="Delete"><i class="fas fa-trash"></i> Del</button>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <nav>
        <ul class="pagination pagination-sm flex-wrap">
          <?php
          $qs = http_build_query(['q' => $search, 'cc' => $filter_cc, 'status' => $filter_stat]);
          for ($pg = 1; $pg <= $total_pages; $pg++):
          ?>
            <li class="page-item <?php echo $pg === $current_pg ? 'active' : ''; ?>">
              <a class="page-link" href="?<?php echo $qs; ?>&page=<?php echo $pg; ?>"><?php echo $pg; ?></a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>
      <?php endif; ?>
    </div>
  </div>
</div><!-- /container -->

<!-- ══════════════════════════════════════════
     EDIT PRODUCT MODAL
══════════════════════════════════════════ -->
<div class="modal fade" id="editProductModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header" style="background:linear-gradient(135deg,#4e73df,#224abe);color:#fff;">
        <h5 class="modal-title"><i class="fas fa-edit mr-2"></i>Edit Gift Card Product</h5>
        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
      </div>
      <form id="editProductForm">
        <div class="modal-body">
          <input type="hidden" name="action" value="edit_product">
          <input type="hidden" name="id" id="ep_id">
          <div class="row">
            <div class="col-md-8">
              <div class="form-group">
                <label><strong>Product Name</strong></label>
                <input type="text" class="form-control" name="product_name" id="ep_product_name" required>
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label><strong>Brand Name</strong></label>
                <input type="text" class="form-control" name="brand_name" id="ep_brand_name">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label><strong>Markup %</strong></label>
                <div class="input-group">
                  <input type="number" step="0.01" min="0" class="form-control" name="markup_percent" id="ep_markup_percent" required>
                  <div class="input-group-append"><span class="input-group-text">%</span></div>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label><strong>NGN Sell Rate (per 1 <?php echo 'USD'; ?>)</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="1" class="form-control" name="ngn_sell_rate" id="ep_ngn_sell_rate" required>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label><strong>Status</strong></label>
                <select class="form-control" name="status" id="ep_status">
                  <option value="1">✅ Active (visible to users)</option>
                  <option value="0">❌ Hidden</option>
                </select>
              </div>
            </div>
            <div class="col-md-12" id="ep_denoms_row">
              <div class="form-group">
                <label><strong>Denominations (JSON array)</strong></label>
                <input type="text" class="form-control" name="denominations" id="ep_denominations" placeholder='e.g. [5,10,25,50,100]'>
                <small class="text-muted">Comma-separated values will be converted. Leave blank for range products.</small>
              </div>
            </div>
            <div class="col-md-6" id="ep_range_row_min" style="display:none;">
              <div class="form-group">
                <label><strong>Min Amount</strong></label>
                <input type="number" step="0.01" class="form-control" name="min_amount" id="ep_min_amount">
              </div>
            </div>
            <div class="col-md-6" id="ep_range_row_max" style="display:none;">
              <div class="form-group">
                <label><strong>Max Amount</strong></label>
                <input type="number" step="0.01" class="form-control" name="max_amount" id="ep_max_amount">
              </div>
            </div>
            <div class="col-md-12">
              <div class="form-group">
                <label><strong>Image URL</strong></label>
                <input type="text" class="form-control" name="image_url" id="ep_image_url">
              </div>
            </div>
          </div>
          <!-- Read-only info -->
          <div class="alert alert-light border small mt-1 mb-0">
            <strong>Reloadly Product ID:</strong> <span id="ep_product_id_display"></span> &nbsp;|&nbsp;
            <strong>Country:</strong> <span id="ep_country_display"></span> &nbsp;|&nbsp;
            <strong>Currency:</strong> <span id="ep_currency_display"></span> &nbsp;|&nbsp;
            <strong>Discount from Reloadly:</strong> <span id="ep_discount_display"></span>%
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary"><i class="fas fa-save mr-1"></i>Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- ═══════ JS ═══════ -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// ── Show/hide password ─────────────────────────────────────────
function toggleVis(fieldId, btn) {
  var input = document.getElementById(fieldId);
  var icon  = btn.querySelector('i');
  input.type = input.type === 'password' ? 'text' : 'password';
  icon.className = input.type === 'password' ? 'fas fa-eye' : 'fas fa-eye-slash';
}

// ── Save Reloadly API Settings ─────────────────────────────────
document.getElementById('reloadlySettingsForm').addEventListener('submit', function(e) {
  e.preventDefault();
  var fd = new FormData(this);
  fd.append('action', 'save_reloadly_settings');
  Swal.fire({ title: 'Saving…', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
  fetch('ajax/reloadly_ajax.php', { method: 'POST', body: fd })
    .then(r => r.json()).then(d => {
      Swal.close();
      if (d.status == '1') {
        Swal.fire({ icon: 'success', title: 'Saved!', text: d.msg, confirmButtonColor: '#1cc88a' });
      } else {
        Swal.fire({ icon: 'error', title: 'Error', text: d.msg });
      }
    }).catch(() => Swal.fire('Error', 'Could not reach server.', 'error'));
});

// ── Sync Products ──────────────────────────────────────────────
function syncGiftCards(btn) {
  var clientId = document.getElementById('reloadly_client_id').value.trim();
  if (!clientId) {
    Swal.fire('Missing Credentials', 'Please save your Reloadly API credentials first.', 'warning');
    return;
  }
  Swal.fire({
    title: '🔄 Syncing Products…',
    html: 'Fetching gift card catalog from Reloadly.<br><small class="text-muted">This may take 20–60 seconds depending on catalog size.</small>',
    allowOutsideClick: false,
    didOpen: () => Swal.showLoading()
  });
  $.ajax({
    url: 'ajax/reloadly_ajax.php', type: 'POST',
    data: { action: 'sync_giftcards' },
    dataType: 'json',
    timeout: 120000,
    success: function(res) {
      Swal.close();
      if (res.status === '1') {
        Swal.fire({ icon: 'success', title: 'Sync Complete!', html: res.msg, confirmButtonColor: '#1cc88a' })
          .then(() => location.reload());
      } else {
        Swal.fire('Sync Failed', res.msg, 'error');
      }
    },
    error: function() { Swal.close(); Swal.fire('Error', 'Request timed out or server error.', 'error'); }
  });
}

// ── Recalculate All Prices ────────────────────────────────────
function recalcPrices(btn) {
  var markup = parseFloat(document.getElementById('reloadly_markup').value);
  var rate   = parseFloat(document.getElementById('reloadly_ngn_rate').value);
  if (isNaN(markup) || isNaN(rate)) {
    Swal.fire('Missing Values', 'Enter a valid Markup % and NGN Rate first.', 'warning');
    return;
  }
  Swal.fire({
    title: 'Recalculate All Gift Card Prices?',
    html: 'This will update <strong>ngn_sell_rate</strong> and <strong>markup_percent</strong> for <strong>all</strong> products.<br><br>'
        + '<strong>Markup:</strong> ' + markup + '%<br>'
        + '<strong>NGN Rate:</strong> ₦' + rate.toLocaleString() + ' per USD',
    icon: 'warning', showCancelButton: true,
    confirmButtonText: 'Yes, Recalculate', confirmButtonColor: '#f6c23e'
  }).then(function(r) {
    if (!r.isConfirmed) return;
    Swal.fire({ title: 'Recalculating…', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    $.ajax({
      url: 'ajax/reloadly_ajax.php', type: 'POST',
      data: { action: 'recalc_giftcard_prices', markup: markup, ngn_rate: rate },
      dataType: 'json',
      success: function(res) {
        Swal.close();
        if (res.status === '1') {
          Swal.fire({ icon: 'success', title: 'Done!', text: res.msg, confirmButtonColor: '#1cc88a' });
        } else { Swal.fire('Failed', res.msg, 'error'); }
      },
      error: function() { Swal.close(); Swal.fire('Error', 'Server error.', 'error'); }
    });
  });
}

// ── Edit Product Modal ────────────────────────────────────────
function editProduct(p) {
  document.getElementById('ep_id').value            = p.id;
  document.getElementById('ep_product_name').value  = p.product_name;
  document.getElementById('ep_brand_name').value    = p.brand_name  || '';
  document.getElementById('ep_markup_percent').value= p.markup_percent;
  document.getElementById('ep_ngn_sell_rate').value = p.ngn_sell_rate;
  document.getElementById('ep_status').value        = p.status;
  document.getElementById('ep_image_url').value     = p.image_url   || '';
  document.getElementById('ep_product_id_display').textContent = p.product_id;
  document.getElementById('ep_country_display').textContent    = (p.country_name || '') + ' (' + p.country_code + ')';
  document.getElementById('ep_currency_display').textContent   = p.currency_code;
  document.getElementById('ep_discount_display').textContent   = p.discount_percent;

  if (p.is_range == 1) {
    document.getElementById('ep_denoms_row').style.display    = 'none';
    document.getElementById('ep_range_row_min').style.display = 'block';
    document.getElementById('ep_range_row_max').style.display = 'block';
    document.getElementById('ep_min_amount').value = p.min_amount || '';
    document.getElementById('ep_max_amount').value = p.max_amount || '';
  } else {
    document.getElementById('ep_denoms_row').style.display    = 'block';
    document.getElementById('ep_range_row_min').style.display = 'none';
    document.getElementById('ep_range_row_max').style.display = 'none';
    document.getElementById('ep_denominations').value = p.denominations || '';
  }
  $('#editProductModal').modal('show');
}

// ── Submit Edit Product ───────────────────────────────────────
document.getElementById('editProductForm').addEventListener('submit', function(e) {
  e.preventDefault();
  var fd = new FormData(this);
  Swal.fire({ title: 'Saving…', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
  fetch('ajax/reloadly_ajax.php', { method: 'POST', body: fd })
    .then(r => r.json()).then(d => {
      Swal.close();
      if (d.status == '1') {
        $('#editProductModal').modal('hide');
        Swal.fire({ icon: 'success', title: 'Updated!', text: d.msg, confirmButtonColor: '#1cc88a' })
          .then(() => location.reload());
      } else {
        Swal.fire({ icon: 'error', title: 'Error', text: d.msg });
      }
    }).catch(() => Swal.fire('Error', 'Server error.', 'error'));
});

// ── Delete Product ────────────────────────────────────────────
function deleteProduct(id, name) {
  Swal.fire({
    title: 'Delete "' + name + '"?',
    text: 'This removes it from your catalog. It will be restored on next sync.',
    icon: 'warning', showCancelButton: true,
    confirmButtonText: 'Yes, Delete', confirmButtonColor: '#e74a3b'
  }).then(function(r) {
    if (!r.isConfirmed) return;
    $.ajax({
      url: 'ajax/reloadly_ajax.php', type: 'POST',
      data: { action: 'delete_product', id: id },
      dataType: 'json',
      success: function(res) {
        if (res.status === '1') {
          Swal.fire({ icon: 'success', title: 'Deleted!', timer: 1500, showConfirmButton: false })
            .then(() => location.reload());
        } else { Swal.fire('Error', res.msg, 'error'); }
      },
      error: function() { Swal.fire('Error', 'Server error.', 'error'); }
    });
  });
}
</script>

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