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

    <!-- Bootstrap CSS (if not already loaded in your layout) -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>
        /* Example styling for main content area */
        .content-wrapper {
            min-height: 100vh;
            background: #f8f9fa; /* light gray */
            padding: 20px;
        }
        /* Modal fix for scrolling */
        .modal-dialog-scrollable .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }
        /* Cursor changes on editable fields */
        td[data-field="notes"] {
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="wrapper">

    <!-- Navbar / Left Sidebar -->
    <?= view('layouts/navbar', ['menuItems' => $menuItems]) ?>

    <!-- Page Content -->
    <div class="content-wrapper text-navy">
        <h1>Audit Payments</h1>

        <!-- Filter Form -->
        <form method="get" action="" class="mb-3">
            <div class="row">
                <!-- Date From -->
                <div class="col-sm-2">
                    <label for="from_date">From</label>
                    <input
                        type="date"
                        name="from_date"
                        id="from_date"
                        class="form-control"
                        value="<?= esc($fromDate) ?>"
                    />
                </div>
                <!-- Date To -->
                <div class="col-sm-2">
                    <label for="to_date">To</label>
                    <input
                        type="date"
                        name="to_date"
                        id="to_date"
                        class="form-control"
                        value="<?= esc($toDate) ?>"
                    />
                </div>
                <!-- Payment Type -->
                <div class="col-sm-2">
                    <label for="p_type">Payment Type</label>
                    <select name="p_type" id="p_type" class="form-control">
                        <option value="ALL" <?= ($pTypeFilter === 'ALL') ? 'selected' : '' ?>>
                            ALL
                        </option>
                        <?php if (! empty($paymentTypes)): ?>
                            <?php foreach ($paymentTypes as $pt): ?>
                                <option value="<?= esc($pt) ?>" <?= ($pTypeFilter === $pt) ? 'selected' : '' ?>>
                                    <?= esc($pt) ?>
                                </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>

                <!-- Filter Button -->
                <div class="col-sm-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary">
                        Filter
                    </button>
                </div>
            </div>
        </form>

        <!-- Limit + Pagination info -->
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div class="d-flex align-items-center">
                <form method="get" action="" style="margin-bottom:0;">
                    <!-- preserve existing filters -->
                    <input type="hidden" name="from_date" value="<?= esc($fromDate) ?>">
                    <input type="hidden" name="to_date"   value="<?= esc($toDate) ?>">
                    <input type="hidden" name="p_type"    value="<?= esc($pTypeFilter) ?>">

                    <label for="limit" class="mr-2 font-weight-bold">Show rows:</label>
                    <select name="limit" id="limit" class="form-control d-inline-block" style="width:auto;"
                            onchange="this.form.submit()">
                        <?php foreach ($limitOptions as $opt): ?>
                            <option value="<?= esc($opt) ?>" <?= ($opt == $limit) ? 'selected' : '' ?>>
                                <?= esc($opt) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </form>

                <!-- Display "Showing X of Y" if you like -->
                <?php
                    $rowsShown = ($limit === 'ALL')
                        ? $totalRows
                        : count($results);
                ?>
                <span class="ml-3">
                    Showing <?= $rowsShown ?> of <?= $totalRows ?> rows
                </span>
            </div>

            <!-- Right side: could place extra button(s) or info -->
            <div></div>
        </div>

        <!-- The Data Table -->
        <div class="table-responsive">
            <table class="table table-bordered table-striped bg-white">
                <thead class="thead-dark">
                    <tr>
                        <th>Notes</th>
                        <th>Quickbooks Id</th>
                        <th>COB#</th>
                        <th>Amount</th>
                        <th>Date</th>
                        <th>Is Reversed</th>
                        <th>Order Type</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($results)): ?>
                    <?php foreach ($results as $row): ?>
                        <?php
                            // Prepare data for each column
                            $notes    = $row['notes']        ?? '';
                            $qbId     = $row['qb_id']        ?? '';
                            $cob      = $row['cob_number']   ?? '';  // from bbt_qb_sales_receipts.inv_no
                            $amount   = $row['amount']       ?? '0.00';
                            $date     = $row['createdat']    ?? '';
                            $dType    = $row['d_type']       ?? '1'; // '1' => default, '0' => reversed
                            $oType    = $row['o_type']       ?? '0'; // 0,1,2,3

                            // Format "Is Reversed"
                            $isReversedText = ($dType === '1') ? 'default' : 'reversed';

                            // Format "Order Type"
                            switch ($oType) {
                                case '1': $oTypeText = 'Order';         break;
                                case '2': $oTypeText = 'Amazon Order';  break;
                                case '3': $oTypeText = 'Service Order'; break;
                                default:  $oTypeText = 'Deal';          break;
                            }
                        ?>
                        <tr>
                            <!-- NOTES (inline editable) -->
                            <td
                              data-id="<?= esc($row['id']) ?>"
                              data-field="notes"
                              ondblclick="openEditModal(this)"
                            >
                                <?= esc($notes) ?>
                            </td>

                            <!-- Quickbooks Id -->
                            <td><?= esc($qbId) ?></td>

                            <!-- COB# (inv_no from the join) -->
                            <td><?= esc($cob) ?></td>

                            <!-- Amount -->
                            <td><?= esc($amount) ?></td>

                            <!-- Date (createdat) -->
                            <td><?= esc($date) ?></td>

                            <!-- Is Reversed -->
                            <td><?= esc($isReversedText) ?></td>

                            <!-- Order Type -->
                            <td><?= esc($oTypeText) ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" class="text-center">
                            No records found with the selected filters.
                        </td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- 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) ?>
                                  &p_type=<?= urlencode($pTypeFilter) ?>
                                  &from_date=<?= urlencode($fromDate) ?>
                                  &to_date=<?= urlencode($toDate) ?>
                                  &page=<?= $p ?>">
                               <?= $p ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        <?php endif; ?>

    </div><!-- /.content-wrapper -->
</div><!-- /.wrapper -->

<!-- Inline Edit Modal -->
<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 Notes</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">
                  Cancel
              </button>
              <button type="button" class="btn btn-primary" onclick="saveChanges()">
                  Save
              </button>
          </div>
      </div>
    </div>
</div>

<!-- jQuery + Bootstrap JS (if not already loaded) -->
<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>
function openEditModal(tdElem) {
    const rowId   = tdElem.getAttribute('data-id');
    const field   = tdElem.getAttribute('data-field');
    const content = tdElem.innerText;

    // Basic safety checks
    if (!rowId || !field) {
        alert('No row id or field available.');
        return;
    }

    // Populate hidden fields
    document.getElementById('editRowId').value     = rowId;
    document.getElementById('editFieldName').value = field;
    document.getElementById('editContent').value   = content;

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

function saveChanges() {
    const rowId    = document.getElementById('editRowId').value;
    const field    = document.getElementById('editFieldName').value;
    const newValue = document.getElementById('editContent').value;

    $.ajax({
        url: '<?= base_url('auditpayments/updateField') ?>',
        method: 'POST',
        data: {
            id: rowId,
            field: field,
            value: newValue
        },
        success: function(response) {
            if (response.success) {
                // Update the cell text directly in the table
                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>
