<!DOCTYPE html>
<html lang="en">
<head>
    <?= view('shared/head') ?>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .content-wrapper {
            min-height: 100vh;
            background: #f8f9fa;
            padding: 20px;
        }
        .hiddenRow {
            padding: 0 !important;
        }
        .detail-row {
            background-color: #f2f2f2;
        }
        .diff-green {
            background-color: #ccffcc !important; /* light green */
        }
        .diff-red {
            background-color: #ffcccc !important; /* light red */
        }
        tr.accordion-toggle {
            cursor: pointer;
        }
        /* Make the notes column visually distinct if desired */
        .audit-notes-cell {
            white-space: pre-wrap; /* so new lines show if the notes have them */
        }
    </style>
</head>
<body>
<div class="wrapper">
    <?= view('layouts/navbar', ['menuItems' => $menuItems]) ?>
    <div class="content-wrapper text-navy">
        <h1>Audit Liability Accounts</h1>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger">
                <?= esc($error) ?>
            </div>
        <?php endif; ?>

        <form method="post" action="<?= base_url('auditliabilityaccounts') ?>">
            <div class="form-row">
                <!-- FROM DATE -->
                <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($from_date) ?>"
                    />
                </div>

                <!-- TO DATE -->
                <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($to_date) ?>"
                    />
                </div>

                <!-- VIEW SELECT DROPDOWN (partial) -->
                <div class="col-sm-3">
                    <?= view('auditquickbooks/_view_select_dropdown', [
                        'view_select' => $view_select ?? 'pull',
                    ]) ?>
                </div>
            </div>

            <!-- Filter Button -->
            <div class="form-row mt-3">
                <div class="col-auto">
                    <button class="btn btn-primary" type="submit">
                        Filter
                    </button>
                </div>

                <!-- Show only Issues checkbox -->
                <div class="col-auto d-flex align-items-center">
                    <input type="checkbox" id="showOnlyIssues" class="mr-1" />
                    <label for="showOnlyIssues" class="mb-0">Show only Issues </label>
                </div>
            </div>
        </form>

        <hr/>

        <!-- Example of the older table (optional) -->
        <?php if (!empty($results)): ?>
            <div class="table-responsive mt-4">
                <table class="table table-bordered table-striped bg-white">
                    <thead class="thead-dark">
                    <tr>
                        <th>ID</th>
                        <th>Doc Number</th>
                        <th>Account</th>
                        <th>Liability Amount</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($results as $row): ?>
                        <tr>
                            <td><?= esc($row['id']) ?></td>
                            <td><?= esc($row['doc_number'] ?? '') ?></td>
                            <td><?= esc($row['some_account'] ?? '') ?></td>
                            <td><?= esc($row['some_amount'] ?? '0') ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p class="mt-4">No liability-account data found for the selected date range (old table).</p>
        <?php endif; ?>

        <hr />

        <!-- NEW: AuditPageTable to show Deal ID, o_type, Inv #, JE Liability, SR Liability, Difference, and Audit Notes -->
        <h3 class="mt-5">AuditPageTable</h3>
        <?php if (!empty($auditPageResults)): ?>
            <div class="table-responsive mt-4">
                <table class="table table-bordered table-striped bg-white">
                    <thead class="thead-dark">
                    <tr>
                        <th>Deal ID</th>
                        <th>o_type</th>
                        <th>Invoice Number</th>
                        <th>JE Liability Amount</th>
                        <th>SR Liability Amount</th>
                        <th>Difference</th>
                        <th>Audit Notes</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($auditPageResults as $index => $rowData): ?>
                        <?php 
                            // Decide class for difference cell
                            $diffCellClass = ($rowData['difference'] == 0) ? 'diff-green' : 'diff-red';
                            $differenceRaw = (float) $rowData['difference']; // for data attribute usage
                        ?>
                        <!-- Main row that toggles the collapse -->
                        <tr class="accordion-toggle main-row"
                            data-toggle="collapse"
                            data-target="#detailRow<?= $index ?>"
                            aria-expanded="false"
                            aria-controls="detailRow<?= $index ?>"
                            data-difference="<?= $differenceRaw ?>"
                        >
                            <td><?= esc($rowData['deal_id']) ?></td>
                            <td><?= esc($rowData['o_type']) ?></td>
                            <td><?= esc($rowData['inv_no']) ?></td>
                            <td><?= number_format($rowData['je_liability'], 2) ?></td>
                            <td><?= number_format($rowData['sr_liability'], 2) ?></td>
                            <td class="<?= $diffCellClass ?>">
                                <?= number_format($rowData['difference'], 2) ?>
                            </td>
                            <!-- Double-clickable cell for Audit Notes -->
                            <td class="audit-notes-cell"
                                data-qb-id="<?= $rowData['qb_id'] ?>"
                                style="white-space: pre-wrap;"
                            >
                                <?= esc($rowData['audit_notes']) ?>
                            </td>
                        </tr>
                        <!-- Collapsible detail row -->
                        <tr class="detail-row" data-difference="<?= $differenceRaw ?>">
                            <td colspan="7" class="hiddenRow">
                                <div id="detailRow<?= $index ?>" class="collapse">
                                    <div class="p-3">
                                        <strong>Journal Entries (Debit side):</strong>
                                        <?php if (!empty($rowData['journalEntriesDebitArray'])): ?>
                                            <ul>
                                                <?php foreach ($rowData['journalEntriesDebitArray'] as $deb): ?>
                                                    <li>
                                                        <a href="https://qbo.intuit.com/app/journal?txnId=<?= $deb['je_id'] ?>" target="_blank">
                                                            Journal #<?= $deb['je_id'] ?>
                                                        </a>
                                                        &nbsp;&ndash;&nbsp;
                                                        <span class="text-info">
                                                            <?= number_format($deb['amount'], 2) ?>
                                                        </span>
                                                    </li>
                                                <?php endforeach; ?>
                                            </ul>
                                        <?php else: ?>
                                            <p class="text-muted">None found</p>
                                        <?php endif; ?>

                                        <strong>Journal Entries (Credit side):</strong>
                                        <?php if (!empty($rowData['journalEntriesCreditArray'])): ?>
                                            <ul>
                                                <?php foreach ($rowData['journalEntriesCreditArray'] as $cred): ?>
                                                    <li>
                                                        <a href="https://qbo.intuit.com/app/journal?txnId=<?= $cred['je_id'] ?>" target="_blank">
                                                            Journal #<?= $cred['je_id'] ?>
                                                        </a>
                                                        &nbsp;&ndash;&nbsp;
                                                        <span class="text-info">
                                                            <?= number_format($cred['amount'], 2) ?>
                                                        </span>
                                                    </li>
                                                <?php endforeach; ?>
                                            </ul>
                                        <?php else: ?>
                                            <p class="text-muted">None found</p>
                                        <?php endif; ?>

                                        <strong>Sales Receipts (SR Liability):</strong>
                                        <?php if (!empty($rowData['salesReceiptsArray'])): ?>
                                            <ul>
                                                <?php foreach ($rowData['salesReceiptsArray'] as $srId): ?>
                                                    <li>
                                                        <a href="https://qbo.intuit.com/app/salesreceipt?txnId=<?= $srId ?>" target="_blank">
                                                            Sales Receipt #<?= $srId ?>
                                                        </a>
                                                    </li>
                                                <?php endforeach; ?>
                                            </ul>
                                        <?php else: ?>
                                            <p class="text-muted">None found</p>
                                        <?php endif; ?>
                                    </div> <!-- /p-3 -->
                                </div> <!-- /collapse -->
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p class="mt-4">No matching bbt_qb_sales_receipts rows found in this date range for update_status = 0.</p>
        <?php endif; ?>
    </div>
