<?php
// /var/www/html/oci/return.php
// Sligro OCI return handler — slaat winkelmand als JSON op en start FM-script
declare(strict_types=1);
@date_default_timezone_set('UTC');

/* ───────────── CONFIG ───────────── */
$CFG = [
  // Bestanden
  'saveDir'  => '/var/www/html/oci/carts',
  'logDir'   => '/var/www/html/logs/oci',

  // Leverancierlabel in payload
  'supplier' => 'sligro',

  // Web Viewer bridge (JS → FileMaker.PerformScript)
  'useWebViewerBridge' => true,
  'fmScriptName'       => 'Sligro_OCI_Receive',   // jouw FM-scriptnaam (bridge)

  // FileMaker Data API (server→server)
  'useDataApi' => true,
  'fmDataApi'  => [
    'host'   => 'https://fms1.seeyouresto.com',   // FMS host (zonder /databases/…)
    'user'   => 'oci_hook',                       // <<< VUL IN
    'pass'   => '********',                       // <<< VUL IN
    'script' => 'Sligro_OCI_Receive',             // FM-script dat de token verwerkt
    'dbDefault' => 'SeeYouResto_DEV',             // fallback als &db= ontbreekt
  ],

  // (optioneel) HMAC handtekening
  'requireHmac'  => false,
  'sharedSecret' => 'change-me',
];

/* ───────────── Helpers ───────────── */
function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
function ensureDirs(string $saveDir, string $logDir): void {
  foreach ([$saveDir, $logDir] as $d) if (!is_dir($d)) @mkdir($d, 0775, true);
}
function logRaw(string $logDir, string $token, string $body, array $post, array $server): void {
  $fn = rtrim($logDir,'/').'/oci-raw-'.gmdate('Ymd-His').'-'.$token.'.log';
  $hdrs = [];
  foreach ($server as $k=>$v) if (strpos($k,'HTTP_')===0) $hdrs[$k]=$v;
  @file_put_contents($fn,
    "time: ".gmdate('c')."\n".
    "ip: ".($server['REMOTE_ADDR'] ?? '')."\n".
    "method: ".($server['REQUEST_METHOD'] ?? '')."\n".
    "headers: ".print_r($hdrs,true)."\n".
    "post: ".print_r($post,true)."\n".
    "raw:\n".$body."\n"
  );
}
function jsonResponse(int $code, array $payload): void {
  http_response_code($code);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
  exit;
}
function httpJson(string $method, string $url, array $headers = [], ?string $json = null): array {
  $ch = curl_init($url);
  $h  = array_merge(['Content-Type: application/json'], $headers);
  $opts = [
    CURLOPT_CUSTOMREQUEST  => $method,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => $h,
    CURLOPT_TIMEOUT        => 20,
  ];
  if ($json !== null) $opts[CURLOPT_POSTFIELDS] = $json;
  curl_setopt_array($ch, $opts);
  $res  = curl_exec($ch);
  $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  return [$code, $res];
}

/* ───────────── (optioneel) HMAC check ───────────── */
$rawBody = file_get_contents('php://input') ?: '';
if ($CFG['requireHmac']) {
  $sig  = $_SERVER['HTTP_X_OCI_SIGNATURE'] ?? '';
  $calc = base64_encode(hash_hmac('sha256', $rawBody, $CFG['sharedSecret'], true));
  if (!hash_equals($sig, $calc)) {
    jsonResponse(401, ['error'=>'unauthorized','msg'=>'invalid signature']);
  }
}

/* ───────────── Input, dirs, logging ───────────── */
ensureDirs($CFG['saveDir'], $CFG['logDir']);

$input = $_POST;
if (empty($input) && isset($_SERVER['CONTENT_TYPE']) && stripos($_SERVER['CONTENT_TYPE'],'application/json')!==false) {
  $jsonIn = json_decode($rawBody, true);
  if (is_array($jsonIn)) $input = $jsonIn;
}

$token = $input['~ok'] ?? $input['token'] ?? ($_GET['token'] ?? '');
$state = $input['state'] ?? ($_GET['state'] ?? '');
if (!$token) $token = bin2hex(random_bytes(16));

logRaw($CFG['logDir'], $token, $rawBody, $input, $_SERVER);

/* ───────────── SAP OCI → indexeren ───────────── */
$indices = [];   // NEW_ITEM-<FIELD>[n]
foreach ($input as $k=>$v) {
  if (preg_match('/^NEW_ITEM-([A-Z_]+)\[(\d+)\]$/i', (string)$k, $m)) {
    $field = strtoupper($m[1]); $i = (int)$m[2];
    if (!isset($indices[$i])) $indices[$i] = [];
    $indices[$i][$field] = is_array($v) ? implode(" ", $v) : (string)$v;
  }
}
if (isset($input['items']) && is_array($input['items'])) {
  $i = count($indices);
  foreach ($input['items'] as $row) { $i++; $indices[$i] = array_change_key_case($row, CASE_UPPER); }
}

