<?php
declare(strict_types=1);

function golder_tax_decimal(float|int|string|null $value, float $default = 0.0): float
{
    if ($value === null) {
        return $default;
    }
    $normalized = str_replace(',', '.', trim((string)$value));
    if ($normalized === '') {
        return $default;
    }
    return is_numeric($normalized) ? (float)$normalized : $default;
}

function golder_tax_money(float $value): float
{
    return round($value, 2);
}

function golder_fetch_active_taxes_by_ids(PDO $db, string $profileId, array $selectedTaxIds): array
{
    $idList = [];
    foreach ($selectedTaxIds as $rawId) {
        $taxId = trim((string)$rawId);
        if ($taxId !== '') {
            $idList[$taxId] = true;
        }
    }
    $idList = array_keys($idList);
    if (!$idList) {
        return [];
    }

    $placeholders = implode(',', array_fill(0, count($idList), '?'));
    $params = array_merge([$profileId], $idList);
    $st = $db->prepare(
        "SELECT id, name, rate, type, active
         FROM taxes
         WHERE profile_id = ?
           AND id IN ({$placeholders})
           AND active = 1
         ORDER BY name ASC"
    );
    $st->execute($params);

    $rows = [];
    foreach ($st->fetchAll() ?: [] as $row) {
        $taxId = trim((string)($row['id'] ?? ''));
        $taxName = trim((string)($row['name'] ?? ''));
        if ($taxId === '' || $taxName === '') {
            continue;
        }
        $taxType = strtolower(trim((string)($row['type'] ?? 'percent')));
        if (!in_array($taxType, ['percent', 'fixed'], true)) {
            $taxType = 'percent';
        }
        $rows[] = [
            'id' => $taxId,
            'name' => $taxName,
            'rate' => golder_tax_decimal($row['rate'] ?? 0),
            'type' => $taxType,
        ];
    }

    return $rows;
}

function golder_compute_tax_snapshot(
    array $items,
    string $currency,
    array $selectedTaxes,
    string $customerName = '',
    string $note = '',
    bool $applyTaxes = true
): array {
    $cleanCurrency = strtoupper(trim($currency));
    if ($cleanCurrency === '') {
        $cleanCurrency = 'TRY';
    }

    $lines = [];
    $subtotal = 0.0;
    foreach ($items as $item) {
        if (!is_array($item)) {
            continue;
        }
        $qty = golder_tax_decimal($item['qty'] ?? 0);
        $unitPrice = golder_tax_decimal($item['unit_price'] ?? 0);
        $lineSubtotal = golder_tax_money(max(0.0, $qty * $unitPrice));
        $subtotal += $lineSubtotal;
        $lines[] = [
            'name' => trim((string)($item['name'] ?? '')),
            'qty' => $qty,
            'unit_price' => golder_tax_money($unitPrice),
            'line_subtotal' => $lineSubtotal,
        ];
    }
    $subtotal = golder_tax_money($subtotal);

    if (!$applyTaxes) {
        $selectedTaxes = [];
    }

    $percentTaxes = [];
    $fixedTaxes = [];
    foreach ($selectedTaxes as $tax) {
        if (!is_array($tax)) {
            continue;
        }
        $type = strtolower(trim((string)($tax['type'] ?? 'percent')));
        if ($type === 'fixed') {
            $fixedTaxes[] = $tax;
        } else {
            $percentTaxes[] = $tax;
        }
    }

    $percentTotals = [];
    foreach ($percentTaxes as $tax) {
        $percentTotals[trim((string)($tax['id'] ?? ''))] = 0.0;
    }

    $percentTaxTotal = 0.0;
    foreach ($lines as &$line) {
        $lineSubtotal = golder_tax_decimal($line['line_subtotal'] ?? 0);
        $lineTaxTotal = 0.0;
        $lineItems = [];
        foreach ($percentTaxes as $tax) {
            $taxId = trim((string)($tax['id'] ?? ''));
            if ($taxId === '') {
                continue;
            }
            $rate = max(0.0, golder_tax_decimal($tax['rate'] ?? 0));
            $amount = golder_tax_money(($lineSubtotal * $rate) / 100.0);
            $percentTotals[$taxId] = golder_tax_money(($percentTotals[$taxId] ?? 0.0) + $amount);
            $lineTaxTotal += $amount;
            if ($amount > 0) {
                $lineItems[] = ['tax_id' => $taxId, 'amount' => $amount];
            }
        }
        $lineTaxTotal = golder_tax_money($lineTaxTotal);
        $percentTaxTotal += $lineTaxTotal;
        $line['line_tax_total'] = $lineTaxTotal;
        $line['line_total'] = golder_tax_money($lineSubtotal + $lineTaxTotal);
        $line['tax_items'] = $lineItems;
    }
    unset($line);

    $fixedTaxTotal = 0.0;
    $fixedItems = [];
    $taxes = [];
    foreach ($fixedTaxes as $tax) {
        $taxId = trim((string)($tax['id'] ?? ''));
        $taxName = trim((string)($tax['name'] ?? ''));
        if ($taxId === '' || $taxName === '') {
            continue;
        }
        $amount = golder_tax_money(max(0.0, golder_tax_decimal($tax['rate'] ?? 0)));
        $fixedTaxTotal += $amount;
        $fixedItems[] = ['tax_id' => $taxId, 'amount' => $amount];
        $taxes[] = [
            'tax_id' => $taxId,
            'name' => $taxName,
            'type' => 'fixed',
            'rate' => golder_tax_decimal($tax['rate'] ?? 0),
            'amount' => $amount,
        ];
    }

    foreach ($percentTaxes as $tax) {
        $taxId = trim((string)($tax['id'] ?? ''));
        $taxName = trim((string)($tax['name'] ?? ''));
        if ($taxId === '' || $taxName === '') {
            continue;
        }
        $taxes[] = [
            'tax_id' => $taxId,
            'name' => $taxName,
            'type' => 'percent',
            'rate' => golder_tax_decimal($tax['rate'] ?? 0),
            'amount' => golder_tax_money($percentTotals[$taxId] ?? 0.0),
        ];
    }

    $taxTotal = golder_tax_money($percentTaxTotal + $fixedTaxTotal);
    return [
        'version' => 2,
        'apply_taxes' => $applyTaxes && !empty($selectedTaxes),
        'currency' => $cleanCurrency,
        'customer_name' => trim($customerName),
        'note' => trim($note),
        'subtotal' => $subtotal,
        'tax_total' => $taxTotal,
        'grand_total' => golder_tax_money($subtotal + $taxTotal),
        'applied_taxes_summary' => implode(', ', array_values(array_filter(array_map(static fn($tax) => trim((string)($tax['name'] ?? '')), $selectedTaxes)))),
        'taxes' => $taxes,
        'fixed_items' => $fixedItems,
        'lines' => $lines,
    ];
}


