<?php
require_once __DIR__ . '/../config/db_remote.php';

$mode = $_GET['mode'] ?? '';

if ($mode === 'json_last30') {
  header('Content-Type: application/json');

  $rows = [];
  $res = $mysqli->query("
    SELECT bs.*, cc.SKU, cc.grower
    FROM barcode_scans bs
    LEFT JOIN casecodes cc ON cc.serial = bs.code
    WHERE bs.scanned_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ORDER BY bs.id DESC
    LIMIT 50000
  ");
  while ($r = $res->fetch_assoc()) $rows[] = $r;

  echo json_encode(['rows' => $rows]);
  exit;
}

if ($mode === 'xlsx_today') {
  // Simple XLSX via CSV (Excel opens it)
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=production_today.csv');

  $out = fopen('php://output', 'w');
  fputcsv($out, ['id','code','source','scan_function','scanned_at','SKU','grower']);

  $res = $mysqli->query("
    SELECT bs.id, bs.code, bs.source, bs.scan_function, bs.scanned_at, cc.SKU, cc.grower
    FROM barcode_scans bs
    LEFT JOIN casecodes cc ON cc.serial = bs.code
    WHERE DATE(bs.scanned_at) = CURDATE()
    ORDER BY bs.id DESC
    LIMIT 50000
  ");
  while ($r = $res->fetch_assoc()) {
    fputcsv($out, $r);
  }
  fclose($out);
  exit;
}

http_response_code(400);
echo "Invalid mode";
