<?php
// includes/finance/tools/export_receipts.php

// Config include pattern (per your standard)
if (file_exists('../../../../' . ($_REQUEST['tenant'] ?? '') . '/config.php')) {
    require_once('../../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    http_response_code(500);
    echo 'Database connection not available.';
    exit;
}

$preset   = strtolower(trim((string)($_REQUEST['preset'] ?? 'generic')));
$startStr = trim((string)($_REQUEST['start'] ?? ''));
$endStr   = trim((string)($_REQUEST['end'] ?? ''));

function parseDMYToUnixStart(string $dmy): ?int {
    $dmy = trim($dmy);
    if ($dmy === '') return null;
    $dmy = str_replace('/', '-', $dmy);
    if (!preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/', $dmy, $m)) return null;
    $d = (int)$m[1]; $mo = (int)$m[2]; $y = (int)$m[3];
    return strtotime(sprintf('%04d-%02d-%02d 00:00:00', $y, $mo, $d));
}
function parseDMYToUnixEnd(string $dmy): ?int {
    $dmy = trim($dmy);
    if ($dmy === '') return null;
    $dmy = str_replace('/', '-', $dmy);
    if (!preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/', $dmy, $m)) return null;
    $d = (int)$m[1]; $mo = (int)$m[2]; $y = (int)$m[3];
    return strtotime(sprintf('%04d-%02d-%02d 23:59:59', $y, $mo, $d));
}

function csv_cell(string $s): string {
    $s = str_replace(["\r\n", "\n", "\r"], ' ', $s);
    $s = trim($s);
    if ($s === '') return '';
    if (strpbrk($s, ",\"\n\r") !== false) {
        $s = '"' . str_replace('"', '""', $s) . '"';
    }
    return $s;
}

function normaliseInvoiceField(string $invoiceRaw): string {
    $invoiceRaw = trim($invoiceRaw);
    if ($invoiceRaw === '') return '';
    // split on commas/whitespace/pipe; keep non-numeric tokens as-is
    $parts = preg_split('/[,\s|]+/', $invoiceRaw, -1, PREG_SPLIT_NO_EMPTY);
    if (!$parts) return $invoiceRaw;

    $out = [];
    foreach ($parts as $p) {
        $p = trim($p);
        if ($p === '') continue;
        if (ctype_digit($p)) {
            $out[] = str_pad($p, 6, '0', STR_PAD_LEFT);
        } else {
            $out[] = $p;
        }
    }
    return implode(',', $out);
}

function ymd(string $dmy): string {
    // Expect dd-mm-yyyy; if not, return raw
    $dmy = trim($dmy);
    if (!preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/', $dmy, $m)) return $dmy;
    return sprintf('%04d-%02d-%02d', (int)$m[3], (int)$m[2], (int)$m[1]);
}

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

$start = parseDMYToUnixStart($startStr) ?? $firstOfMonth;
$end   = parseDMYToUnixEnd($endStr) ?? ( $now < $lastOfMonth ? strtotime(date('Y-m-d 23:59:59', $now)) : $lastOfMonth );

// Fetch
$sql = "
  SELECT `id`,`registered`,`pType`,`payee`,`details`,`vat`,`totals`,`commission`,
         `method`,`invoice`,`chequeNo`,`date`
  FROM `receipts`
  WHERE `date` BETWEEN ? AND ?
  ORDER BY `date` ASC, `id` ASC
";
$stmt = $GLOBALS['con']->prepare($sql);
$stmt->bind_param('ii', $start, $end);
$stmt->execute();
$res = $stmt->get_result();

// Output headers
$fnRange = date('Ymd', $start) . '-' . date('Ymd', $end);
$filename = "receipts_export_{$fnRange}_{$preset}.csv";

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');

// UTF-8 BOM for Excel compatibility
echo "\xEF\xBB\xBF";

$allowed = ['generic','xero_bank','sage_bank'];
if (!in_array($preset, $allowed, true)) $preset = 'generic';

// Headers per preset
if ($preset === 'generic') {
    echo "Date,Type,Contact,Reference,Description,Net,VAT,Gross,Method,InvoiceNumber\n";
} else {
    // bank-style
    echo "Date,Amount,Payee,Reference,Description\n";
}

// Rows
while ($r = $res->fetch_assoc()) {
    $dateUnix = (int)$r['date'];
    $dmy = date('d-m-Y', $dateUnix);

    $totals = (string)($r['totals'] ?? '');
    $parts = explode('|', $totals);
    $net = (float)str_replace(',', '', (string)($parts[0] ?? '0'));
    $vat = (float)str_replace(',', '', (string)($parts[1] ?? '0'));
    $gross = $net + $vat;

    $payee = (string)($r['payee'] ?? '');
    $details = (string)($r['details'] ?? '');
    $method = (string)($r['method'] ?? '');
    $ref = 'RCP-' . (string)($r['id'] ?? '');
    $inv = normaliseInvoiceField((string)($r['invoice'] ?? ''));

    if ($preset === 'generic') {
        $line = [
            ymd($dmy),
            'Receipt',
            $payee,
            $ref,
            $details,
            number_format($net, 2, '.', ''),
            number_format($vat, 2, '.', ''),
            number_format($gross, 2, '.', ''),
            $method,
            $inv
        ];
        echo implode(',', array_map('csv_cell', $line)) . "\n";
    } else {
        // Xero/Sage bank statement: Amount positive for receipts
        $line = [
            ymd($dmy),
            number_format($gross, 2, '.', ''),
            $payee,
            ($inv !== '' ? $inv : $ref),
            $details
        ];
        echo implode(',', array_map('csv_cell', $line)) . "\n";
    }
}

$stmt->close();
exit;
