<?php
// finance_exp_data.php

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

// Normalise inputs
$paymentType = 'Expenses';
$startStr    = trim($_REQUEST['start'] ?? date('01-m-Y'));
$endStr      = trim($_REQUEST['end']   ?? date('d-m-Y'));
$q = trim((string)($_REQUEST['q'] ?? ''));

$startTs = strtotime($startStr);
$endTs   = strtotime($endStr . ' 23:59:59');

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


$sql = "
  SELECT id, `date`, `employee`, `type`, `code`, `desc`, `totals`, `amount`, `payment_method`, `chequeNo`
  FROM `expenses`
  WHERE `payment_type` = ?
    AND `date` >= ?
    AND `date` <= ?
";

$types = 'sii';
$params = [$paymentType, $startTs, $endTs];

$term = trim((string)$q);
if ($term !== '') {
    $sql .= " AND (
" .
            "   `employee` LIKE ? OR
" .
            "   `type` LIKE ? OR
" .
            "   `desc` LIKE ? OR
" .
            "   `payment_method` LIKE ? OR
" .
            "   `chequeNo` LIKE ? OR
" .
            "   `totals` LIKE ? OR
" .
            "   CAST(`amount` 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` ASC";

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

$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()) {
    // totals stored as "net|vat"
    $tv = explode('|', $r['totals'] ?? '0|0');
    $net = (float)($tv[0] ?? 0);
    $vat = (float)($tv[1] ?? 0);
    $gross = (float)($r['amount'] ?? 0);

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

    $rows[] = [
        'id'      => (int)$r['id'],
        'date'    => date('d-m-Y', (int)$r['date']),
        'employee'   => $r['employee'],
        'type'    => $r['type'],
        //'code'    => $r['code'],
        'details' => $r['desc'],
        'net'     => $net,
        'vat'     => $vat,
        'gross'   => $gross,
        'method'  => $r['payment_method'],
        'cheque'  => $r['chequeNo'],
    ];
}
$stmt->close();

$gbp = fn($n) => '£' . number_format((float)$n, 2);
?>
<div id="expenseData">
    <div class="table-responsive">
        <table class="table table-hover align-middle table-sm">
            <thead class="table-dark">
                <tr>
                    <th style="white-space:nowrap">Date</th>
                    <th>Employee</th>
                    <th>Type</th>

                    <th>Details</th>
                    <th class="text-end">Net</th>
                    <th class="text-end">VAT</th>
                    <th class="text-end">Gross</th>
                    <th>Method</th>
                    <th class="text-center noprint">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($rows)): ?>
                <tr>
                    <td colspan="10" class="text-center py-4">No records 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['employee']) ?></td>
                    <td><?= htmlspecialchars($row['type']) ?></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>
                        <?= htmlspecialchars($row['method']) ?>
                        <?php if (strtolower((string)$row['method'])==='cheque' && !empty($row['cheque'])): ?>
                        <span class="text-muted ms-1">#<?= htmlspecialchars($row['cheque']) ?></span>
                        <?php endif; ?>
                    </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 entry">
                            <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 entry">
                            <i class="fad fa-trash"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
            <tfoot class="table-dark">
                <tr>
                    <th colspan="5" 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 colspan="2"></th>
                </tr>
            </tfoot>
        </table>
    </div>

    <div class="table-responsive">
        <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 EXPENSES</td>
                    <td><?= $gbp($tot_vat) ?></td>
                </tr>
                <tr>
                    <td>TOTAL EXCLUDING VAT</td>
                    <td><?= $gbp($tot_net) ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<script>
(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/expenses/finance_exp_edit.php' +
                '?id=' + encodeURIComponent(id) +
                '&tenant=' + encodeURIComponent(TENANT_URL);

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

                    // Date pickers inside modal
                    modal.querySelectorAll('.date-picker').forEach((el) => {
                        if (typeof mdb !== 'undefined' && mdb.Datepicker && mdb.Datepicker.getInstance(el)) return;
                        const format = el.dataset.format || 'dd-mm-yyyy';
                        if (typeof mdb !== 'undefined' && mdb.Datepicker) {
                            new mdb.Datepicker(el, {
                                confirmDateOnSelect: true,
                                format
                            });
                        }
                    });
                }
            );
        });
    });

    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 employee = safe(1);
        const type = safe(2);
        const code = safe(3);
        const details = safe(4);
        const net = safe(5);
        const vat = safe(6);
        const gross = safe(7);
        const method = 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;">employee</th><td style="padding:6px 10px;">${escapeHtml(employee)}</td></tr>
            <tr><th style="text-align:right; padding:6px 10px;">Type</th><td style="padding:6px 10px;">${escapeHtml(type)}</td></tr>
            <tr><th style="text-align:right; padding:6px 10px;">Code</th><td style="padding:6px 10px;">${escapeHtml(code)}</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>
              <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>
              <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>
    `;
    }

    // Row print -> use printContainer(contentHtml, options)
    document.querySelectorAll('#expenseData .btn-print-row').forEach(btn => {
        btn.addEventListener('click', () => {
            const tr = btn.closest('tr');
            if (!tr) return;
            const title = '<?= htmlspecialchars($paymentType) ?> 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();
            }
        });
    });

    // 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 expense?</p>'
            // Callback to execute after confirm
            const doDelete = async () => {
                try {
                    const payload = new URLSearchParams({
                        FUNCTION: 'delete_expense',
                        id: String(id),
                        tenant: TENANT_URL
                    });
                    const res = await fetch(ROOT_URL + '/includes/finance/expenses/finance_expense_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', 'Expense deleted');
                        killModal('popupBox')
                        if (window.reloadList) reloadList();
                    } else {
                        showResponse('danger', 'Delete failed: ' + (txt || 'Unknown error'));
                    }
                } catch (e) {
                    showResponse('danger', 'Network error deleting expense');
                }
            };

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