<?php
require_once __DIR__ . '/config.php';
bs_cors();
bs_ensure_data_dir();
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$orders = bs_read_json_file(BS_ORDERS_FILE, []);
if (!is_array($orders)) $orders = [];

if ($method === 'GET') {
  $id = trim((string)($_GET['id'] ?? $_GET['order_id'] ?? ''));
  if ($id !== '') {
    if (!isset($orders[$id])) bs_json(['ok'=>false,'error'=>'not found'], 404);
    bs_json(['ok'=>true,'order'=>$orders[$id]]);
  }
  $list = array_values($orders);
  usort($list, function($a,$b){ return ((int)($b['createdAt']??0)) <=> ((int)($a['createdAt']??0)); });
  bs_json(['ok'=>true,'orders'=>$list,'count'=>count($list)]);
}

if ($method !== 'POST') bs_json(['ok'=>false,'error'=>'method'], 405);
$body = json_decode(file_get_contents('php://input') ?: '{}', true) ?: [];
$action = $body['action'] ?? 'save';

if ($action === 'save' || $action === 'upsert') {
  $o = $body['order'] ?? $body;
  $id = trim((string)($o['invoiceId'] ?? $o['order_id'] ?? $body['id'] ?? ''));
  if ($id === '') bs_json(['ok'=>false,'error'=>'invoiceId required'], 400);
  $o['invoiceId'] = $id;
  if (!isset($o['createdAt'])) $o['createdAt'] = round(microtime(true)*1000);
  $o['updatedAt'] = date('c');
  $orders[$id] = isset($orders[$id]) && is_array($orders[$id]) ? array_merge($orders[$id], $o) : $o;
  bs_write_json_file(BS_ORDERS_FILE, $orders);
  bs_json(['ok'=>true,'order'=>$orders[$id]]);
}

if ($action === 'status') {
  $id = trim((string)($body['id'] ?? $body['invoiceId'] ?? $body['order_id'] ?? ''));
  $st = trim((string)($body['status'] ?? ''));
  if ($id===''||$st==='') bs_json(['ok'=>false,'error'=>'id/status required'], 400);
  if (!isset($orders[$id])) bs_json(['ok'=>false,'error'=>'not found'], 404);
  $orders[$id]['status'] = $st;
  $orders[$id]['updatedAt'] = date('c');
  if (!isset($orders[$id]['statusHistory']) || !is_array($orders[$id]['statusHistory'])) $orders[$id]['statusHistory'] = [];
  $orders[$id]['statusHistory'][] = ['status'=>$st,'at'=>round(microtime(true)*1000),'note'=>(string)($body['note']??'API'),'by'=>(string)($body['by']??'api')];
  bs_write_json_file(BS_ORDERS_FILE, $orders);
  bs_json(['ok'=>true,'order'=>$orders[$id]]);
}

bs_json(['ok'=>false,'error'=>'unknown action'], 400);
