<?php

$token = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$ajax  = isset($_GET['ajax']) ? trim((string)$_GET['ajax']) : '';

/* ------------------------ helpers ------------------------ */

$data = $obj->details_by_cond('re_tbl_agent', "ag_id='$token'");
if (!$data) {
  if ($ajax) json_out(['ok' => false, 'msg' => 'Customer not found'], 404);
  echo '<div class="alert alert-danger">Customer not found</div>';
  exit;
}



/* =========================================================
   Normal Page Render (NO AJAX)
========================================================= */

$date = date('Y-m-d');

$statusPill = ((int)($data['ag_status'] ?? 0) === 1)
  ? '<span class="pill pill-ok">Active</span>'
  : '<span class="pill pill-bad">Inactive</span>';

$billDate = date('Y-m-d', strtotime(date('Y-m') . '-' . (int)($data['bill_date'] ?? date('d'))));

$billingPerson = '';
if (!empty($data['billing_person_id'])) {
  $entryb = $obj->details_by_cond('_reseller_createuser', 'UserId=' . (int)$data['billing_person_id']);
  $billingPerson = $entryb['UserName'] ?? '';
}

$ledgerRows   = $obj->view_all_by_cond("re_vw_account", "agent_id='$token' order by acc_id");
$discountRows = $obj->view_all_by_cond("re_bonus", "customerID=$token ");
$rechargeRows = $obj->view_all_by_cond("re_tbl_reseller_account", "agent_id=$token AND type=5 ");
$activityRows = $obj->view_all_by_cond("re_history", "ag_id=$token");


$ledgerCount   = is_array($ledgerRows) ? count($ledgerRows) : 0;
$discountCount = is_array($discountRows) ? count($discountRows) : 0;
$rechargeCount = is_array($rechargeRows) ? count($rechargeRows) : 0;
$activityCount = is_array($activityRows) ? count($activityRows) : 0;

$totalLedger = 0;
if (is_array($ledgerRows))   foreach ($ledgerRows as $r)   $totalLedger += (float)($r['acc_amount'] ?? 0);
$totalDis    = 0;
if (is_array($discountRows)) foreach ($discountRows as $r) $totalDis    += (float)($r['amount'] ?? 0);
$totalReg    = 0;
if (is_array($rechargeRows)) foreach ($rechargeRows as $r) $totalReg    += (float)($r['amount'] ?? 0);


?>

