<?php
require_once __DIR__ . '/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'Countries';
$adminSubtitle = 'Fast country marketplace settings with search, pagination and one-country editing.';
verify_csrf();

function mj_country_admin_cols(): array {
    return [
        'id','flag_emoji','name','iso2','iso3','slug','currency_code','timezone_default',
        'language_default','tax_name','tax_rate','seo_title','seo_description','is_active'
    ];
}

function mj_country_safe_row(array $row): array {
    foreach (mj_country_admin_cols() as $c) {
        if (!array_key_exists($c, $row)) { $row[$c] = ''; }
    }
    return $row;
}

function mj_country_fast_time(?string $timezone): string {
    $tz = trim((string)$timezone) ?: 'UTC';
    try {
        $dt = new DateTime('now', new DateTimeZone($tz));
        return $dt->format('d M Y, h:i A') . ' ' . $tz;
    } catch (Throwable $e) {
        return date('d M Y, h:i A') . ' UTC';
    }
}


function mj_country_has_column(string $column): bool {
    static $cache = [];
    $column = preg_replace('/[^a-zA-Z0-9_]/', '', $column);
    if ($column === '') { return false; }
    if (array_key_exists($column, $cache)) { return $cache[$column]; }
    try {
        $row = one('SELECT COUNT(*) AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ? LIMIT 1', ['mj_countries', $column]);
        $cache[$column] = ((int)($row['c'] ?? 0) > 0);
    } catch (Throwable $e) {
        $cache[$column] = false;
    }
    return $cache[$column];
}

function mj_country_select_cols(bool $hasIso3): string {
    $cols = ['id','flag_emoji','name','iso2'];
    if ($hasIso3) { $cols[] = 'iso3'; }
    $cols = array_merge($cols, ['slug','currency_code','timezone_default','language_default','tax_name','tax_rate','seo_title','seo_description','is_active']);
    return implode(',', $cols);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = trim((string)($_POST['action'] ?? 'save_country'));
    $backQ = trim((string)($_POST['back_q'] ?? ''));
    $backPage = max(1, (int)($_POST['back_page'] ?? 1));
    $backUrl = 'countries.php?q=' . urlencode($backQ) . '&page=' . $backPage;

    if ($postAction === 'bulk_status') {
        $rawIds = $_POST['country_ids'] ?? [];
        if (!is_array($rawIds)) { $rawIds = [$rawIds]; }
        $ids = [];
        foreach ($rawIds as $rawId) {
            $countryId = (int)$rawId;
            if ($countryId > 0) { $ids[$countryId] = $countryId; }
        }
        $ids = array_values($ids);
        $bulkStatusRaw = (string)($_POST['bulk_status'] ?? '');
        if ($bulkStatusRaw !== '1' && $bulkStatusRaw !== '0') {
            flash('error', 'Please choose Active or Inactive for bulk status change.');
            redirect($backUrl);
        }
        if (!$ids) {
            flash('error', 'Please select at least one country.');
            redirect($backUrl);
        }

        $bulkStatus = (int)$bulkStatusRaw;
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        try {
            q('UPDATE mj_countries SET is_active=? WHERE id IN (' . $placeholders . ')', array_merge([$bulkStatus], $ids));
            admin_log('bulk_status_update', 'mj_countries', 0, [
                'ids' => $ids,
                'is_active' => $bulkStatus,
                'count' => count($ids)
            ]);
            flash('success', count($ids) . ' country status updated to ' . ($bulkStatus ? 'Active' : 'Inactive') . '.');
        } catch (Throwable $e) {
            flash('error', 'Unable to bulk update country status. ' . $e->getMessage());
        }
        redirect($backUrl);
    }

    $id = (int)($_POST['id'] ?? 0);
    $name = trim((string)($_POST['name'] ?? ''));
    $slug = slugify((string)($_POST['slug'] ?? $name));
    $currency = strtoupper(substr(preg_replace('/[^A-Z]/i', '', (string)($_POST['currency_code'] ?? '')), 0, 3));
    $timezone = trim((string)($_POST['timezone_default'] ?? 'UTC'));
    $language = trim((string)($_POST['language_default'] ?? 'en'));
    $taxName = trim((string)($_POST['tax_name'] ?? ''));
    $taxRate = (float)($_POST['tax_rate'] ?? 0);
    $seoTitle = trim((string)($_POST['seo_title'] ?? ''));
    $seoDescription = trim((string)($_POST['seo_description'] ?? ''));
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if ($id <= 0) {
        flash('error', 'Invalid country selected.');
        redirect('countries.php');
    }
    if ($name === '') {
        flash('error', 'Country name is required.');
        redirect('countries.php?edit=' . $id);
    }
    if ($currency === '') { $currency = 'SGD'; }
    if ($taxRate < 0) { $taxRate = 0; }
    if ($taxRate > 100) { $taxRate = 100; }

    try {
        new DateTimeZone($timezone ?: 'UTC');
    } catch (Throwable $e) {
        flash('error', 'Invalid timezone. Example: Asia/Singapore');
        redirect('countries.php?edit=' . $id);
    }

    try {
        q('UPDATE mj_countries
              SET name=?, slug=?, currency_code=?, timezone_default=?, language_default=?, tax_name=?, tax_rate=?, seo_title=?, seo_description=?, is_active=?
            WHERE id=?', [
            $name, $slug, $currency, $timezone, $language, $taxName, $taxRate, $seoTitle, $seoDescription, $isActive, $id
        ]);
        admin_log('update', 'mj_countries', $id, [
            'name' => $name, 'slug' => $slug, 'currency_code' => $currency, 'timezone_default' => $timezone,
            'language_default' => $language, 'tax_name' => $taxName, 'tax_rate' => $taxRate, 'is_active' => $isActive
        ]);
        flash('success', 'Country updated.');
        redirect('countries.php');
    } catch (Throwable $e) {
        flash('error', 'Unable to update country. ' . $e->getMessage());
        redirect('countries.php?edit=' . $id);
    }
}