</div>

<!-- Modal for editing Audit Notes -->
<div class="modal fade" id="editNotesModal" tabindex="-1" aria-labelledby="editNotesModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="editNotesForm">
        <div class="modal-header">
          <h5 class="modal-title" id="editNotesModalLabel">Edit Audit Notes</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        
        <div class="modal-body">
          <input type="hidden" id="modalQbId" name="qb_id" value="">
          <div class="form-group">
            <label for="modalAuditNotes">Notes</label>
            <textarea class="form-control" id="modalAuditNotes" name="audit_notes" rows="5"></textarea>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="submit" id="saveNotesBtn" class="btn btn-primary">Save Notes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- 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>
$(function() {
    // ----------------------------------------
    // 1) "Show only Issues" checkbox logic
    //    Hides rows with difference = 0
    // ----------------------------------------
    $('#showOnlyIssues').on('change', function() {
        if ($(this).is(':checked')) {
            // Hide all rows where data-difference == 0
            $('tr.main-row').each(function() {
                var diffVal = parseFloat($(this).attr('data-difference'));
                if (diffVal === 0) {
                    $(this).hide();
                    // also hide the detail row (the next one)
                    $(this).next('.detail-row').hide();
                }
            });
        } else {
            // Show them back
            $('tr.main-row').each(function() {
                var diffVal = parseFloat($(this).attr('data-difference'));
                if (diffVal === 0) {
                    $(this).show();
                    // show detail row as well
                    $(this).next('.detail-row').show();
                }
            });
        }
    });

    // ----------------------------------------
    // 2) Double-click on the Audit Notes cell
    //    to open the modal
    // ----------------------------------------
    $('.audit-notes-cell').on('dblclick', function(e) {
        e.stopPropagation(); // prevent triggering row collapse
        var qbId     = $(this).data('qb-id');
        var currText = $(this).text();

        // Populate modal fields
        $('#modalQbId').val(qbId);
        $('#modalAuditNotes').val(currText.trim());

        // Show the modal
        $('#editNotesModal').modal('show');
    });

    // ----------------------------------------
    // 3) Save (AJAX) in the modal
    // ----------------------------------------
    $('#editNotesForm').on('submit', function(e) {
        e.preventDefault();

        var qbId       = $('#modalQbId').val();
        var auditNotes = $('#modalAuditNotes').val();

        $.ajax({
            url: '<?= base_url('auditliabilityaccounts/updateAuditNotes') ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                qb_id: qbId,
                audit_notes: auditNotes
            },
            success: function(response) {
                if (response.status === 'success') {
                    // Update the cell text in the table
                    $('.audit-notes-cell[data-qb-id="' + qbId + '"]').text(auditNotes);

                    // Close modal
                    $('#editNotesModal').modal('hide');
                } else {
                    alert('Error: ' + (response.message || 'Unable to update notes.'));
                }
            },
            error: function(xhr, status, error) {
                alert('An unexpected error occurred: ' + error);
            }
        });
    });
});
</script>

</body>
</html>
