<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

function fail($msg){ http_response_code(400); echo json_encode(['ok'=>false,'error'=>$msg]); exit; }
function clean_filename($s){ return preg_replace('/[^A-Za-z0-9_\-]/', '_', $s); }

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) fail('Geen geldige JSON ontvang nie.');

$base = __DIR__ . '/data';
$sigDir = __DIR__ . '/signatures';
if (!is_dir($base)) mkdir($base, 0755, true);
if (!is_dir($sigDir)) mkdir($sigDir, 0755, true);
$visitsFile = $base . '/visits.json';
if (!file_exists($visitsFile)) file_put_contents($visitsFile, '[]', LOCK_EX);

$policy = trim($data['policy_nr'] ?? '');
$type = trim($data['type'] ?? 'visit'); // visit / outside_area / not_home
if ($policy === '') fail('Polisnommer ontbreek.');

$now = date('Y-m-d H:i:s');
$id = date('YmdHis') . '_' . clean_filename($policy) . '_' . substr(md5(random_bytes(8)),0,6);

$clientSigPath = '';
$agentSigPath = '';

foreach ([['client_signature','client'], ['agent_signature','agent']] as $pair) {
  $field = $pair[0]; $label = $pair[1];
  if (!empty($data[$field]) && preg_match('/^data:image\/png;base64,/', $data[$field])) {
    $img = substr($data[$field], strpos($data[$field], ',') + 1);
    $bin = base64_decode($img);
    if ($bin !== false) {
      $fileName = $id . '_' . $label . '.png';
      file_put_contents($sigDir . '/' . $fileName, $bin, LOCK_EX);
      if ($label === 'client') $clientSigPath = 'signatures/' . $fileName;
      if ($label === 'agent') $agentSigPath = 'signatures/' . $fileName;
    }
  }
}

$record = [
  'id' => $id,
  'type' => $type,
  'policy_nr' => $policy,
  'client_name' => trim($data['client_name'] ?? ''),
  'tel' => trim($data['tel'] ?? ''),
  'adres' => trim($data['adres'] ?? ''),
  'office' => trim($data['office'] ?? ''),
  'agent' => trim($data['agent'] ?? 'Heinrich Booysen'),
  'visit_date' => date('Y-m-d'),
  'start_time' => trim($data['start_time'] ?? ''),
  'submit_time' => $now,
  'status' => trim($data['status'] ?? ''),
  'notes' => trim($data['notes'] ?? ''),
  'client_signed' => $clientSigPath !== '',
  'agent_signed' => $agentSigPath !== '',
  'client_signature' => $clientSigPath,
  'agent_signature' => $agentSigPath,
  'created_at' => $now
];

$fp = fopen($visitsFile, 'c+');
if (!$fp) fail('Kan visits.json nie oopmaak nie.');
flock($fp, LOCK_EX);
$contents = stream_get_contents($fp);
$visits = json_decode($contents ?: '[]', true);
if (!is_array($visits)) $visits = [];
$visits[] = $record;
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, json_encode($visits, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
fflush($fp);
flock($fp, LOCK_UN);
fclose($fp);

echo json_encode(['ok'=>true, 'record'=>$record], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
