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

// Load all types
$types = $pdo->query("SELECT * FROM sell_giftcard_types ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
?>

<title>Sell Gift Cards – Card Types | <?php echo htmlspecialchars($GLOBALS['site_data']['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">🏷️ Sell Gift Cards — Card Types</h1>
    <ol class="breadcrumb mb-0">
      <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
      <li class="breadcrumb-item"><a href="sell-giftcard-admin">Sell Gift Cards</a></li>
      <li class="breadcrumb-item active">Card Types</li>
    </ol>
  </div>

  <!-- ── Quick Nav ─────────────────────────────────────────────── -->
  <div class="mb-4 d-flex gap-2 flex-wrap">
    <a href="sell-giftcard-admin" class="btn btn-outline-primary btn-sm"><i class="fas fa-list mr-1"></i>View Sale Orders</a>
    <button class="btn btn-success btn-sm" onclick="openAdd()"><i class="fas fa-plus mr-1"></i>Add New Card Type</button>
  </div>

  <!-- ── Stats ─────────────────────────────────────────────────── -->
  <?php
  $st = $pdo->query("SELECT COUNT(*) as total,
      SUM(status='pending') as pending, SUM(status='approved') as approved,
      SUM(status='rejected') as rejected,
      SUM(CASE WHEN status='approved' THEN ngn_payout ELSE 0 END) as revenue
      FROM sell_giftcard_orders")->fetch(PDO::FETCH_ASSOC);
  ?>
  <div class="row mb-4">
    <?php foreach ([
      ['Total Sales',    $st['total'],    'primary'],
      ['Pending',        $st['pending'],  'warning'],
      ['Approved',       $st['approved'], 'success'],
      ['Rejected',       $st['rejected'], 'danger'],
    ] as [$lbl,$val,$cls]): ?>
    <div class="col-xl-3 col-md-6 mb-3">
      <div class="card border-left-<?php echo $cls; ?> shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-<?php echo $cls; ?> text-uppercase mb-1"><?php echo $lbl; ?></div>
          <div class="h5 mb-0 font-weight-bold"><?php echo number_format($val ?? 0); ?></div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <div class="alert alert-info d-flex align-items-center mb-4">
    <i class="fas fa-naira-sign mr-2"></i>
    <strong>Total Revenue (Approved):&nbsp;</strong> ₦<?php echo number_format($st['revenue'] ?? 0, 2); ?>
  </div>

  <!-- ── Card Types Table ───────────────────────────────────────── -->
  <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-tags mr-2"></i>Supported Gift Card Types
        <span class="badge badge-light ml-2"><?php echo count($types); ?> types</span>
      </h6>
      <button class="btn btn-sm btn-light" onclick="openAdd()">
        <i class="fas fa-plus mr-1"></i>Add Type
      </button>
    </div>
    <div class="card-body pb-2">
      <div class="table-responsive">
        <table class="table table-hover table-sm table-bordered align-middle">
          <thead class="thead-dark">
            <tr>
              <th width="45">#</th>
              <th width="60">Image</th>
              <th>Card Name</th>
              <th width="60">Currency</th>
              <th>NGN Rate / Unit</th>
              <th>Min (USD)</th>
              <th>Max (USD)</th>
              <th width="70">Status</th>
              <th width="120">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($types)): ?>
              <tr><td colspan="9" class="text-center text-muted py-4">
                <i class="fas fa-tags fa-2x d-block mb-2"></i>No card types added yet. Click "Add Type" to get started.
              </td></tr>
            <?php else: ?>
              <?php foreach ($types as $i => $t): ?>
              <tr>
                <td><?php echo $i + 1; ?></td>
                <td>
                  <?php if ($t['image_url']): ?>
                  <img src="<?php echo htmlspecialchars($t['image_url']); ?>"
                       width="40" height="30" style="object-fit:contain;border-radius:4px;"
                       onerror="this.style.display='none'">
                  <?php else: ?>
                  <span class="text-muted">—</span>
                  <?php endif; ?>
                </td>
                <td><strong><?php echo htmlspecialchars($t['name']); ?></strong></td>
                <td><?php echo htmlspecialchars($t['currency']); ?></td>
                <td><strong>₦<?php echo number_format($t['ngn_rate'], 2); ?></strong></td>
                <td><?php echo htmlspecialchars($t['min_usd']); ?></td>
                <td><?php echo htmlspecialchars($t['max_usd']); ?></td>
                <td>
                  <?php if ($t['status']): ?>
                    <span class="badge badge-success">Active</span>
                  <?php else: ?>
                    <span class="badge badge-secondary">Inactive</span>
                  <?php endif; ?>
                </td>
                <td>
                  <button class="btn btn-xs btn-primary mb-1"
                          onclick="openEdit(<?php echo htmlspecialchars(json_encode($t)); ?>)">
                    <i class="fas fa-edit"></i> Edit
                  </button>
                  <button class="btn btn-xs btn-<?php echo $t['status'] ? 'warning' : 'success'; ?> mb-1"
                          onclick="toggleType(<?php echo $t['id']; ?>, <?php echo $t['status']; ?>)">
                    <i class="fas fa-<?php echo $t['status'] ? 'eye-slash' : 'eye'; ?>"></i>
                    <?php echo $t['status'] ? 'Hide' : 'Show'; ?>
                  </button>
                  <button class="btn btn-xs btn-danger"
                          onclick="deleteType(<?php echo $t['id']; ?>, '<?php echo addslashes($t['name']); ?>')">
                    <i class="fas fa-trash"></i>
                  </button>
                </td>
              </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div><!-- /container -->

<!-- ══════════════════════════════════════════
     ADD / EDIT MODAL (shared)
══════════════════════════════════════════ -->
<div class="modal fade" id="typeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="background:linear-gradient(135deg,#6f42c1,#4e2d8e);color:#fff;">
        <h5 class="modal-title" id="typeModalTitle"><i class="fas fa-tags mr-2"></i>Add Card Type</h5>
        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
      </div>
      <form id="typeForm">
        <div class="modal-body">
          <input type="hidden" name="action" id="formAction" value="add_sell_type">
          <input type="hidden" name="id" id="f_id">

          <div class="form-group">
            <label><strong>Card Name</strong> <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="name" id="f_name" required
                   placeholder="e.g. Amazon USA, iTunes US">
          </div>
          <div class="form-group">
            <label><strong>Image / Logo URL</strong> <small class="text-muted">(optional)</small></label>
            <input type="text" class="form-control" name="image_url" id="f_image_url"
                   placeholder="https://…/logo.png">
          </div>
          <div class="row">
            <div class="col-md-4">
              <div class="form-group">
                <label><strong>Currency</strong></label>
                <input type="text" class="form-control" name="currency" id="f_currency"
                       value="USD" placeholder="USD" maxlength="5">
              </div>
            </div>
            <div class="col-md-8">
              <div class="form-group">
                <label><strong>NGN Rate per 1 unit</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_rate" id="f_ngn_rate"
                         required placeholder="e.g. 1450">
                </div>
                <small class="text-muted">Amount in NGN paid to user per 1 USD of card value.</small>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Min Card Value (USD)</strong></label>
                <input type="number" step="0.01" min="0" class="form-control" name="min_usd" id="f_min_usd"
                       required placeholder="e.g. 1">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Max Card Value (USD)</strong></label>
                <input type="number" step="0.01" min="1" class="form-control" name="max_usd" id="f_max_usd"
                       required placeholder="e.g. 500">
              </div>
            </div>
          </div>
          <div class="form-group">
            <label><strong>Status</strong></label>
            <select class="form-control" name="status" id="f_status">
              <option value="1">✅ Active (visible to users)</option>
              <option value="0">❌ Inactive</option>
            </select>
          </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</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function openAdd() {
    document.getElementById('typeModalTitle').innerHTML = '<i class="fas fa-plus mr-2"></i>Add Card Type';
    document.getElementById('formAction').value  = 'add_sell_type';
    document.getElementById('f_id').value        = '';
    document.getElementById('f_name').value      = '';
    document.getElementById('f_image_url').value = '';
    document.getElementById('f_currency').value  = 'USD';
    document.getElementById('f_ngn_rate').value  = '';
    document.getElementById('f_min_usd').value   = '1';
    document.getElementById('f_max_usd').value   = '';
    document.getElementById('f_status').value    = '1';
    $('#typeModal').modal('show');
}

function openEdit(t) {
    document.getElementById('typeModalTitle').innerHTML = '<i class="fas fa-edit mr-2"></i>Edit Card Type';
    document.getElementById('formAction').value  = 'edit_sell_type';
    document.getElementById('f_id').value        = t.id;
    document.getElementById('f_name').value      = t.name;
    document.getElementById('f_image_url').value = t.image_url || '';
    document.getElementById('f_currency').value  = t.currency;
    document.getElementById('f_ngn_rate').value  = t.ngn_rate;
    document.getElementById('f_min_usd').value   = t.min_usd;
    document.getElementById('f_max_usd').value   = t.max_usd;
    document.getElementById('f_status').value    = t.status;
    $('#typeModal').modal('show');
}

document.getElementById('typeForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var fd = new FormData(this);
    Swal.fire({ title: 'Saving…', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    fetch('ajax/sell-giftcard-admin-ajax.php', { method: 'POST', body: fd })
        .then(r => r.json()).then(d => {
            Swal.close();
            if (d.status == '1') {
                $('#typeModal').modal('hide');
                Swal.fire({ icon: 'success', title: 'Saved!', text: d.msg, timer: 1500, showConfirmButton: false })
                    .then(() => location.reload());
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: d.msg });
            }
        }).catch(() => Swal.fire('Error', 'Server error.', 'error'));
});

function toggleType(id, currentStatus) {
    Swal.fire({
        title: currentStatus ? 'Hide this card type?' : 'Activate this card type?',
        icon: 'question', showCancelButton: true,
        confirmButtonText: 'Yes', confirmButtonColor: currentStatus ? '#f6c23e' : '#1cc88a'
    }).then(r => {
        if (!r.isConfirmed) return;
        $.post('ajax/sell-giftcard-admin-ajax.php', { action: 'toggle_sell_type', id: id }, function(res) {
            if (res.status === '1') {
                Swal.fire({ icon: 'success', title: 'Done!', timer: 1200, showConfirmButton: false })
                    .then(() => location.reload());
            } else { Swal.fire('Error', res.msg, 'error'); }
        }, 'json');
    });
}

function deleteType(id, name) {
    Swal.fire({
        title: 'Delete "' + name + '"?',
        text: 'This cannot be undone. Existing orders will not be affected.',
        icon: 'warning', showCancelButton: true,
        confirmButtonText: 'Delete', confirmButtonColor: '#e74a3b'
    }).then(r => {
        if (!r.isConfirmed) return;
        $.post('ajax/sell-giftcard-admin-ajax.php', { action: 'delete_sell_type', id: id }, function(res) {
            if (res.status === '1') {
                Swal.fire({ icon: 'success', title: 'Deleted!', timer: 1200, showConfirmButton: false })
                    .then(() => location.reload());
            } else { Swal.fire('Error', res.msg, 'error'); }
        }, 'json');
    });
}
</script>

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