<?php
// api/log-receipt.php — saves a UTF-8 .txt receipt into /Logs (one per transfer)
header('Content-Type: application/json; charset=utf-8');

// Directory to write logs
$logsDir = __DIR__ . '/../Logs';
if (!is_dir($logsDir)) {
  mkdir($logsDir, 0755, true);
}

// Read raw body (JSON preferred)
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) {
  parse_str($raw, $data);
  if (!is_array($data)) $data = [];
}

// Build lines (Hebrew keys)
$ref       = preg_replace('/[^0-9]/', '', $data['ref'] ?? '');
$timestamp = $data['timestamp'] ?? '';

$lines = [];
$add = function($k,$v) use (&$lines){ $lines[] = $k . ': ' . (string)$v; };

$add('אסמכתא',           $ref);
$add('תאריך ושעה',       $timestamp);
$add('סכום',             $data['amount']    ?? '');
$add('שם המעביר',        $data['payer']     ?? '');
$add('שם מוטב',          $data['payee']     ?? '');
$add('בנק',              $data['bank']      ?? '');
$add('סניף',             $data['branch']    ?? '');
$add('מספר חשבון',       $data['account']   ?? '');
$add('מטרת העברה',       $data['purpose']   ?? '');
$add('יום ערך',          $data['value_date']?? '');

// Filename like 2025-10-29_12-34-56_123456.txt
$fname = date('Y-m-d_H-i-s') . '_' . ($ref ?: uniqid('ref_')) . '.txt';
file_put_contents($logsDir . '/' . $fname, implode(PHP_EOL, $lines) . PHP_EOL, LOCK_EX);

echo json_encode(['ok' => true]);