<style>
  :root {
    --bg: #f4f7fb;
    --card: #fff;
    --text: #495266;
    --muted: #6b6b6c;
    --border: #e6edf5;
    --shadow: 0 12px 28px rgba(15, 23, 42, .08);
    --radius: 16px;
    --p1: #1d4ed8;
    --p2: #0ea5e9;
    --p3: #10b981;
  }

  .ledger-wrap {
    padding: 12px;
  }

  .ledger-header {
    border-radius: var(--radius);
    padding: 14px;
    box-shadow: var(--shadow);
    margin-bottom: 12px;
    border: 1px solid var(--border);
    background:
      radial-gradient(900px 240px at 10% 0%, rgba(14, 165, 233, .16), transparent 55%),
      radial-gradient(800px 240px at 80% 0%, rgba(16, 185, 129, .12), transparent 55%),
      linear-gradient(135deg, rgba(29, 78, 216, .09), rgba(167, 139, 250, .07));
  }

  .ledger-title {
    margin: 0;
    font-weight: 900;
    font-size: 16px;
    color: var(--text);
  }

  .ledger-sub {
    margin-top: 8px;
    font-size: 12px;
    color: var(--muted);
  }

  .badge-chip {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 10px;
    border-radius: 999px;
    background: #ffffffcc;
    border: 1px solid var(--border);
    font-weight: 900;
    font-size: 12px;
    margin-right: 8px;
    margin-top: 8px;
  }

  .soft-card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    overflow: hidden;
    margin-bottom: 12px;
  }

  .soft-card .card-head {
    padding: 12px 14px;
    border-bottom: 1px solid var(--border);
    background: linear-gradient(180deg, #fbfdff, #f6f9ff);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    flex-wrap: wrap;
  }

  .card-head h4,
  .card-head h6 {
    margin: 0;
    font-weight: 900;
    font-size: 13px;
    color: var(--text);
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .card-head .hint {
    color: var(--muted);
    font-size: 12px;
    font-weight: 800;
  }

  .kv {
    display: grid;
    grid-template-columns: 160px 1fr;
    gap: 8px;
    font-size: 12px;
    padding: 12px 14px;
  }

  .kv .k {
    color: var(--muted);
    font-weight: 900;
  }

  .kv .v {
    color: var(--text);
    font-weight: 900;
    word-break: break-word;
  }

  .pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    border-radius: 999px;
    font-weight: 900;
    font-size: 11px;
    border: 1px solid var(--border);
    background: #fff;
  }

  .pill-ok {
    background: rgba(16, 185, 129, .10);
    border-color: rgba(16, 185, 129, .25);
    color: #047857;
  }

  .pill-bad {
    background: rgba(239, 68, 68, .10);
    border-color: rgba(239, 68, 68, .25);
    color: #b91c1c;
  }

  .pill-blue {
    background: rgba(29, 78, 216, .08);
    border-color: rgba(29, 78, 216, .18);
    color: #1d4ed8;
  }

  .pill-amber {
    background: rgba(245, 158, 11, .10);
    border-color: rgba(245, 158, 11, .25);
    color: #92400e;
  }

  .statusbox {
    padding: 12px 14px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
  }

  .statusdot {
    width: 10px;
    height: 10px;
    border-radius: 999px;
    background: #94a3b8;
    box-shadow: 0 0 0 4px rgba(148, 163, 184, .20);
  }

  .statusdot.on {
    background: linear-gradient(135deg, var(--p2), var(--p3));
    box-shadow: 0 0 0 4px rgba(14, 165, 233, .14);
  }

  .statusdot.off {
    background: #ef4444;
    box-shadow: 0 0 0 4px rgba(239, 68, 68, .14);
  }

  .kv-mini {
    display: grid;
    grid-template-columns: 120px 1fr;
    gap: 8px;
    font-size: 12px;
    padding: 0 14px 14px;
  }

  .kv-mini .k {
    color: var(--muted);
    font-weight: 900;
  }

  .kv-mini .v {
    color: var(--text);
    font-weight: 900;
    word-break: break-word;
  }

  .chart-wrap {
    padding: 8px 14px 14px;
  }

  .muted {
    color: var(--muted);
    font-size: 12px;
    font-weight: 800;
    margin-top: 8px;
  }

  .table-soft {
    margin: 0;
  }

  .table-soft thead th {
    background: #f7fbff !important;
    border-bottom: 1px solid var(--border) !important;
    font-weight: 900;
    font-size: 12px;
    white-space: nowrap;
    color: var(--text);
  }

  .table-soft tbody td {
    border-top: 1px solid var(--border) !important;
    font-size: 12px;
    vertical-align: middle !important;
    color: var(--text);
  }

  .table-soft tbody tr:hover td {
    background: rgba(14, 165, 233, .06);
  }

  .btn-action {
    padding: 6px 9px;
    border-radius: 12px !important;
    font-weight: 900;
    border: 1px solid var(--border);
    background: #fff;
  }

  .btn-action:hover {
    background: #f6fbff;
  }

  .tabbar {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin: 10px 0 12px;
  }

  .tabbtn {
    border: 1px solid var(--border);
    background: #fff;
    color: var(--muted);
    padding: 10px 12px;
    border-radius: 14px;
    font-weight: 900;
    font-size: 12px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: .15s ease;
    user-select: none;
    box-shadow: 0 8px 18px rgba(255, 255, 255, 0.04);
  }

  .tabbtn .dot {
    width: 10px;
    height: 10px;
    border-radius: 999px;
    background: rgba(255, 255, 255, 0.35);
    box-shadow: 0 0 0 4px rgba(254, 255, 255, 0.12);
  }

  .tabbtn.active {
      color: #f6fff8;
      border-color: #4CAF50;
      background: #4CAF50;
  }

  .tabbtn.active .dot {
    background: linear-gradient(135deg, var(--p2), var(--p3));
    box-shadow: 0 0 0 4px rgba(14, 165, 233, .14);
  }

  .tabcount {
    margin-left: 4px;
    padding: 3px 8px;
    border-radius: 999px;
    border: 1px solid var(--border);
    background: #fff;
    color: var(--text);
    font-size: 11px;
  }

  .tab-panel {
    display: none;
  }

  .tab-panel.active {
    display: block;
  }

  .totals {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    padding: 12px 14px;
    border-top: 1px solid var(--border);
    background: #fff;
  }

  .total-chip {
    border: 1px solid var(--border);
    border-radius: 999px;
    padding: 8px 12px;
    font-weight: 900;
    background: #fff;
    font-size: 12px;
    color: var(--text);
    box-shadow: 0 8px 18px rgba(15, 23, 42, .06);
  }

  @media (max-width: 767px) {
    .kv {
      grid-template-columns: 1fr;
    }

    .kv-mini {
      grid-template-columns: 1fr;
    }
  }
</style>

<?php
$disconnectDate = $data['mikrotik_disconnect'] ?? null;

$badgeClass = 'bg-success text-white'; 
$statusText = 'N/A';

if ($disconnectDate) {
    $today = new DateTime(date('Y-m-d'));
    $discDate = new DateTime($disconnectDate);
    $diffDays = (int)$today->diff($discDate)->format('%r%a');

    if ($diffDays < 0) {
        $badgeClass = 'bg-danger text-white';
        $statusText = 'Disconnected';
    } elseif ($diffDays <= 5) {
        $badgeClass = 'bg-warning text-dark';
        $statusText = $diffDays . ' days left';
    } else {
        $badgeClass = 'bg-success text-white';
        $statusText = $diffDays . ' days left';
    }
}
?>



<div class="container-fluid ledger-wrap">

  <div class="ledger-header">
    <h6 class="ledger-title">Customer Ledger — <?php echo htmlspecialchars($data['ag_name']); ?></h6>
    <div class="ledger-sub">
      <span class="badge-chip"><b>ID:</b> <?php echo htmlspecialchars($data['cus_id']); ?></span>
      <span class="badge-chip"><b>Secret/IP:</b> <?php echo htmlspecialchars($data['ip']); ?></span>
      <span class="badge-chip"><b>Mobile:</b> <?php echo htmlspecialchars($data['ag_mobile_no']); ?></span>
      <span class="badge-chip <?= $badgeClass ?>">
        <b>Disconnect Date:</b>
        <?= htmlspecialchars($disconnectDate ?? 'N/A') ?>
        <?php if ($disconnectDate): ?>
            (<?= $statusText ?>)
        <?php endif; ?>
    </span>
    </div>
  </div>

  <div class="row">

    <div class="col-md-6">
      <div class="soft-card">
        <div class="card-head">
          <h4><span class="glyphicon glyphicon-user"></span> Customer Summary</h4>
          <div class="hint">
            <a href="?page=reseller-customer-edit&id=<?php echo (int)$token; ?>" class="btn btn-xs btn-action">
              <span class="fas fa-pen"></span> Edit
            </a>
          </div>
        </div>

        <div class="kv">
          <div class="k">Name</div>
          <div class="v"><?php echo htmlspecialchars($data['ag_name']); ?></div>
          <div class="k">Address</div>
          <div class="v" style="color:var(--muted);font-weight:800;"><?php echo htmlspecialchars($data['ag_office_address'] ?? 'N/A'); ?></div>
          <div class="k">Profile / Speed</div>
          <div class="v"><span class="pill pill-blue"><?php echo htmlspecialchars($data['mb'] ?? ''); ?></span></div>
          <div class="k">Status</div>
          <div class="v"><?php echo $statusPill; ?></div>
          <div class="k">Connection Date</div>
          <div class="v"><?php echo htmlspecialchars($data['connection_date'] ?? ''); ?></div>
          <div class="k">Entry Date</div>
          <div class="v"><?php echo htmlspecialchars($data['entry_date'] ?? ''); ?></div>
          <div class="k">Bill Date</div>
          <div class="v"><span class="pill pill-amber"><?php echo $billDate; ?></span></div>
          <div class="k">Billing Person</div>
          <div class="v"><?php echo htmlspecialchars($billingPerson); ?></div>
          <div class="k">Monthly Bill</div>
          <div class="v"><b><?php echo htmlspecialchars($data['taka'] ?? 0); ?></b></div>
          <div class="k">Due / Advance</div>
          <div class="v"><b><?php echo htmlspecialchars($data['dueadvance'] ?? 0); ?></b></div>
        </div>
      </div>
    </div>

    <div class="col-md-6">
      <div class="card shadow-sm border-0">
        <div class="card-header bg-white fw-semibold">
          <div>
            <span>Live Graph (Last 60s)</span>
            <span id="connectionChecker" class="badge bg-secondary float-right">Checking...</span>
          </div>
        </div>
        <div class="card-body">
          <div class="d-flex gap-2 flex-wrap mb-2">
            <span id="liveStatus" class="badge bg-secondary">Idle</span>
            <span class="badge bg-success" id="downText">Download: 0.00 Mbps</span>
            <span class="badge bg-info text-dark" id="upText">Upload: 0.00 Mbps</span>
          </div>

          <div class="text-muted" style="font-size:12px;">
            <div>Address: <span id="addrText">-</span></div>
          </div>

          <canvas id="speedChart" height="120"></canvas>

        </div>
      </div>
    </div>

  </div>

  <div class="tabbar">
    <div class="tabbtn active" data-tab="tab-ledger"><span class="dot"></span> Other's Transactions <span class="tabcount"><?php echo $ledgerCount; ?></span></div>
    <div class="tabbtn" data-tab="tab-discount"><span class="dot"></span> Discount <span class="tabcount"><?php echo $discountCount; ?></span></div>
    <div class="tabbtn" data-tab="tab-recharge"><span class="dot"></span> Recharge <span class="tabcount"><?php echo $rechargeCount; ?></span></div>
    <div class="tabbtn" data-tab="tab-activity"><span class="dot"></span> Activity log <span class="tabcount"><?php echo $activityCount; ?></span></div>
  </div>

  <div id="tab-ledger" class="tab-panel active">
    <div class="soft-card">
      <div class="card-head">
        <h6><span class="glyphicon glyphicon-list-alt"></span> Other's Transactions</h6>
        <div class="hint">Payments & bill collections</div>
      </div>

      <div class="table-responsive">
        <table class="table table-hover table-soft">
          <thead>
            <tr>
              <th style="width:55px;">#</th>
              <th style="width:110px;">Date</th>
              <th>Description</th>
              <th style="width:110px;">Amount</th>
              <th style="width:210px;">Received By</th>
              <th style="width:110px;">Action</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $i = 1;
            if (is_array($ledgerRows)) {
              foreach ($ledgerRows as $customer_info) {
                $amount = (float)($customer_info['acc_amount'] ?? 0);
                $edate  = $customer_info['entry_date'] ?? "2016-02-1";
            ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo date("d-m-Y", strtotime($edate)); ?></td>
                  <td style="color:var(--muted);font-weight:800;"><?php echo htmlspecialchars($customer_info['acc_description'] ?? ''); ?></td>
                  <td><b><?php echo htmlspecialchars($amount); ?></b></td>
                  <td style="color:var(--muted);font-weight:800;">
                    <?php echo htmlspecialchars($customer_info['FullName'] ?? ''); ?>
                    (<?php echo htmlspecialchars($customer_info['UserName'] ?? ''); ?>)
                  </td>
                  <td>
                    <a href="javascript:void(0)" class="btn btn-xs btn-action js-edit-payment"
                      data-acc-id="<?php echo (int)($customer_info['acc_id'] ?? 0); ?>">
                      <span class="fas fa-pen"></span>
                    </a>
                    <a class="btn btn-xs btn-action" target="_blank"
                      href="pages/pdf/re_receipt.php?token=<?php echo htmlspecialchars($customer_info['acc_id'] ?? ''); ?>">
                      <span class="fas fa-print"></span>
                    </a>
                  </td>
                </tr>
            <?php }
            } ?>
          </tbody>
          <tfoot>
            <tr>
              <th colspan="3" style="text-align:right;">Total</th>
              <th colspan="3" style="text-align:left;"><?php echo $totalLedger; ?> Taka</th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>

  <div id="tab-discount" class="tab-panel">
    <div class="soft-card">
      <div class="card-head">
        <h6><span class="glyphicon glyphicon-gift"></span> Discount</h6>
        <div class="hint">All discount history</div>
      </div>

      <div class="table-responsive">
        <table class="table table-hover table-soft">
          <thead>
            <tr>
              <th style="width:55px;">#</th>
              <th style="width:120px;">Date</th>
              <th style="width:120px;">Amount</th>
              <th>Taken By</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $i = 1;
            if (is_array($discountRows)) {
              foreach ($discountRows as $re_bonus) {
                $userData = $obj->details_by_cond('_reseller_createuser', "UserId = " . (int)($re_bonus['takenBy'] ?? 0) . "");
            ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo date("d-m-Y", strtotime($re_bonus['date'] ?? "2016-02-1")); ?></td>
                  <td><b><?php echo htmlspecialchars($re_bonus['amount'] ?? 0); ?></b></td>
                  <td>
                    <a href="?q=user_details&token=<?php echo htmlspecialchars($re_bonus['takenBy'] ?? ''); ?>"
                      style="font-weight:900;color:var(--p1);text-decoration:none;">
                      <?php echo htmlspecialchars($userData['FullName'] ?? ''); ?>
                    </a>
                  </td>
                </tr>
            <?php }
            } ?>
          </tbody>
        </table>
      </div>

      <div class="totals">
        <div class="total-chip">Total Discount: <span style="color:var(--text);"><?php echo $totalDis; ?></span></div>
      </div>
    </div>
  </div>

  <div id="tab-recharge" class="tab-panel">
    <div class="soft-card">
      <div class="card-head">
        <h6><span class="glyphicon glyphicon-flash"></span> Recharge</h6>
        <div class="hint">Reseller recharge entries</div>
      </div>

      <div class="table-responsive">
        <table class="table table-hover table-soft">
          <thead>
            <tr>
              <th style="width:55px;">#</th>
              <th style="width:120px;">Date</th>
              <th style="width:120px;">Amount</th>
              <th>Description</th>
              <th style="width:220px;">By</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $i = 1;
            if (is_array($rechargeRows)) {
              foreach ($rechargeRows as $rechargeac) {
                $userData = $obj->details_by_cond('_reseller_createuser', "UserId = " . (int)($rechargeac['entry_by'] ?? 0) . "");
            ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo date("d-m-Y", strtotime($rechargeac['entry_date'] ?? $date)); ?></td>
                  <td><b><?php echo htmlspecialchars($rechargeac['amount'] ?? 0); ?></b></td>
                  <td style="color:var(--muted);font-weight:800;"><?php echo htmlspecialchars($rechargeac['description'] ?? ''); ?></td>
                  <td>
                    <a href="?q=user_details&token=<?php echo htmlspecialchars($rechargeac['entry_by'] ?? ''); ?>"
                      style="font-weight:900;color:var(--p1);text-decoration:none;">
                      <?php echo htmlspecialchars($userData['FullName'] ?? ''); ?>
                    </a>
                  </td>
                </tr>
            <?php }
            } ?>
          </tbody>
        </table>
      </div>

      <div class="totals">
        <div class="total-chip">Total Recharge: <span style="color:var(--text);"><?php echo $totalReg; ?></span></div>
      </div>
    </div>
  </div>

  <div id="tab-activity" class="tab-panel">
    <div class="soft-card">
      <div class="card-head">
        <h6><span class="glyphicon glyphicon-flash"></span> Activity Log</h6>
        <div class="hint">Customer activity log entries</div>
      </div>

      <div class="table-responsive">
        <table class="table table-hover table-soft">
          <thead>
            <tr>
              <th style="width:55px;">#</th>
              <th style="width:120px;">Date</th>
              <th style="width:120px;">Title</th>
              <th>Description</th>
              <th style="width:220px;">By</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $i = 1;
            if (is_array($activityRows)) {
              foreach ($activityRows as $activity) {
                $userData = $obj->details_by_cond('_reseller_createuser', "UserId = " . (int)($activity['re_id'] ?? 0) . "");
            ?>
                <tr>
                  <td><?php echo $i++; ?></td>
                  <td><?php echo date("d-m-Y", strtotime($activity['created_at'] ?? $date)); ?></td>
                  <td><b><?php echo htmlspecialchars($activity['header'] ?? 0); ?></b></td>
                  <td style="color:var(--muted);font-weight:800;"><?php echo htmlspecialchars($activity['descriptions'] ?? ''); ?></td>
                  <td style="color:var(--muted);font-weight:800;"><?php if(isset($userData) && !empty($userData)) { echo $userData['FullName']; } else { echo 'Admin'; } ?></td>
                  
                </tr>
            <?php }
            } ?>
          </tbody>
        </table>
      </div>

      <div class="totals">
        <div class="total-chip">Total Recharge: <span style="color:var(--text);"><?php echo $totalReg; ?></span></div>
      </div>
    </div>
  </div>

</div>

<!-- Edit Payment Modal -->
<div class="modal fade" id="editPaymentModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-md">
    <div class="modal-content" style="border-radius:12px; overflow:hidden;">
      <div class="modal-header" style="background:#f3f4f6;">
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
        <h4 class="modal-title">Edit Payment</h4>
      </div>
      <div class="modal-body">
        <div id="editPaymentBody">
          <div class="text-center" style="padding:15px;">Loading...</div>
        </div>
      </div>
    </div>
  </div>
</div>

<?php echo $obj->start_script(); ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
  $(document).ready(function() {

    // -------- Tabs
    $(document).on('click', '.tabbtn', function() {
      var tab = $(this).data('tab');
      $('.tabbtn').removeClass('active');
      $(this).addClass('active');
      $('.tab-panel').removeClass('active');
      $('#' + tab).addClass('active');
    });

    // -------- Edit Payment
    $(document).on('click', '.js-edit-payment', function() {
      var accId = $(this).data('acc-id');
      if (!accId) {
        Swal.fire('Error!', 'Invalid payment id', 'error');
        return;
      }

      $('#editPaymentBody').html('<div class="text-center" style="padding:15px;">Loading...</div>');
      $('#editPaymentModal').modal('show');

      $.ajax({
        url: 'pages/resellers/customer/ajax_edit_payment_form.php',
        type: 'GET',
        data: {
          acc_id: accId
        },
        success: function(html) {
          $('#editPaymentBody').html(html);
        },
        error: function() {
          $('#editPaymentBody').html('<div class="alert alert-danger">Request failed</div>');
        }
      });
    });

    $(document).on('submit', '#editPaymentForm', function(e) {
      e.preventDefault();
      var $form = $(this);

      $.ajax({
        url: 'pages/resellers/customer/ajax_edit_payment_update.php',
        type: 'POST',
        data: $form.serialize(),
        dataType: 'json',
        success: function(res) {
          if (res && res.status === 'success') {
            Swal.fire('Success!', res.message || 'Updated', 'success');
            $('#editPaymentModal').modal('hide');
            location.reload();
          } else {
            Swal.fire('Error!', (res && res.message) ? res.message : 'Update failed', 'error');
          }
        },
        error: function(xhr) {
          Swal.fire('Error!', 'Request failed', 'error');
          console.log(xhr.responseText);
        }
      });
    });

  });
</script>

<script>
  /* ================= PHP VARIABLES ================= */
  const token = <?php echo (int)$token; ?>;
  const USER = <?php echo json_encode((string)($data['ip'] ?? '')); ?>;

  /* ================= GLOBAL STATE ================= */
  let mikrotikStatus = false;
  let pollTimer = null;

  /* ================= CHECK MIKROTIK ================= */
  const connectionChecker = document.getElementById('connectionChecker');

  async function checkMikrotik() {
    if (!token) return false;

    try {
      const url = `./pages/resellers/customer/mikrotikliveTrafic.php?action=mikrotik_check&token=${token}&_=${Date.now()}`;
      const res = await fetch(url, {
        cache: 'no-store'
      });
      const j = await res.json();
      if (j.ok != false) {
        connectionChecker.textContent = 'Mikrotik Connected';
        connectionChecker.className = 'badge bg-success';
      } else {
        connectionChecker.textContent = 'Mikrotik Not Connected';
        connectionChecker.className = 'badge bg-danger';
      }

      return !!j.ok;

    } catch (e) {
      console.error('checkMikrotik error:', e);
      connectionChecker.textContent = 'Error';
      connectionChecker.className = 'badge bg-danger';
      return false;
    }
  }


  /* ================= START LIVE TRAFFIC ================= */
  function startLiveTraffic() {

    const statusEl = document.getElementById('liveStatus');
    const downText = document.getElementById('downText');
    const upText = document.getElementById('upText');
    const addrText = document.getElementById('addrText');

    let labels = [];
    let downData = [];
    let upData = [];

    const ctx = document.getElementById('speedChart').getContext('2d');
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels,
        datasets: [{
            label: 'Download (Mbps)',
            data: downData,
            tension: 0.3
          },
          {
            label: 'Upload (Mbps)',
            data: upData,
            tension: 0.3
          }
        ]
      },
      options: {
        animation: false,
        responsive: true,
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });

    function setStatus(cls, text) {
      statusEl.className = 'badge ' + cls;
      statusEl.textContent = text;
    }

    function pushPoint(down, up) {
      labels.push(new Date().toLocaleTimeString());
      downData.push(Number(down.toFixed(2)));
      upData.push(Number(up.toFixed(2)));

      if (labels.length > 60) {
        labels.shift();
        downData.shift();
        upData.shift();
      }

      chart.update('none');

      downText.textContent = `Download: ${down.toFixed(2)} Mbps`;
      upText.textContent = `Upload: ${up.toFixed(2)} Mbps`;
    }

    async function poll() {
      try {
        const url = `./pages/resellers/customer/mikrotikliveTrafic.php?action=speed&token=${token}&_=${Date.now()}`;
        const res = await fetch(url, {
          cache: 'no-store'
        });
        const j = await res.json();

        if (!j.ok) {
          setStatus('bg-danger', 'Offline');
          pushPoint(0, 0);
          return;
        }

        setStatus('bg-success', 'Live');
        addrText.textContent = j.name || '-';

        pushPoint(
          Number(j.down_mbps || 0),
          Number(j.up_mbps || 0)
        );

      } catch (e) {
        console.error('poll error:', e);
        setStatus('bg-danger', 'Error');
        pushPoint(0, 0);
      }
    }

    poll();
    pollTimer = setInterval(poll, 5000);
  }

  document.addEventListener('DOMContentLoaded', async () => {

    mikrotikStatus = await checkMikrotik();


    if (mikrotikStatus) {
      startLiveTraffic();
    } else {
      const statusEl = document.getElementById('liveStatus');
      if (statusEl) {
        statusEl.className = 'badge bg-secondary';
        statusEl.textContent = 'Offline';
      }
    }
  });
</script>

<?php echo $obj->end_script(); ?>