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

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'] ?? ''));
$paymentType = trim((string)($_REQUEST['payment_type'] ?? 'Outgoings')); // keep flexible

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;
    return strtotime(sprintf('%04d-%02d-%02d 00:00:00', (int)$m[3], (int)$m[2], (int)$m[1]));
}
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;
    return strtotime(sprintf('%04d-%02d-%02d 23:59:59', (int)$m[3], (int)$m[2], (int)$m[1]));
}

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 '';
    $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 {
    $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]);
}

// Defaults like your data page: current month-to-date
$now = time();
$firstOfMonth = strtotime(date('Y-m-01 00:00:00', $now));
$start = parseDMYToUnixStart($startStr) ?? $firstOfMonth;
$end   = parseDMYToUnixEnd($endStr) ?? strtotime(date('Y-m-d 23:59:59', $now));

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

$stmt = $GLOBALS['con']->prepare($sql);
$stmt->bind_param('sii', $paymentType, $start, $end);
$stmt->execute();
$res = $stmt->get_result();

$fnRange = date('Ymd', $start) . '-' . date('Ymd', $end);
$filename = "outgoings_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');

echo "\xEF\xBB\xBF";

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

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

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

    // totals stored as "net|vat"; gross is amount
    $tv = explode('|', (string)($r['totals'] ?? '0|0'));
    $net = (float)str_replace(',', '', (string)($tv[0] ?? '0'));
    $vat = (float)str_replace(',', '', (string)($tv[1] ?? '0'));
    $gross = (float)str_replace(',', '', (string)($r['amount'] ?? '0'));

    $payee = (string)($r['payee'] ?? '');
    $cat   = (string)($r['type'] ?? '');
    $code  = (string)($r['code'] ?? '');
    $desc  = (string)($r['desc'] ?? '');
    $method = (string)($r['payment_method'] ?? '');
    $ref = 'EXP-' . (string)($r['id'] ?? '');

    // If your outgoings link invoices elsewhere, you can pass invoice via a join later.
    // For now: store blank (or use code if you want).
    $invoice = '';

    if ($preset === 'generic') {
        $line = [
            ymd($dmy),
            $paymentType,
            $payee,
            $ref,
            $desc,
            number_format($net, 2, '.', ''),
            number_format($vat, 2, '.', ''),
            number_format($gross, 2, '.', ''),
            $method,
            normaliseInvoiceField($invoice),
            $code,
            $cat
        ];
        echo implode(',', array_map('csv_cell', $line)) . "\n";
    } else {
        // bank statement: outgoings are negative
        $amount = 0 - abs($gross);
        $line = [
            ymd($dmy),
            number_format($amount, 2, '.', ''),
            $payee,
            $ref,
            $desc
        ];
        echo implode(',', array_map('csv_cell', $line)) . "\n";
    }
}

$stmt->close();
exit;