/* ───────────── Cart normaliseren ───────────── */
$cart = [];
foreach ($indices as $i=>$row) {
  $vend   = $row['VENDORMAT']     ?? ''; // Sligro artikelnummer (primair)
  $desc   = $row['DESCRIPTION']   ?? '';
  $qty    = (float)str_replace(',', '.', $row['QUANTITY'] ?? '0');
  $uom    = $row['UNIT']          ?? '';
  $price  = (float)str_replace(',', '.', $row['PRICE'] ?? '0');
  $curr   = $row['CURRENCY']      ?? 'EUR';
  $punit  = $row['PRICEUNIT']     ?? '';
  $branch = $row['MANUFACTCODE']  ?? '';
  $nzi    = $row['MATGROUP']      ?? '';
  $btwPct = $row['CUST_FIELD1']   ?? '';
  $custNo = $row['CUST_FIELD2']   ?? '';
  $portion= $row['CUST_FIELD3']   ?? '';
  $reqDel = $row['CUST_FIELD4']   ?? '';
  $orderId= $row['CUST_FIELD5']   ?? '';

  $longs=[]; foreach ($row as $rk=>$rv) if (preg_match('/^LONGTEXT_/i',$rk)) $longs[]=(string)$rv;
  $long = trim(implode("\n",$longs));

  $cart[] = [
    'i'                => $i,
    'sligroItemNumber' => (string)$vend,
    'description'      => $desc,
    'quantity'         => $qty,
    'uom'              => $uom,
    'price'            => $price,
    'currency'         => $curr,
    'priceUnit'        => $punit,
    'deliveryBranch'   => $branch,
    'nziCode'          => $nzi,
    'vatPercent'       => $btwPct,
    'sligroCustomerNo' => $custNo,
    'portion'          => $portion,
    'requestedDate'    => $reqDel,
    'orderReqId'       => $orderId,
    'longtext'         => $long,
  ];
}

/* ───────────── Payload opslaan ───────────── */
$headerCustomer = $cart[0]['sligroCustomerNo'] ?? ($input['CUSTOMERID'] ?? '');
$payload = [
  'token'      => $token,
  'state'      => (string)$state,
  'created'    => gmdate('c'),
  'supplier'   => $CFG['supplier'],
  'customerId' => (string)$headerCustomer,
  'cart'       => array_values($cart),
  'meta'       => [
    'ip'        => $_SERVER['REMOTE_ADDR'] ?? '',
    'userAgent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
  ],
];
$json = json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$file = rtrim($CFG['saveDir'],'/').'/'.$token.'.json';
if (@file_put_contents($file, $json) === false) {
  jsonResponse(500, ['error'=>'io_error','msg'=>'cannot write cart file','file'=>$file]);
}

/* ───────────── Data API push (db via &db=) ───────────── */
$dataApiInfo = null;
if (!empty($CFG['useDataApi'])) {
  // DB-naam uit query/body (meegegeven vanuit FM: Get ( FileName ))
  $db = $_GET['db'] ?? ($input['db'] ?? $CFG['fmDataApi']['dbDefault']);
  $db = preg_replace('/[^A-Za-z0-9_]/', '', (string)$db);       // simpele sanitatie
  if ($db === '') $db = $CFG['fmDataApi']['dbDefault'];

  // Base dynamisch
  $fmsBase = rtrim($CFG['fmDataApi']['host'],'/')
           . '/fmi/data/vLatest/databases/'
           . rawurlencode($db);

  // 1) Login
  [$c1,$r1] = httpJson('POST', $fmsBase.'/sessions',
    ['Authorization: Basic '.base64_encode($CFG['fmDataApi']['user'].':'.$CFG['fmDataApi']['pass'])],
    '{}'
  );
  $tok = @json_decode($r1,true)['response']['token'] ?? null;

  // 2) Script uitvoeren met token als parameter
  if ($tok) {
    $body = json_encode(['script.param' => $token], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    [$c2,$r2] = httpJson('POST', $fmsBase.'/scripts/'.rawurlencode($CFG['fmDataApi']['script']),
      ['Authorization: Bearer '.$tok], $body
    );
    $dataApiInfo = ['db'=>$db,'login'=>$c1,'scriptHttp'=>$c2];
    // 3) Logout (optioneel)
    httpJson('DELETE', $fmsBase.'/sessions/'.$tok, ['Authorization: Bearer '.$tok], null);
  } else {
    $dataApiInfo = ['db'=>$db,'login'=>$c1,'error'=>'no_token'];
  }
}

/* ───────────── HTML response ───────────── */
$useBridge = !empty($CFG['useWebViewerBridge']);
$script    = (string)$CFG['fmScriptName'];
$fmpUrl    = 'fmp://$/'.rawurlencode($_GET['db'] ?? $CFG['fmDataApi']['dbDefault'])
          . '?script='.rawurlencode($script).'&param='.rawurlencode($token);
$count     = count($cart);
?><!doctype html>
<html lang="nl">
<head>
  <meta charset="utf-8">
  <title>Winkelmand ontvangen</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial;margin:2rem;line-height:1.5}
    code{background:#f5f5f5;padding:.2rem .4rem;border-radius:4px}
    .btn{display:inline-block;padding:.6rem 1rem;border:1px solid #ccc;border-radius:8px;text-decoration:none}
    .muted{color:#666}
  </style>
</head>
<body>
  <h1>Winkelmand ontvangen</h1>
  <p>We hebben <strong><?php echo (int)$count ?></strong> artikel(en) opgeslagen.</p>
  <p>Token: <code><?php echo h($token) ?></code></p>

  <?php if ($useBridge): ?>
  <p class="muted">Als je dit in een FileMaker Web Viewer bekijkt, wordt het script automatisch gestart.</p>
  <script>
  (function(){
    var token  = "<?php echo h($token) ?>";
    var script = "<?php echo h($script) ?>";
    try {
      if (window.FileMaker && typeof window.FileMaker.PerformScript === 'function') {
        window.FileMaker.PerformScript(script, token);
      }
    } catch(e) {}
  })();
  </script>
  <?php endif; ?>

  <p><a class="btn" href="<?php echo h($fmpUrl) ?>">Terug naar SeeYouResto</a></p>

  <?php if ($dataApiInfo !== null): ?>
  <p class="muted">Data API → DB: <?php echo h($dataApiInfo['db']) ?> (login HTTP <?php echo h($dataApiInfo['login']) ?>, script HTTP <?php echo h($dataApiInfo['scriptHttp']) ?>)</p>
  <?php endif; ?>
</body>
</html>
