<?php



$packages = $obj->rawSql("
    SELECT 
        p.package_id,
        p.package_name,
        p.net_speed,
        p.bill_amount,
        p.re_bill_amount,
        p.reseller_id,
        u.UserName AS reseller_name
    FROM re_tbl_package p
    LEFT JOIN _reseller_createuser u ON u.UserId = p.reseller_id
    ORDER BY p.package_id DESC
");

$resellers = $obj->rawSql("SELECT UserId, UserName FROM _reseller_createuser ORDER BY UserName ASC");

$AJAX_URL = "pages/admin_reseller/re_package_ajax.php";
?>

<style>
.table-card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;overflow:hidden;box-shadow:0 8px 24px rgba(17,24,39,.06)}
.table-card-header{padding:14px 16px;border-bottom:1px solid #e5e7eb;background:linear-gradient(180deg,#fafafa,#fff)}
.table-card-body{padding:14px 16px}
.page-title{font-weight:800;font-size:22px;color:#111827;margin:0}
.table-modern thead th{background:#0f172a;color:#fff;border:none!important;padding:12px;white-space:nowrap;font-size:13px}
.table-modern tbody td{padding:12px;border-top:1px solid #eef2f7!important;vertical-align:middle}
.td-actions{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap}
.badge-chip{display:inline-flex;align-items:center;padding:6px 10px;border-radius:999px;background:#f3f4f6;border:1px solid #e5e7eb;font-weight:700;font-size:12px}
.muted{color:#6b7280;font-size:12px}
.mk-ok{color:#16a34a;font-weight:700}
.mk-bad{color:#dc2626;font-weight:700}
</style>

<div class="container-fluid">

  <div class="row" style="margin-bottom:10px;">
    <div class="col-sm-6">
      <h6 class="page-title">Package List</h6>
      <small class="muted">Add / Edit / Update from modal</small>
    </div>
    <div class="col-sm-6 text-right text-end" style="margin-top:10px;">
      <a href="javascript:void(0)" class="btn btn-success" id="btnAddPackage">
        + Add New Package
      </a>
    </div>
  </div>

  <div class="table-card">
    <div class="table-card-body">
      <div class="table-responsive">
        <table id="packageTable" class="table table-striped table-hover table-modern w-100">
          <thead>
            <tr>
              <th>Package</th>
              <th>Profile / Speed</th>
              <th>Customer Bill</th>
              <th>Reseller Bill</th>
              <th>Reseller</th>
              <th class="text-end">Actions</th>
            </tr>
          </thead>

          <tbody>
            <?php foreach ($packages as $p): ?>
              <tr>
                <td>
                  <span class="badge-chip">
                    <?php echo htmlspecialchars($p['package_name'] ?? ''); ?>
                  </span>
                </td>
                <td><?php echo htmlspecialchars($p['net_speed'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($p['bill_amount'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($p['re_bill_amount'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($p['reseller_name'] ?? 'N/A'); ?></td>

                <td class="text-end">
                  <div class="td-actions">
                    <a href="javascript:void(0)"
                       class="btn btn-primary btn-sm btnEditPackage"
                       data-id="<?php echo (int)$p['package_id']; ?>"
                       data-name="<?php echo htmlspecialchars($p['package_name'] ?? '', ENT_QUOTES); ?>"
                       data-speed="<?php echo htmlspecialchars($p['net_speed'] ?? '', ENT_QUOTES); ?>"
                       data-bill="<?php echo htmlspecialchars($p['bill_amount'] ?? '', ENT_QUOTES); ?>"
                       data-rebill="<?php echo htmlspecialchars($p['re_bill_amount'] ?? '', ENT_QUOTES); ?>"
                       data-reseller="<?php echo (int)$p['reseller_id']; ?>"
                    >
                      Edit
                    </a>

                    <a href="javascript:void(0)"
                       class="btn btn-danger btn-sm"
                       onclick="deletePackage('<?php echo (int)$p['package_id']; ?>', '<?php echo (int)$p['reseller_id']; ?>')">
                      Delete
                    </a>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>

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

</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="packageModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="border-radius:14px; overflow:hidden;">
      <div class="modal-header" style="background:#0f172a; color:#fff;">
        <h5 class="modal-title mb-0" style="color: #fff;" id="packageModalTitle">Add Package</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <form id="packageForm">
        <div class="modal-body">
          <input type="hidden" name="action" id="pkg_action" value="add_package">
          <input type="hidden" name="package_id" id="pkg_id" value="">

          <div class="mb-3">
            <label class="form-label">Package Name</label>
            <input type="text" class="form-control" name="package_name" id="pkg_name" required>
          </div>

          <!-- Reseller -->
          <div class="mb-3">
            <label class="form-label">Reseller</label>
            <select class="form-control" name="reseller_id" id="pkg_reseller" required>
              <option value="">Select reseller</option>
              <?php foreach($resellers as $r): ?>
                <option value="<?php echo (int)$r['UserId']; ?>">
                  <?php echo htmlspecialchars($r['UserName'] ?? ''); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <!-- Profile / Speed (Mikrotik aware) -->
          <div class="mb-3">
            <label class="form-label d-flex align-items-center justify-content-between">
              <span>Profile / Speed</span>
              <small class="muted" id="mk_status_text">Select reseller to check Mikrotik…</small>
            </label>

            <!-- Mikrotik select (no name) -->
            <select class="form-control d-none" name="net_speed" id="pkg_speed_select">
              <option value="">Select profile</option>
            </select>

            <!-- Manual input (backend field) -->
            <input type="text" class="form-control" name="net_speed" id="pkg_speed" required
                   placeholder="ex: 10M, 20M, 5Mbps">

            <div class="mt-2 d-flex gap-2">
              <button type="button" class="btn btn-outline-secondary btn-sm d-none" id="btn_manual_speed">Use Manual</button>
              <button type="button" class="btn btn-outline-primary btn-sm d-none" id="btn_mk_speed">Use Mikrotik</button>
            </div>

          </div>

          <div class="mb-3">
            <label class="form-label">Customer Bill</label>
            <input type="number" step="0.01" class="form-control" name="bill_amount" id="pkg_bill" required>
          </div>

          <div class="mb-1">
            <label class="form-label">Reseller Bill</label>
            <input type="number" step="0.01" class="form-control" name="re_bill_amount" id="pkg_rebill" required>
          </div>

          <div id="pkg_msg" class="mt-3" style="display:none;"></div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-success" id="pkg_save_btn">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php $obj->start_script(); ?>
<script>
(function(){
  const AJAX_URL = "<?php echo $AJAX_URL; ?>";

  // DataTables optional (if loaded)
  if($.fn.DataTable){
    $('#packageTable').DataTable({
      pageLength: 10,
      lengthMenu: [[10,20,50,100,500],[10,20,50,100,500]],
      order: []
    });
  }

  // ---------- UI mode switch ----------
  function useManualSpeed(){
    $('#pkg_speed_select').addClass('d-none').prop('disabled', true);
    $('#pkg_speed').removeClass('d-none').prop('disabled', false).attr('required', true);
    $('#btn_manual_speed').addClass('d-none');
    $('#btn_mk_speed').removeClass('d-none').removeClass('d-none');
  }
  function useMkSpeed(){
    $('#pkg_speed').addClass('d-none').prop('disabled', true).removeAttr('required');
    $('#pkg_speed_select').removeClass('d-none').prop('disabled', false);
    $('#btn_mk_speed').addClass('d-none');
    $('#btn_manual_speed').removeClass('d-none');
  }

  $(document).on('change', '#pkg_speed_select', function(){
    const v = $(this).val() || '';
    $('#pkg_speed').val(v);
  });

  $('#btn_manual_speed').on('click', useManualSpeed);
  $('#btn_mk_speed').on('click', useMkSpeed);

  const mkCache = {}; 
  const CACHE_SEC = 30;

  async function loadProfilesForReseller(resellerId, preferSelectValue){
    const $txt = $('#mk_status_text');
    $('#pkg_speed_select').html('<option value="">Select profile</option>');

    if(!resellerId){
      $txt.text('Select reseller to check Mikrotik…').removeClass('mk-ok mk-bad');
      useManualSpeed();
      $('#btn_manual_speed, #btn_mk_speed').addClass('d-none');
      return;
    }

    // cache
    const now = Date.now()/1000;
    if(mkCache[resellerId] && (now - mkCache[resellerId].ts) < CACHE_SEC){
      applyMkResult(mkCache[resellerId], preferSelectValue);
      return;
    }

    $txt.text('Checking Mikrotik…').removeClass('mk-ok mk-bad');
    $('#btn_manual_speed, #btn_mk_speed').addClass('d-none');

    try{
      const fd = new FormData();
      fd.append('action', 'mk_check_profiles');
      fd.append('reseller_id', resellerId);

      const r = await fetch(AJAX_URL, { method:'POST', body: fd, cache:'no-store' });
      const d = await r.json();

      const result = {
        ts: now,
        ok: !!(d && d.ok),
        profiles: (d && Array.isArray(d.profiles)) ? d.profiles : [],
        msg: (d && d.msg) ? d.msg : ''
      };
      mkCache[resellerId] = result;
      applyMkResult(result, preferSelectValue);

    }catch(e){
      const result = { ts: now, ok:false, profiles:[], msg:'Mikrotik check failed' };
      mkCache[resellerId] = result;
      applyMkResult(result, preferSelectValue);
    }
  }

  function applyMkResult(result, preferSelectValue){
    const $txt = $('#mk_status_text');
    if(result.ok && result.profiles.length){
      $txt.text('Mikrotik connected ').removeClass('mk-bad').addClass('mk-ok');

      const $sel = $('#pkg_speed_select');
      $sel.html('<option value="">Select profile</option>');
      result.profiles.forEach(p=>{
        const name = (p.name || '').toString().trim();
        if(!name) return;
        $sel.append('<option value="'+escapeHtml(name)+'">'+escapeHtml(name)+'</option>');
      });

      // show toggles
      $('#btn_mk_speed, #btn_manual_speed').removeClass('d-none');

      // default mikrotik mode
      useMkSpeed();

      // select existing speed if edit
      if(preferSelectValue){
        $sel.val(preferSelectValue);
        $('#pkg_speed').val(preferSelectValue);
      }

    }else{
      $txt.text(result.msg || 'Mikrotik not configured').removeClass('mk-ok').addClass('mk-bad');
      useManualSpeed();
      // show toggle only if you want, but when not ok, keep only manual
      $('#btn_manual_speed').addClass('d-none');
      $('#btn_mk_speed').addClass('d-none');
    }
  }

  function escapeHtml(s){
    return String(s).replace(/[&<>"']/g, function(m){
      return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]);
    });
  }

  // reseller change => reload profiles
  $('#pkg_reseller').on('change', function(){
    const rid = $(this).val();
    loadProfilesForReseller(rid, $('#pkg_speed').val() || '');
  });

  // open Add modal
  $('#btnAddPackage').on('click', function(){
    $('#packageModalTitle').text('Add Package');
    $('#pkg_action').val('add_package');
    $('#pkg_id').val('');

    $('#packageForm')[0].reset();
    $('#pkg_msg').hide().html('');
    $('#pkg_save_btn').prop('disabled', false).text('Save');

    // initial state
    $('#mk_status_text').text('Select reseller to check Mikrotik…').removeClass('mk-ok mk-bad');
    useManualSpeed();
    $('#btn_manual_speed, #btn_mk_speed').addClass('d-none');

    new bootstrap.Modal(document.getElementById('packageModal')).show();
  });

  // open Edit modal
  $(document).on('click', '.btnEditPackage', function(){
    $('#packageModalTitle').text('Edit Package');
    $('#pkg_action').val('update_package');

    const pkgId = $(this).data('id');
    const pkgName = $(this).data('name');
    const speed = $(this).data('speed');
    const bill = $(this).data('bill');
    const rebill = $(this).data('rebill');
    const reseller = $(this).data('reseller');

    $('#pkg_id').val(pkgId);
    $('#pkg_name').val(pkgName);
    $('#pkg_speed').val(speed);
    $('#pkg_bill').val(bill);
    $('#pkg_rebill').val(rebill);
    $('#pkg_reseller').val(reseller);

    $('#pkg_msg').hide().html('');
    $('#pkg_save_btn').prop('disabled', false).text('Update');

    loadProfilesForReseller(String(reseller), String(speed || ''));

    new bootstrap.Modal(document.getElementById('packageModal')).show();
  });

  // submit Add/Edit
  $('#packageForm').on('submit', function(e){
    e.preventDefault();

    const $btn = $('#pkg_save_btn');
    $btn.prop('disabled', true).text('Saving...');

    if(!$('#pkg_speed').val()){
      $('#pkg_msg').show().html('<div class="alert alert-danger mb-0">Profile/Speed is required.</div>');
      $btn.prop('disabled', false).text($('#pkg_action').val()==='add_package' ? 'Save' : 'Update');
      return;
    }

    $.ajax({
      url: AJAX_URL,
      type: "POST",
      data: $(this).serialize(),
      dataType: "json",
      success: function(res){
          
          console.log(res);
        if(res && res.success){
          $('#pkg_msg').show().html('<div class="alert alert-success mb-0">'+(res.message || 'Success')+'</div>');
          setTimeout(function(){ location.reload(); }, 600);
        }else{
          $('#pkg_msg').show().html('<div class="alert alert-danger mb-0">'+(res.message || 'Failed')+'</div>');
          $btn.prop('disabled', false).text($('#pkg_action').val()==='add_package' ? 'Save' : 'Update');
        }
      },
      error: function(xhr){
        $('#pkg_msg').show().html('<div class="alert alert-danger mb-0">Server error. Try again.</div>');
        $btn.prop('disabled', false).text($('#pkg_action').val()==='add_package' ? 'Save' : 'Update');
        console.log(xhr.responseText);
      }
    });
  });

})();


function deletePackage(id, reseller_id){

  Swal.fire({
    title: 'Are you sure?',
    text: "This package will be permanently deleted!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#d33',
    cancelButtonColor: '#6c757d',
    confirmButtonText: 'Yes, delete it!',
    cancelButtonText: 'Cancel'
  }).then((result) => {

    if (result.isConfirmed) {

      $.ajax({
        type: "POST",
        url: "../pages/admin_reseller/re_package_ajax.php",
        dataType: "json",
        data: {
          action: "delete_package",
          package_id: id,
          reseller_id: reseller_id
        },
        success: function (data) {

          if (data.success) {
            Swal.fire({
              icon: 'success',
              title: 'Deleted!',
              text: data.message,
              timer: 1500,
              showConfirmButton: false
            }).then(() => {
              location.reload();
            });
          } else {
            Swal.fire({
              icon: 'error',
              title: 'Failed!',
              text: data.message
            });
          }
        },
        error: function (xhr) {
          console.log(xhr.responseText);
          Swal.fire(
            'Error!',
            'Server error occurred.',
            'error'
          );
        }
      });

    }
  });
}
</script>
<?php $obj->end_script(); ?>
