<!DOCTYPE html>
<html lang="en">
<head>
  <?= view('shared/head') ?>
  <!-- Optional custom CSS -->
  <link rel="stylesheet" type="text/css" href="<?= base_url('css/library.css') ?>">

  <!-- Bootstrap CSS (for table styling) -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

  <style>
    /* Example styling for the edit popup (modal) */
    #editModal .modal-dialog {
      max-width: 600px;
      max-height: 80vh;
    }
    #editModal .modal-body {
      overflow-y: auto;
    }

    /* Force labels above inputs in filter forms */
    .filter-form .form-group label {
      display: block;
    }

    /* Hide upsell table by default */
    #upsellCommissionsContainer {
      display: none;
    }
  </style>
</head>

<body>
  <div class="wrapper">
    <!-- Navbar -->
    <?= view('layouts/navbar', ['menuItems' => $menuItems]) ?>

    <!-- Page Content -->
    <div class="content-wrapper p-4 text-navy">
      <h1>Deal Commissions (QB Sales Receipts)</h1>

      <!-- Filters + Commission Summary in a single row -->
      <div class="row">
        <!-- Left column: Filters -->
        <div class="col-md-8">
          <form method="get" action="" class="filter-form mb-3">
            <div class="form-row">
              <!-- Date Range -->
              <div class="form-group col-sm-2">
                <label for="from_date">From</label>
                <input
                  type="date"
                  class="form-control"
                  name="from_date"
                  id="from_date"
                  value="<?= esc($fromDate) ?>"
                />
              </div>
              <div class="form-group col-sm-2">
                <label for="to_date">To</label>
                <input
                  type="date"
                  class="form-control"
                  name="to_date"
                  id="to_date"
                  value="<?= esc($toDate) ?>"
                />
              </div>

              <!-- Buttons: Filter + Process Commissions + Process Kits -->
              <div class="form-group col-sm-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary mr-2">
                  Filter
                </button>
                <button type="button" class="btn btn-info" onclick="showProcessModal()">
                  Process Commissions
                </button>
              </div>
            </div>

            <div class="form-row">
              <!-- o_type Filter -->
              <div class="form-group col-sm-2">
                <label for="o_type">o_type</label>
                <select name="o_type" id="o_type" class="form-control" onchange="this.form.submit()">
                  <option value="0"   <?= ($oTypeFilter == '0')   ? 'selected' : '' ?>>Deal (0)</option>
                  <option value="1"   <?= ($oTypeFilter == '1')   ? 'selected' : '' ?>>Order (1)</option>
                  <option value="0,1" <?= ($oTypeFilter == '0,1') ? 'selected' : '' ?>>Deals &amp; Orders (0 &amp; 1)</option>
                  <option value="2"   <?= ($oTypeFilter == '2')   ? 'selected' : '' ?>>Amazon (2)</option>
                  <option value="3"   <?= ($oTypeFilter == '3')   ? 'selected' : '' ?>>Service Order (3)</option>
                </select>
              </div>

              <!-- update_status Filter -->
              <div class="form-group col-sm-2">
                <label for="update_status">Update Status</label>
                <select name="update_status" id="update_status" class="form-control" onchange="this.form.submit()">
                  <option value="ALL" <?= ($updateStatusFilter == 'ALL') ? 'selected' : '' ?>>All (0 &amp; 1)</option>
                  <option value="0" <?= ($updateStatusFilter == '0') ? 'selected' : '' ?>>Closed (0)</option>
                  <option value="1" <?= ($updateStatusFilter == '1') ? 'selected' : '' ?>>Re-Opened (1)</option>
                </select>
              </div>

              <!-- paid_status Filter -->
              <div class="form-group col-sm-2">
                <label for="paid_status">Paid Status</label>
                <select name="paid_status" id="paid_status" class="form-control" onchange="this.form.submit()">
                  <option value="Unpaid Only" <?= ($paidStatusFilter == 'Unpaid Only') ? 'selected' : '' ?>>
                    Unpaid Only
                  </option>
                  <option value="Paid Only" <?= ($paidStatusFilter == 'Paid Only') ? 'selected' : '' ?>>
                    Paid Only
                  </option>
                  <option value="ALL" <?= ($paidStatusFilter == 'ALL') ? 'selected' : '' ?>>
                    ALL
                  </option>
                </select>
              </div>
            </div>
          </form>
        </div> <!-- /.col-md-8 -->

        <!-- Right column: Commission Summary (Deals) -->
        <div class="col-md-4">
          <div class="border rounded p-3 bg-light">
            <h3>Commission Summary (Deals)</h3>
            <?php if (!empty($commissionSummary)): ?>
              <ul>
                <?php foreach ($commissionSummary as $userName => $totalCommission): ?>
                  <li><?= esc($userName) ?> - $<?= number_format($totalCommission, 2) ?></li>
                <?php endforeach; ?>
              </ul>
            <?php else: ?>
              <p>No commissions found for any user.</p>
            <?php endif; ?>
          </div>
        </div> <!-- /.col-md-4 -->
      </div> <!-- /.row -->

      <!-- A second summary row for Upsell Commissions -->
      <div class="row mt-4">
        <div class="col-md-8">
          <!-- left side blank or used for something else -->
        </div>
        <!-- Upsell Commission Summary -->
        <div class="col-md-4">
          <div class="border rounded p-3 bg-light">
            <h3>Upsell Commission Summary</h3>
            <?php if (!empty($upsellCommissionSummary)): ?>
              <ul>
                <?php foreach ($upsellCommissionSummary as $uName => $uTotal): ?>
                  <li><?= esc($uName) ?> - $<?= number_format($uTotal, 2) ?></li>
                <?php endforeach; ?>
              </ul>
            <?php else: ?>
              <p>No upsell commissions found for any user.</p>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <hr>

      <!-- Rows shown + pagination limit selector + "DisplayDD" + NEW "Hide Zeros" toggle -->
      <?php
        $rowsShown = $limit === 'ALL' ? $totalRows : count($results);
      ?>
      <div class="d-flex align-items-center justify-content-between mb-3">
        <!-- Left side: pagination limit form + "Showing X rows" -->
        <div class="d-flex align-items-center">
          <!-- Show rows dropdown -->
          <form method="get" class="mr-3" action="" style="margin-bottom:0;">
            <!-- Preserve existing filters -->
            <input type="hidden" name="o_type" value="<?= esc($oTypeFilter) ?>">
            <input type="hidden" name="update_status" value="<?= esc($updateStatusFilter) ?>">
            <input type="hidden" name="from_date" value="<?= esc($fromDate) ?>">
            <input type="hidden" name="to_date" value="<?= esc($toDate) ?>">
            <input type="hidden" name="paid_status" value="<?= esc($paidStatusFilter) ?>">

            <div class="form-group" style="margin-bottom:0;">
              <label for="limit" style="display:block;">Show rows:</label>
              <select name="limit" id="limit" class="form-control" onchange="this.form.submit()">
                <?php foreach ($limitOptions as $opt): ?>
                  <?php $selected = ($opt == $limit) ? 'selected' : ''; ?>
                  <option value="<?= esc($opt) ?>" <?= $selected ?>><?= esc($opt) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </form>

          <p class="font-weight-bold mb-0 ml-2">Showing: <?= $rowsShown ?> rows</p>
        </div>

        <!-- Right side: hide-zeros toggle + "DisplayDD" dropdown -->
        <div class="d-flex align-items-center">
          <!-- New Hide Zeros Button -->
          <button id="hideZerosBtn" type="button" class="btn btn-secondary mr-3" onclick="toggleHideZeros()">
            Show All
          </button>

          <label for="displayDD" class="mr-2 font-weight-bold">Display:</label>
          <select id="displayDD" class="form-control d-inline-block" style="width:auto;">
            <option value="deal">Deal Commissions</option>
            <option value="upsell">Upsell Commissions</option>
          </select>
        </div>
      </div>

      <!-- ========== DealCommissionsTable ========== -->
      <?php if (!empty($results) && !empty($fieldNames)): ?>
        <div id="dealCommissionsContainer" class="table-responsive">
          <table class="table table-bordered table-striped">
            <thead>
              <tr>
                <?php foreach ($fieldNames as $col): ?>
                  <th><?= esc($col) ?></th>
                <?php endforeach; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($results as $row): ?>
                <tr>
                  <?php foreach ($fieldNames as $col): ?>
                    <td
                      ondblclick="openEditModal(this)"
                      data-id="<?= isset($row['id']) ? esc($row['id']) : '' ?>"
                      data-field="<?= esc($col) ?>"
                    >
                      <?= isset($row[$col]) ? esc($row[$col]) : '' ?>
                    </td>
                  <?php endforeach; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>

          <!-- Pagination if limit != ALL -->
          <?php if ($limit !== 'ALL' && $totalPages > 1): ?>
            <nav>
              <ul class="pagination">
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                  <li class="page-item <?= ($p == $currentPage) ? 'active' : '' ?>">
                    <a class="page-link"
                       href="?limit=<?= urlencode($limit) ?>
                          &o_type=<?= urlencode($oTypeFilter) ?>
                          &update_status=<?= urlencode($updateStatusFilter) ?>
                          &from_date=<?= urlencode($fromDate) ?>
                          &to_date=<?= urlencode($toDate) ?>
                          &paid_status=<?= urlencode($paidStatusFilter) ?>
                          &page=<?= $p ?>">
                      <?= $p ?>
                    </a>
                  </li>
                <?php endfor; ?>
              </ul>
            </nav>
          <?php endif; ?>
        </div>
      <?php else: ?>
        <p id="dealCommissionsContainer">No data found in <strong>bbt_qb_sales_receipts</strong> with the selected filters.</p>
      <?php endif; ?>

      <!-- ========== UpsellCommissionsTable ========== -->
      <?php if (!empty($upsellResults) && !empty($upsellFieldNames)): ?>
        <div id="upsellCommissionsContainer" class="table-responsive">
          <table class="table table-bordered table-striped">
            <thead>
              <tr>
                <?php foreach ($upsellFieldNames as $col): ?>
                  <th><?= esc($col) ?></th>
                <?php endforeach; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($upsellResults as $row): ?>
                <tr>
                  <?php foreach ($upsellFieldNames as $col): ?>
                    <td><?= isset($row[$col]) ? esc($row[$col]) : '' ?></td>
                  <?php endforeach; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>

          <!-- We reuse the same limit/page as deal commissions. Same pagination possible. -->
          <?php if ($limit !== 'ALL' && $upsellTotalPages > 1): ?>
            <nav>
              <ul class="pagination">
                <?php for ($p = 1; $p <= $upsellTotalPages; $p++): ?>
                  <li class="page-item <?= ($p == $currentPage) ? 'active' : '' ?>">
                    <a class="page-link"
                       href="?limit=<?= urlencode($limit) ?>
                          &o_type=<?= urlencode($oTypeFilter) ?>
                          &update_status=<?= urlencode($updateStatusFilter) ?>
                          &from_date=<?= urlencode($fromDate) ?>
                          &to_date=<?= urlencode($toDate) ?>
                          &paid_status=<?= urlencode($paidStatusFilter) ?>
                          &page=<?= $p ?>">
                      <?= $p ?>
                    </a>
                  </li>
                <?php endfor; ?>
              </ul>
            </nav>
          <?php endif; ?>
        </div>
      <?php else: ?>
        <!-- If no upsell data, still show container (hidden by default) -->
        <div id="upsellCommissionsContainer">
          <p>No upsell data found in <strong>bbt_upsell_tracking</strong> for these filters.</p>
        </div>
      <?php endif; ?>
    </div><!-- /.content-wrapper -->
  </div><!-- /.wrapper -->

  <!-- Modal for Editing (Inline) -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Edit Field</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span>&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <textarea id="editContent" class="form-control" rows="5"></textarea>
          <input type="hidden" id="editFieldName" value="" />
          <input type="hidden" id="editRowId" value="" />
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Go Back</button>
          <button type="button" class="btn btn-success" onclick="saveChanges()">Save</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Modal for Processing Commissions -->
  <div class="modal fade" id="processModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Process Commissions</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span>&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to process these commissions as paid?</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Go Back</button>
          <button type="button" class="btn btn-success" onclick="submitProcessForm()">Process Now</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Hidden form for "Process Commissions" confirmation -->
  <form method="get"
        action="<?= base_url('dealcommissions/processCommissions') ?>"
        id="processForm"
        style="display:none;">
    <input type="hidden" name="from_date" value="<?= esc($fromDate) ?>">
    <input type="hidden" name="to_date"   value="<?= esc($toDate) ?>">
    <input type="hidden" name="o_type"    value="<?= esc($oTypeFilter) ?>">
    <input type="hidden" name="update_status" value="<?= esc($updateStatusFilter) ?>">
  </form>

  <!-- jQuery + Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

  <script>
    // On load, set DisplayDD based on cookie
    $(function() {
      let cookieVal = getCookie('displayMode');
      if (!cookieVal) {
        cookieVal = 'deal'; // default to 'Deal Commissions'
      }
      $('#displayDD').val(cookieVal);

      // By default, let's hide zeros (so the button should say "Show All")
      hideZeros = true;
      $('#hideZerosBtn').text('Show All');

      // Show/hide the correct table, then apply hide-zero logic
      toggleTables(cookieVal);

      // if user changes dropdown
      $('#displayDD').on('change', function() {
        const mode = $(this).val();
        setCookie('displayMode', mode, 365); // store for 1 year
        toggleTables(mode);
      });
    });

    // track whether we are hiding zeros
    let hideZeros = false;

    function toggleTables(mode) {
      if (mode === 'upsell') {
        $('#dealCommissionsContainer').hide();
        $('#upsellCommissionsContainer').show();
      } else {
        $('#dealCommissionsContainer').show();
        $('#upsellCommissionsContainer').hide();
      }
      // Re-apply hide/show zero logic if needed
      applyHideZeroRows(hideZeros);
    }

    // "Hide Zeros" toggle
    function toggleHideZeros() {
      hideZeros = !hideZeros;
      if (hideZeros) {
        $('#hideZerosBtn').text('Show All');
      } else {
        $('#hideZerosBtn').text('Hide Zeros');
      }
      applyHideZeroRows(hideZeros);
    }

    // Hide or show rows where "Gross Profit" = $0.00 (only in upsell table)
    // Note: Now the columns are: 0 => inv_no, 1 => Revenue, 2 => Gross Profit, then user columns.
    function applyHideZeroRows(hide) {
      if ($('#upsellCommissionsContainer').is(':visible')) {
        if (hide) {
          $('#upsellCommissionsContainer table tbody tr').each(function() {
            let gpCell = $(this).find('td:eq(2)');
            let gpVal  = parseFloat(gpCell.text().replace(/[^0-9.\-]/g, ''));
            if (!isNaN(gpVal) && gpVal === 0) {
              $(this).hide();
            } else {
              $(this).show();
            }
          });
        } else {
          $('#upsellCommissionsContainer table tbody tr').show();
        }
      }
    }

    // Cookie helpers
    function setCookie(name, value, days) {
      const d = new Date();
      d.setTime(d.getTime() + (days * 24*60*60*1000));
      let expires = "expires="+ d.toUTCString();
      document.cookie = name + "=" + value + "; " + expires + "; path=/";
    }

    function getCookie(name) {
      const cname = name + "=";
      const decodedCookie = decodeURIComponent(document.cookie);
      const ca = decodedCookie.split(';');
      for(let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();
        if (c.indexOf(cname) === 0) {
          return c.substring(cname.length, c.length);
        }
      }
      return "";
    }

    // Confirmation for "Process Commissions"
    function showProcessModal() {
      $('#processModal').modal('show');
    }
    function submitProcessForm() {
      document.getElementById('processForm').submit();
    }

    // Inline edit modal
    function openEditModal(tdElem) {
      const rowId   = tdElem.getAttribute('data-id');
      if (!rowId) {
        alert('No "id" found in this row. Cannot edit.');
        return;
      }
      const field   = tdElem.getAttribute('data-field');
      const content = tdElem.innerText;

      document.getElementById('editRowId').value     = rowId;
      document.getElementById('editFieldName').value = field;
      document.getElementById('editContent').value   = content;

      $('#editModal').modal('show');
    }

    // AJAX to update field in DB
    function saveChanges() {
      const rowId    = document.getElementById('editRowId').value;
      const field    = document.getElementById('editFieldName').value;
      const newValue = document.getElementById('editContent').value;

      $.ajax({
        url: '<?= base_url('dealcommissions/updateField') ?>',
        method: 'POST',
        data: { id: rowId, field: field, value: newValue },
        success: function(response) {
          if (response.success) {
            const selector = 'td[data-id="' + rowId + '"][data-field="' + field + '"]';
            $(selector).text(newValue);
            $('#editModal').modal('hide');
          } else {
            alert('Update failed: ' + (response.message || 'Unknown error'));
          }
        },
        error: function(xhr, status, error) {
          alert('AJAX error: ' + error);
        }
      });
    }
  </script>
</body>
</html>
