<?php
// finance_commission_data.php

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

$startStr = trim($_REQUEST['start'] ?? '');
$endStr   = trim($_REQUEST['end'] ?? '');

$startTs = null;
$endTs   = null;

if ($startStr !== '') {
    $dt = DateTime::createFromFormat('d-m-Y', $startStr);
    if ($dt instanceof DateTime) $startTs = $dt->getTimestamp();
}
if ($endStr !== '') {
    $dt = DateTime::createFromFormat('d-m-Y', $endStr);
    if ($dt instanceof DateTime) {
        $dt->setTime(23, 59, 59);
        $endTs = $dt->getTimestamp();
    }
}
if (!$startTs || !$endTs) {
    echo '<div class="alert alert-warning">Invalid date range supplied.</div>';
    return;
}

// Payee filter
$payeeRaw = trim($_REQUEST['payee'] ?? '');
$payeeType = '';
$payeeId = 0;

if ($payeeRaw !== '') {
    $parts = explode('|', $payeeRaw, 2);
    if (count($parts) === 2) {
        $payeeType = strtolower(trim($parts[0]));
        $payeeId   = (int)trim($parts[1]);
        if (!in_array($payeeType, ['agent', 'broker'], true)) {
            $payeeType = '';
            $payeeId = 0;
        }
    }
}

$whereExtra = '';
$bindTypes = 'ii';
$bindVals = [$startTs, $endTs];

if ($payeeType === 'agent' && $payeeId > 0) {
    $whereExtra = " AND `agent` = ? ";
    $bindTypes .= 'i';
    $bindVals[] = $payeeId;
} elseif ($payeeType === 'broker' && $payeeId > 0) {
    $whereExtra = " AND `broker` = ? ";
    $bindTypes .= 'i';
    $bindVals[] = $payeeId;
}

$sql = "
    SELECT *
    FROM `invoices`
    WHERE `status` = '3'
      AND `commission` != ''
      AND `date_paid` >= ?
      AND `date_paid` <= ?
      $whereExtra
    ORDER BY ABS(`date_paid`) DESC
";

$stmt = $GLOBALS['con']->prepare($sql);
if (!$stmt) {
    echo '<div class="alert alert-danger">Database error preparing commission query.</div>';
    return;
}

// Bind params safely (dynamic)
$stmt->bind_param($bindTypes, ...$bindVals);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();

$num = $result ? $result->num_rows : 0;
if ($num === 0) {
    echo '<div class="alert alert-warning">No commission data within the selected filters.</div>';
    return;
}

function commissionPayeeLabel(array $invRow): string {
    $agent  = isset($invRow['agent']) ? (int)$invRow['agent'] : 0;
    $broker = isset($invRow['broker']) ? (int)$invRow['broker'] : 0;

    if ($agent !== 0)  return 'Agent: '  . (string)getAgentName($agent);
    if ($broker !== 0) return 'Broker: ' . (string)getBrokerName($broker);
    return '';
}

$ct = 0.0;
?>
<div id="repdata">
    <p id="exportTitle" class="lead reportHeader">
        Commission report for the period
        <strong><?= htmlspecialchars(date('d-m-Y', $startTs), ENT_QUOTES) ?></strong>
        to
        <strong><?= htmlspecialchars(date('d-m-Y', $endTs), ENT_QUOTES) ?></strong>
    </p>

    <div class="table-responsive">
        <table id="commissionrep" class="table table-sm table-striped align-middle">
            <thead class="table-dark">
                <tr>
                    <th>Invoice</th>
                    <th>Date paid</th>
                    <th>Client</th>
                    <th>Agent/Broker</th>
                    <th>Commission</th>

                </tr>
            </thead>
            <tbody>
                <?php while ($d = $result->fetch_assoc()) {
                $commission = (float)$d['commission'];
                $ct += $commission;
            ?>
                <tr>
                    <td><?= sprintf('%06d', (int)$d['invNo']) ?></td>
                    <td><?= htmlspecialchars(date('d-m-Y', (int)$d['date_paid']), ENT_QUOTES) ?></td>
                    <td><?= htmlspecialchars(getClientName((int)$d['client']), ENT_QUOTES) ?></td>
                    <td><?= htmlspecialchars(commissionPayeeLabel($d), ENT_QUOTES) ?></td>
                    <td>&pound;<?= number_format($commission, 2) ?></td>

                </tr>
                <?php } ?>
            </tbody>
            <tfoot class="table-dark">
                <tr>
                    <th colspan="4" class="text-end">Total:</th>
                    <th>&pound;<?= number_format($ct, 2) ?></th>

                </tr>
            </tfoot>
        </table>
    </div>
</div>