<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');

// Admin only
if (!$user['is_admin']) { header('Location: dashboard'); exit(); }

require_once '../include/JAP.php';
$jap = new JAP($site_data['jap_api_key'], $site_data['jap_api_url'] ?? 'https://the-owlet.com/api/v2');

// Handle actions
$alert = '';
$alert_type = 'success';

if (isset($_POST['action'])) {

    // ── Sync services from JAP ──
    if ($_POST['action'] === 'sync_services') {
        $res = $jap->getServices();
        if (!$res['success']) {
            $alert = 'JAP API error: ' . ($res['error'] ?? 'Unknown error');
            $alert_type = 'danger';
        } else {
            $services   = $res['data'];
            $markup     = (float)($site_data['smm_markup'] ?? 30);
            $inserted   = 0;
            $updated    = 0;

            foreach ($services as $s) {
                $jap_rate = (float)($s['rate'] ?? 0);
                $our_rate = round($jap_rate * (1 + $markup / 100), 2); // Owlet: already NGN

                // Check if exists
                $exists = $pdo->prepare("SELECT id FROM smm_services WHERE jap_service_id = :jid LIMIT 1");
                $exists->execute(['jid' => $s['service']]);
                $row = $exists->fetch();

                if ($row) {
                    // Update existing (preserve status and our_rate if manually set)
                    $pdo->prepare("UPDATE smm_services SET
                        category = :cat, name = :name, type = :type,
                        jap_rate = :jrate, min_quantity = :min, max_quantity = :max,
                        refill = :refill, cancel = :cancel, updated_at = NOW()
                        WHERE jap_service_id = :jid")
                        ->execute([
                            'cat'    => $s['category'] ?? 'General',
                            'name'   => $s['name'],
                            'type'   => $s['type'] ?? 'Default',
                            'jrate'  => $jap_rate,
                            'min'    => $s['min'],
                            'max'    => $s['max'],
                            'refill' => isset($s['refill']) && $s['refill'] ? 1 : 0,
                            'cancel' => isset($s['cancel']) && $s['cancel'] ? 1 : 0,
                            'jid'    => $s['service'],
                        ]);
                    $updated++;
                } else {
                    // Insert new
                    $pdo->prepare("INSERT INTO smm_services
                        (jap_service_id, category, name, type, jap_rate, our_rate, min_quantity, max_quantity, refill, cancel, status)
                        VALUES (:jid, :cat, :name, :type, :jrate, :orate, :min, :max, :refill, :cancel, 1)")
                        ->execute([
                            'jid'    => $s['service'],
                            'cat'    => $s['category'] ?? 'General',
                            'name'   => $s['name'],
                            'type'   => $s['type'] ?? 'Default',
                            'jrate'  => $jap_rate,
                            'orate'  => $our_rate,
                            'min'    => $s['min'],
                            'max'    => $s['max'],
                            'refill' => isset($s['refill']) && $s['refill'] ? 1 : 0,
                            'cancel' => isset($s['cancel']) && $s['cancel'] ? 1 : 0,
                        ]);
                    $inserted++;
                }
            }
            $alert = "Sync complete! {$inserted} new services added, {$updated} updated.";
        }
    }

    // ── Toggle service status ──
    if ($_POST['action'] === 'toggle_status') {
        $sid    = (int)$_POST['service_id'];
        $status = (int)$_POST['status'];
        $pdo->prepare("UPDATE smm_services SET status = :s WHERE id = :id")
            ->execute(['s' => $status, 'id' => $sid]);
        echo json_encode(['status' => '1', 'msg' => 'Updated']);
        exit();
    }

    // ── Update our_rate ──
    if ($_POST['action'] === 'update_rate') {
        $sid  = (int)$_POST['service_id'];
        $rate = (float)$_POST['our_rate'];
        $pdo->prepare("UPDATE smm_services SET our_rate = :r WHERE id = :id")
            ->execute(['r' => $rate, 'id' => $sid]);
        echo json_encode(['status' => '1', 'msg' => 'Rate updated']);
        exit();
    }

    // ── Recalculate all rates ──
    if ($_POST['action'] === 'recalculate_rates') {
        $markup     = (float)($_POST['markup']     ?? $site_data['smm_markup']  ?? 30);

        // Save to settings
        $pdo->prepare("UPDATE settings SET smm_markup = :markup WHERE id = 1")
            ->execute(['markup' => $markup]);

        // Update all services
        $all = $pdo->query("SELECT id, jap_rate FROM smm_services")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($all as $s) {
            $new_rate = round((float)$s['jap_rate'] * (1 + $markup / 100), 2); // Owlet: already NGN
            $pdo->prepare("UPDATE smm_services SET our_rate = :r WHERE id = :id")
                ->execute(['r' => $new_rate, 'id' => $s['id']]);
        }
        $alert = 'All rates recalculated. Markup: ' . $markup . '%';
    }
}

// Load JAP balance
$jap_balance_res = $jap->getBalance();
$jap_balance     = $jap_balance_res['success'] ? ($jap_balance_res['data']['balance'] ?? '—') : 'API Error';

// Fetch services from DB
$services_stmt = $pdo->query("SELECT * FROM smm_services ORDER BY category ASC, jap_service_id ASC");
$db_services   = $services_stmt->fetchAll(PDO::FETCH_ASSOC);
$total_active   = count(array_filter($db_services, function($s) { return $s['status'] == 1; }));

$page_title = "SMM Services — Admin";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $page_title; ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<div class="container-fluid py-4">

  <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
    <div>
      <h3 class="mb-0 font-weight-bold"><i class="fas fa-rocket mr-2 text-primary"></i>SMM Services Manager</h3>
      <small class="text-muted">Powered by JustAnotherPanel (JAP)</small>
    </div>
    <div class="d-flex gap-2 flex-wrap">
      <!-- JAP Balance Badge -->
      <span class="badge badge-success p-2" style="font-size:0.85rem;">
        <i class="fas fa-wallet mr-1"></i>JAP Balance: $<?php echo htmlspecialchars($jap_balance); ?>
      </span>
      <!-- Sync Button -->
      <form method="POST" class="d-inline">
        <input type="hidden" name="action" value="sync_services">
        <button type="submit" class="btn btn-primary btn-sm"
                onclick="this.innerHTML='<i class=\'fas fa-spinner fa-spin\'></i> Syncing...'; this.disabled=true; this.form.submit();">
          <i class="fas fa-sync-alt mr-1"></i>Sync Services from JAP
        </button>
      </form>
      <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#rateModal">
        <i class="fas fa-calculator mr-1"></i>Recalculate Rates
      </button>
    </div>
  </div>

  <?php if ($alert): ?>
  <div class="alert alert-<?php echo $alert_type; ?> alert-dismissible fade show">
    <i class="fas fa-<?php echo $alert_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?> mr-2"></i>
    <?php echo htmlspecialchars($alert); ?>
    <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
  </div>
  <?php endif; ?>

  <!-- Stats Cards -->
  <div class="row g-3 mb-4">
    <div class="col-md-3 col-6">
      <div class="card border-left-primary shadow-sm">
        <div class="card-body py-3">
          <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Services</div>
          <div class="h4 mb-0 font-weight-bold"><?php echo count($db_services); ?></div>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-6">
      <div class="card border-left-success shadow-sm">
        <div class="card-body py-3">
          <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Active</div>
          <div class="h4 mb-0 font-weight-bold"><?php echo $total_active; ?></div>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-6">
      <div class="card border-left-info shadow-sm">
        <div class="card-body py-3">
          <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Provider</div>
          <div class="h4 mb-0 font-weight-bold" style="font-size:1rem;">The Owlet</div>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-6">
      <div class="card border-left-warning shadow-sm">
        <div class="card-body py-3">
          <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Markup</div>
          <div class="h4 mb-0 font-weight-bold"><?php echo $site_data['smm_markup'] ?? 30; ?>%</div>
        </div>
      </div>
    </div>
  </div>

  <!-- Services Table -->
  <div class="card shadow-sm">
    <div class="card-header bg-white py-3">
      <h6 class="m-0 font-weight-bold text-primary">All Services</h6>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table id="servicesTable" class="table table-hover mb-0" style="width:100%">
          <thead class="thead-light">
            <tr>
              <th>JAP ID</th>
              <th>Category</th>
              <th>Service Name</th>
              <th>JAP Rate (USD/1K)</th>
              <th>Our Rate (₦/1K)</th>
              <th>Min</th>
              <th>Max</th>
              <th>Refill</th>
              <th>Cancel</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($db_services as $s): ?>
            <tr id="row_<?php echo $s['id']; ?>">
              <td><code><?php echo $s['jap_service_id']; ?></code></td>
              <td><span class="badge badge-light text-dark"><?php echo htmlspecialchars($s['category']); ?></span></td>
              <td class="small" style="max-width:280px; white-space:normal;"><?php echo htmlspecialchars($s['name']); ?></td>
              <td class="text-muted small">$<?php echo number_format($s['jap_rate'], 4); ?></td>
              <td>
                <div class="input-group input-group-sm" style="width:130px;">
                  <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                  <input type="number" class="form-control rate-input" data-id="<?php echo $s['id']; ?>"
                         value="<?php echo $s['our_rate']; ?>" step="0.01" min="0"
                         onchange="updateRate(<?php echo $s['id']; ?>, this.value)">
                </div>
              </td>
              <td class="small"><?php echo number_format($s['min_quantity']); ?></td>
              <td class="small"><?php echo number_format($s['max_quantity']); ?></td>
              <td><?php echo $s['refill'] ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-secondary">No</span>'; ?></td>
              <td><?php echo $s['cancel'] ? '<span class="badge badge-info">Yes</span>'   : '<span class="badge badge-secondary">No</span>'; ?></td>
              <td>
                <div class="custom-control custom-switch">
                  <input type="checkbox" class="custom-control-input status-toggle"
                         id="toggle_<?php echo $s['id']; ?>"
                         data-id="<?php echo $s['id']; ?>"
                         <?php echo $s['status'] ? 'checked' : ''; ?>>
                  <label class="custom-control-label" for="toggle_<?php echo $s['id']; ?>"></label>
                </div>
              </td>
              <td>
                <span class="badge <?php echo $s['status'] ? 'badge-success' : 'badge-secondary'; ?>" id="status_badge_<?php echo $s['id']; ?>">
                  <?php echo $s['status'] ? 'Active' : 'Hidden'; ?>
                </span>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Recalculate Rates Modal -->
<div class="modal fade" id="rateModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content rounded-lg">
      <div class="modal-header bg-warning">
        <h5 class="modal-title font-weight-bold"><i class="fas fa-calculator mr-2"></i>Recalculate All Rates</h5>
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <form method="POST">
        <input type="hidden" name="action" value="recalculate_rates">
        <div class="modal-body">
          <div class="alert alert-info py-2 small">
            <i class="fas fa-info-circle mr-1"></i>
            <strong>The Owlet</strong> prices are already in NGN — no exchange rate needed.
          </div>
          <div class="form-group">
            <label class="font-weight-bold">Profit Markup % <span class="text-danger">*</span></label>
            <div class="input-group">
              <input type="number" class="form-control" name="markup"
                     value="<?php echo $site_data['smm_markup'] ?? 30; ?>"
                     step="0.1" min="0" max="500" required>
              <div class="input-group-append"><span class="input-group-text">%</span></div>
            </div>
            <small class="text-muted">Added on top of Owlet's NGN rate. E.g. 30% markup on ₦500/1K = ₦650/1K</small>
          </div>
          <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle mr-1"></i>
            This will <strong>overwrite</strong> all manually set rates. This cannot be undone.
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-warning font-weight-bold">
            <i class="fas fa-calculator mr-1"></i>Recalculate All
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script>
$(document).ready(function() {
  $('#servicesTable').DataTable({
    order:      [[0, 'asc']],
    pageLength: 50,
    columnDefs: [{ orderable: false, targets: [10] }]
  });

  // Toggle status
  $(document).on('change', '.status-toggle', function() {
    var id     = $(this).data('id');
    var status = $(this).is(':checked') ? 1 : 0;
    $.post('sync_smm_services.php', { action: 'toggle_status', service_id: id, status: status }, function(res) {
      var badge = $('#status_badge_' + id);
      if (status) {
        badge.removeClass('badge-secondary').addClass('badge-success').text('Active');
      } else {
        badge.removeClass('badge-success').addClass('badge-secondary').text('Hidden');
      }
    }, 'json');
  });
});

function updateRate(id, rate) {
  $.post('sync_smm_services.php', { action: 'update_rate', service_id: id, our_rate: rate }, function(res) {
    if (res.status === '1') {
      Swal.fire({ title: 'Saved!', text: 'Rate updated to ₦' + parseFloat(rate).toFixed(2), icon: 'success', timer: 1200, showConfirmButton: false });
    }
  }, 'json');
}
</script>
</body>
</html>