<?php //ini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL);

if (file_exists('../../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Inputs may come via GET or POST
$startStr = trim($_REQUEST['start'] ?? '');
$endStr   = trim($_REQUEST['end']   ?? '');
$q = trim((string)($_REQUEST['q'] ?? ''));

// dd-mm-yyyy → Unix (start-of-day)
function parseDMYToUnix(?string $dmy): ?int {
    $dmy = trim((string)$dmy);
    if ($dmy === '') return null;
    $dmy = str_replace('/', '-', $dmy);
    if (!preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/', $dmy, $m)) return null;
    [$all,$d,$m,$y] = $m;
    return strtotime(sprintf('%04d-%02d-%02d 00:00:00', (int)$y, (int)$m, (int)$d));
}

// Default = current month
$now = time();
$firstOfMonth = strtotime(date('Y-m-01 00:00:00', $now));
$lastDay      = (int)date('t', $now); // days in month
$lastOfMonth  = strtotime(date("Y-m-{$lastDay} 23:59:59", $now));

$start = parseDMYToUnix($startStr) ?? $firstOfMonth;
$end   = parseDMYToUnix($endStr)
       ?? ( // if no end provided, default to "today 23:59:59" within current month
            ($now < $lastOfMonth ? strtotime(date('Y-m-d 23:59:59', $now)) : $lastOfMonth)
          );

// use inclusive end-of-day for BETWEEN
$endEOD = $end;


$rows = [];
$tot_net = 0.0; $tot_vat = 0.0; $tot_gross = 0.0; $tot_comm = 0.0;

$sql = "
  SELECT `id`,`registered`,`pType`,`payee`,`details`,`vat`,`totals`,`commission`,
         `method`,`invoice`,`chequeNo`,`date`
  FROM `receipts`
  WHERE `date` BETWEEN ? AND ?
";

$types = 'ii';
$params = [$start, $endEOD];

$term = trim((string)$q);
if ($term !== '') {
    $sql .= " AND (
" .
            "   `payee` LIKE ? OR
" .
            "   `details` LIKE ? OR
" .
            "   `method` LIKE ? OR
" .
            "   `invoice` LIKE ? OR
" .
            "   `chequeNo` LIKE ? OR
" .
            "   `totals` LIKE ? OR
" .
            "   CAST(`commission` AS CHAR) LIKE ? OR
" .
            "   CAST(`id` AS CHAR) LIKE ?
" .
            " )";
    $like = '%' . $term . '%';
    $types .= 'ssssssss';
    $params = array_merge($params, [$like,$like,$like,$like,$like,$like,$like,$like]);
}

$sql .= " ORDER BY `date` DESC, `id` DESC";

$stmt = $GLOBALS['con']->prepare($sql);

// Bind params dynamically
$bind = [$types];
foreach ($params as $k => $v) {
    $bind[] = &$params[$k];
}
call_user_func_array([$stmt, 'bind_param'], $bind);

$stmt->execute();
$res = $stmt->get_result();

while($r = $res->fetch_assoc()){
    $net = 0.0; $vat = 0.0; $gross = 0.0;
    if (!empty($r['totals'])) {
        $parts = explode('|', $r['totals']);
        $net = (float)str_replace(',', '', $parts[0] ?? '0');
        $vat = (float)str_replace(',', '', $parts[1] ?? '0');
        $gross = $net + $vat;
    } else {
        // Fallback: if legacy rows only had vat flag, try to compute or just use net as totals
        $gross = 0.0;
    }
    $comm = (float)($r['commission'] ?? 0);

    $tot_net   += $net;
    $tot_vat   += $vat;
    $tot_gross += $gross;
    $tot_comm  += $comm;

    $rows[] = [
        'id'      => (int)$r['id'],
        'date'    => date('d-m-Y', (int)$r['date']),
        'payee'   => $r['payee'],
        'details' => $r['details'],
        'net'     => $net,
        'vat'     => $vat,
        'gross'   => $gross,
        'comm'    => $comm,
        'method'  => $r['method'],
        'invoice' => $r['invoice'],
        'cheque'  => $r['chequeNo'],
    ];
}
$stmt->close();

function gbp($n){ return '£' . number_format((float)$n, 2); }
?>
<div class="table-responsive">
    <table class="table table-striped table-hover align-middle table-sm mb-0">
        <thead class="table-dark">
            <tr>
                <th scope="col">Date</th>
                <th scope="col">Payee</th>
                <th scope="col">Details</th>
                <th scope="col" class="text-end">Net</th>
                <th scope="col" class="text-end">VAT</th>
                <th scope="col" class="text-end">Gross</th>
                <th scope="col" class="text-end">Commission</th>
                <th scope="col">Method</th>
                <th scope="col">Invoice(s)</th>
                <th scope="col" class="text-center noprint">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if(empty($rows)): ?>
            <tr>
                <td colspan="10" class="text-center py-4">No receipts in this period.</td>
            </tr>
            <?php else: foreach($rows as $row): ?>
            <tr data-id="<?= (int)$row['id'] ?>">
                <td><?= htmlspecialchars($row['date']) ?></td>
                <td><?= htmlspecialchars($row['payee']) ?></td>
                <td><?= nl2br(htmlspecialchars($row['details'])) ?></td>
                <td class="text-end"><?= gbp($row['net']) ?></td>
                <td class="text-end"><?= gbp($row['vat']) ?></td>
                <td class="text-end"><?= gbp($row['gross']) ?></td>
                <td class="text-end"><?= gbp($row['comm']) ?></td>
                <td>
                    <?= htmlspecialchars($row['method']) ?>
                    <?php if(strtolower($row['method'])==='cheque' && !empty($row['cheque'])): ?>
                    <span class="text-muted ms-1">#<?= htmlspecialchars($row['cheque']) ?></span>
                    <?php endif; ?>
                </td>
                <td><?= htmlspecialchars($row['invoice']) ?></td>
                <td class="text-center noprint">
                    <button type="button" class="btn btn-sm btn-secondary me-1 btn-edit-row"
                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Edit receipt">
                        <i class="fad fa-edit"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-info me-1 btn-print-row"
                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Print row">
                        <i class="fad fa-print"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-danger btn-delete-row"
                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Delete receipt">
                        <i class="fad fa-trash"></i>
                    </button>
                </td>

            </tr>
            <?php endforeach; endif; ?>
        </tbody>
        <tfoot class="table-dark">
            <tr>
                <th colspan="3" class="text-end">Totals</th>
                <th class="text-end"><?= gbp($tot_net) ?></th>
                <th class="text-end"><?= gbp($tot_vat) ?></th>
                <th class="text-end"><?= gbp($tot_gross) ?></th>
                <th class="text-end"><?= gbp($tot_comm) ?></th>
                <th colspan="3"></th>
            </tr>
        </tfoot>
    </table>

</div>

<div class="table-responsive mt-3">
    <table class="vatBox table table-bordered table-sm" style="width:50%;">
        <thead class="table-dark">
            <tr>
                <th colspan="2">Report Totals</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>VAT FROM OUTGOINGS</td>
                <td><?= gbp($tot_vat) ?></td>
            </tr>
            <tr>
                <td>TOTAL EXCLUDING VAT</td>
                <td><?= gbp($tot_net) ?></td>
            </tr>
        </tbody>
    </table>
</div>
<script>
// Inline bindings for this fragment. Executed by loadContentAndExecuteScripts.
(function() {
    const root = document.currentScript.parentElement;

    // Tooltips bootstrapper for newly injected nodes
    root.querySelectorAll('[data-mdb-tooltip-init]').forEach(el => {

    });

    function findRowId(btn) {
        const tr = btn.closest('tr');
        return tr ? Number(tr.dataset.id) : 0;
    }

    // Edit
    root.querySelectorAll('.btn-edit-row').forEach(btn => {
        btn.addEventListener('click', () => {
            const id = findRowId(btn);
            if (!id) return;

            const dest = ROOT_URL + '/includes/finance/receipts/finance_rcp_edit.php' +
                '?id=' + encodeURIComponent(id) +
                '&tenant=' + encodeURIComponent(TENANT_URL);

            // Standard EnRep modal loader
            loadModalContent(
                dest,
                'popupBox',
                'modal-xl',
                1060,
                'true',
                'Edit receipt',
                'cancelEdit',
                () => {
                    const modal = document.getElementById('popupBox');
                    if (!modal) return;

                    modal.querySelectorAll('.date-picker').forEach((el) => {
                        if (mdb.Datepicker.getInstance(el)) return;

                        const format = el.dataset.format || 'dd-mm-yyyy';
                        new mdb.Datepicker(el, {
                            confirmDateOnSelect: true,
                            format
                        });
                    });
                }
            );
        });
    });


    // Delete
    root.querySelectorAll('.btn-delete-row').forEach(btn => {
        btn.addEventListener('click', () => {
            const id = findRowId(btn);
            if (!id) return;

            // Confirm via your bespoke modal pattern
            const dest = '<p class="text-center">Are you sure you wish to delete this receipt?</p>'
            // Callback to execute after confirm
            const doDelete = async () => {
                try {
                    const payload = new URLSearchParams({
                        FUNCTION: 'delete_receipt',
                        id: String(id),
                        tenant: TENANT_URL
                    });
                    const res = await fetch(ROOT_URL + '/includes/finance/receipts/finance_receipts_functions.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: payload
                    });
                    const txt = (await res.text()).trim().toLowerCase();
                    if (txt.includes('success') || txt === 's') {
                        showResponse('success', 'Receipt deleted');
                        killModal('popupBox')
                        if (window.reloadList) reloadList();
                    } else {
                        showResponse('danger', 'Delete failed: ' + (txt || 'Unknown error'));
                    }
                } catch (e) {
                    showResponse('danger', 'Network error deleting receipt');
                }
            };

            // Use your loader signature: loadModalContent(url, modalId, size, zIndex, static, title, cancelId, callback)
            loadModalContent(dest, "popupBox", "modal-md", 1060, "true", "Confirm Removal", "cancelConfirm", doDelete);
        });
    });

    // Row print -> use printContainer(contentHtml, options)
    document.querySelectorAll('#receiptsList .btn-print-row').forEach(btn => {
        btn.addEventListener('click', () => {
            const tr = btn.closest('tr');
            if (!tr) return;
            const title = 'Receipts entry';

            const contentHtml = buildRowPrintHTML(tr, title);
            const header = title;

            if (typeof printContainer === 'function') {
                printContainer(contentHtml, {
                    orientation: 'landscape',
                    header: `<p>${header}</p>`,
                    footer: `<p>Generated by EnRep Reporting System: ${new Date().toLocaleDateString()}</p>`,
                    logoUrl: 'images/company/logo.jpg',
                    styles: [
                        `${ROOT_URL}/src/css/print.css`,
                    ],
                });
            } else {
                // Fallback: open window
                const w = window.open('', '_blank');
                w.document.write(`<html><head><meta charset="utf-8"><title>${header}</title></head><body>${contentHtml}</body></html>`);
                w.document.close();
                w.focus();
                w.print();
                w.close();
            }
        });
    });

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

    function buildRowPrintHTML(tr, title) {
        const tds = Array.from(tr.querySelectorAll('td'));
        const safe = (i) => (tds[i]?.textContent || '').trim();

        const date = safe(0);
        const payee = safe(1);
        const details = safe(2);
        const net = safe(3);
        const vat = safe(4);
        const gross = safe(5);
        const commission = safe(6);
        const method = safe(7);
        const invoice = safe(8);

        // try extract cheque no from text like ". #1234"
        let cheque = '';
        const methodTxt = method || '';
        const m = methodTxt.match(/#\s*([^\s]+)/);
        if (m) cheque = m[1];

        // equal-width summary table
        const cols = cheque ? 5 : 4;
        const colW = (100 / cols).toFixed(2) + '%';
        const colgroup = Array.from({
                length: cols
            })
            .map(() => `<col style="width:${colW}">`)
            .join('');

        return `
      <div class="print-wrap" style="padding:24px;">
        <div style="margin-bottom:16px;">
          <h3 style="margin:0; font-weight:600;">${escapeHtml(title)}</h3>
          <div style="color:#666;">Printed: ${new Date().toLocaleString()}</div>
        </div>

        <table class="kv table-borderless" style="width:100%; margin-bottom:0; border-collapse:collapse;">
          <tbody>
            <tr><th style="text-align:right; padding:6px 10px; width:25%;">Date</th><td style="padding:6px 10px;">${date}</td></tr>
            <tr><th style="text-align:right; padding:6px 10px;">Payee</th><td style="padding:6px 10px;">${escapeHtml(payee)}</td></tr>
            <tr><th style="text-align:right; padding:6px 10px;">Details</th><td style="padding:6px 10px;">${escapeHtml(details)}</td></tr>
              </tbody>
        </table>

        <hr style="margin:12px 0;">

        <table class="summary" style="width:100%; border-collapse:collapse; table-layout:fixed;">
          <colgroup>${colgroup}</colgroup>
          <thead>
            <tr>
            ${commission ? `<th style="text-align:left; padding:8px 10px; border-bottom:1px solid #ccc;">Commission</th>` : ''}
              <th style="text-align:left; padding:8px 10px; border-bottom:1px solid #ccc;">Net</th>
              <th style="text-align:left; padding:8px 10px; border-bottom:1px solid #ccc;">VAT</th>
              <th style="text-align:left; padding:8px 10px; border-bottom:1px solid #ccc;">Gross</th>
              <th style="text-align:left; padding:8px 10px; border-bottom:1px solid #ccc;">Method</th>
              ${cheque ? '<th style="text-align:left; padding:8px 10px; border-bottom:1px solid #ccc;">Cheque No</th>' : ''}
            </tr>
          </thead>
          <tbody>
            <tr>
             ${commission ? `<td style="padding:8px 10px;">${escapeHtml(commission)}</td>` : ''}
              <td style="padding:8px 10px;">${net}</td>
              <td style="padding:8px 10px;">${vat}</td>
              <td style="padding:8px 10px;">${gross}</td>
              <td style="padding:8px 10px;">${escapeHtml(methodTxt.replace(/#\s*\\S+/, '').trim())}</td>
              ${cheque ? `<td style="padding:8px 10px;">${escapeHtml(cheque)}</td>` : ''}
            </tr>
          </tbody>
        </table>
      </div>
    `;
    }

})();
</script>