$search = trim((string)($_GET['q'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 30;
$offset = ($page - 1) * $perPage;
$hasIso3 = mj_country_has_column('iso3');
$countrySelectCols = mj_country_select_cols($hasIso3);
$where = '1=1';
$params = [];
if ($search !== '') {
    $whereParts = ['name LIKE ?', 'iso2 LIKE ?', 'slug LIKE ?', 'currency_code LIKE ?'];
    $like = '%' . $search . '%';
    $params = [$like, $like, $like, $like];
    if ($hasIso3) {
        array_splice($whereParts, 2, 0, 'iso3 LIKE ?');
        array_splice($params, 2, 0, $like);
    }
    $where = '(' . implode(' OR ', $whereParts) . ')';
}

$totalRow = one('SELECT COUNT(*) AS total FROM mj_countries WHERE ' . $where, $params) ?: ['total' => 0];
$total = (int)($totalRow['total'] ?? 0);
$totalPages = max(1, (int)ceil($total / $perPage));
if ($page > $totalPages) { $page = $totalPages; $offset = ($page - 1) * $perPage; }

$rows = all_rows('SELECT ' . $countrySelectCols . '
                   FROM mj_countries
                  WHERE ' . $where . '
               ORDER BY is_active DESC, name ASC
                  LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset, $params);

$editId = (int)($_GET['edit'] ?? 0);
$editCountry = null;
if ($editId > 0) {
    $editCountry = one('SELECT ' . $countrySelectCols . ' FROM mj_countries WHERE id=? LIMIT 1', [$editId]);
    if ($editCountry) { $editCountry = mj_country_safe_row($editCountry); }
}

include __DIR__ . '/_header.php';
?>
<div class="row">
  <div class="col-lg-8">
    <div class="card card-primary card-outline mj-fast-country-page">
      <div class="card-header">
        <h3 class="card-title"><i class="fas fa-globe-asia mr-2"></i>Country Marketplaces</h3>
        <div class="card-tools">
          <span class="badge badge-light"><?= e($total) ?> countries</span>
        </div>
      </div>
      <div class="card-body">
        <div class="alert alert-info py-2">
          <i class="fas fa-bolt mr-1"></i>This page now uses server-side pagination and one-country edit mode, so it will not hang by loading all edit forms at once.
        </div>
        <form class="form-row align-items-end mb-3" method="get">
          <div class="col-md-8">
            <label class="small text-muted mb-1">Search country, ISO, slug or currency</label>
            <input class="form-control" name="q" placeholder="Example: Singapore, SG, SGD" value="<?= e($search) ?>">
          </div>
          <div class="col-md-4 mt-2 mt-md-0">
            <button class="btn btn-info"><i class="fas fa-search mr-1"></i>Search</button>
            <a class="btn btn-light" href="countries.php">Clear</a>
          </div>
        </form>

        <form method="post" id="countryBulkStatusForm" class="mb-0">
          <?= csrf_input() ?>
          <input type="hidden" name="action" value="bulk_status">
          <input type="hidden" name="back_q" value="<?= e($search) ?>">
          <input type="hidden" name="back_page" value="<?= e($page) ?>">
          <div class="d-flex flex-wrap align-items-center justify-content-between bg-light border rounded p-2 mb-2">
            <div class="small text-muted mb-2 mb-md-0">
              <i class="fas fa-check-square mr-1"></i>Select countries on this page and change status together.
            </div>
            <div class="form-inline">
              <select class="form-control form-control-sm mr-2" name="bulk_status" required>
                <option value="">Bulk Status</option>
                <option value="1">Set Active</option>
                <option value="0">Set Inactive</option>
              </select>
              <button type="submit" class="btn btn-sm btn-primary" onclick="return mjCountryConfirmBulkStatus();">
                <i class="fas fa-sync-alt mr-1"></i>Apply
              </button>
            </div>
          </div>

          <div class="table-responsive">
            <table class="table table-sm table-striped table-hover mb-0">
              <thead>
                <tr>
                  <th style="width:34px;"><input type="checkbox" id="countryCheckAll" aria-label="Select all countries on this page"></th>
                  <th>Country</th>
                  <th>Currency</th>
                  <th>Timezone</th>
                  <th>Tax</th>
                  <th>Status</th>
                  <th class="text-right">Action</th>
                </tr>
              </thead>
              <tbody>
              <?php if (!$rows): ?>
                <tr><td colspan="7" class="text-center text-muted py-4">No countries found.</td></tr>
              <?php endif; ?>
              <?php foreach ($rows as $r): $r = mj_country_safe_row($r); ?>
                <tr>
                  <td><input type="checkbox" class="country-row-check" name="country_ids[]" value="<?= e($r['id']) ?>" aria-label="Select <?= e($r['name']) ?>"></td>
                  <td>
                    <strong><?= e(trim(($r['flag_emoji'] ?? '') . ' ' . ($r['name'] ?? ''))) ?></strong><br>
                    <small class="text-muted"><?= e(($r['iso2'] ?? '') . ' / ' . ($r['iso3'] ?? '') . ' / ' . ($r['slug'] ?? '')) ?></small>
                  </td>
                  <td><span class="badge badge-primary"><?= e($r['currency_code']) ?></span></td>
                  <td>
                    <?= e($r['timezone_default']) ?><br>
                    <small class="text-muted"><?= e(mj_country_fast_time($r['timezone_default'] ?? 'UTC')) ?></small>
                  </td>
                  <td><?= e($r['tax_name']) ?> <?= e($r['tax_rate']) ?>%</td>
                  <td><?= !empty($r['is_active']) ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-secondary">Off</span>' ?></td>
                  <td class="text-right"><a class="btn btn-sm btn-outline-primary" href="countries.php?edit=<?= e($r['id']) ?>&q=<?= urlencode($search) ?>&page=<?= e($page) ?>"><i class="fas fa-edit"></i> Edit</a></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </form>

        <div class="d-flex justify-content-between align-items-center mt-3">
          <div class="text-muted small">Showing <?= e($total ? ($offset + 1) : 0) ?> - <?= e(min($offset + $perPage, $total)) ?> of <?= e($total) ?></div>
          <div class="btn-group">
            <?php $base = 'countries.php?q=' . urlencode($search) . '&page='; ?>
            <a class="btn btn-sm btn-outline-secondary <?= $page <= 1 ? 'disabled' : '' ?>" href="<?= e($base . max(1, $page - 1)) ?>">Previous</a>
            <span class="btn btn-sm btn-light disabled">Page <?= e($page) ?> / <?= e($totalPages) ?></span>
            <a class="btn btn-sm btn-outline-secondary <?= $page >= $totalPages ? 'disabled' : '' ?>" href="<?= e($base . min($totalPages, $page + 1)) ?>">Next</a>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-4">
    <div class="card <?= $editCountry ? 'card-warning' : 'card-light' ?> card-outline sticky-top" style="top:80px;">
      <div class="card-header"><h3 class="card-title"><i class="fas fa-edit mr-2"></i><?= $editCountry ? 'Edit Country' : 'Country Editor' ?></h3></div>
      <div class="card-body">
        <?php if (!$editCountry): ?>
          <div class="text-muted">Click <b>Edit</b> beside a country to update currency, timezone, tax and SEO settings. Keeping the form separate makes this page load much faster.</div>
        <?php else: ?>
          <form method="post">
            <?= csrf_input() ?>
            <input type="hidden" name="action" value="save_country">
            <input type="hidden" name="id" value="<?= e($editCountry['id']) ?>">
            <div class="form-group">
              <label>Name *</label>
              <input class="form-control" name="name" value="<?= e($editCountry['name']) ?>" required>
            </div>
            <div class="form-group">
              <label>Slug</label>
              <input class="form-control" name="slug" value="<?= e($editCountry['slug']) ?>">
            </div>
            <div class="form-row">
              <div class="form-group col-6">
                <label>Currency *</label>
                <input class="form-control" name="currency_code" maxlength="3" value="<?= e($editCountry['currency_code']) ?>" required>
              </div>
              <div class="form-group col-6">
                <label>Language</label>
                <input class="form-control" name="language_default" value="<?= e($editCountry['language_default']) ?>">
              </div>
            </div>
            <div class="form-group">
              <label>Timezone *</label>
              <input class="form-control" name="timezone_default" value="<?= e($editCountry['timezone_default']) ?>" required>
              <small class="text-muted">Example: Asia/Singapore</small>
            </div>
            <div class="form-row">
              <div class="form-group col-7">
                <label>Tax Name</label>
                <input class="form-control" name="tax_name" value="<?= e($editCountry['tax_name']) ?>" placeholder="GST / VAT">
              </div>
              <div class="form-group col-5">
                <label>Tax Rate</label>
                <input class="form-control" name="tax_rate" type="number" step="0.01" min="0" max="100" value="<?= e($editCountry['tax_rate']) ?>">
              </div>
            </div>
            <div class="form-group">
              <label>SEO Title</label>
              <input class="form-control" name="seo_title" value="<?= e($editCountry['seo_title']) ?>">
            </div>
            <div class="form-group">
              <label>SEO Description</label>
              <textarea class="form-control" name="seo_description" rows="3"><?= e($editCountry['seo_description']) ?></textarea>
            </div>
            <div class="custom-control custom-switch mb-3">
              <input type="checkbox" class="custom-control-input" id="is_active" name="is_active" <?= !empty($editCountry['is_active']) ? 'checked' : '' ?>>
              <label class="custom-control-label" for="is_active">Active country marketplace</label>
            </div>
            <button class="btn btn-primary btn-block"><i class="fas fa-save mr-1"></i>Save Country</button>
            <a class="btn btn-light btn-block" href="countries.php?q=<?= urlencode($search) ?>&page=<?= e($page) ?>">Cancel</a>
          </form>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
<script>
(function(){
  var master = document.getElementById('countryCheckAll');
  if (!master) { return; }
  master.addEventListener('change', function(){
    document.querySelectorAll('.country-row-check').forEach(function(cb){ cb.checked = master.checked; });
  });
  document.querySelectorAll('.country-row-check').forEach(function(cb){
    cb.addEventListener('change', function(){
      var boxes = Array.prototype.slice.call(document.querySelectorAll('.country-row-check'));
      var checked = boxes.filter(function(item){ return item.checked; }).length;
      master.checked = boxes.length > 0 && checked === boxes.length;
      master.indeterminate = checked > 0 && checked < boxes.length;
    });
  });
})();
function mjCountryConfirmBulkStatus(){
  var checked = document.querySelectorAll('.country-row-check:checked').length;
  var select = document.querySelector('#countryBulkStatusForm select[name="bulk_status"]');
  if (!checked) { alert('Please select at least one country.'); return false; }
  if (!select || select.value === '') { alert('Please choose Active or Inactive.'); return false; }
  var label = select.value === '1' ? 'Active' : 'Inactive';
  return confirm('Change selected ' + checked + ' countr' + (checked === 1 ? 'y' : 'ies') + ' to ' + label + '?');
}
</script>
<?php include __DIR__ . '/_footer.php'; ?>
