<?php
define('_FEXEC', 1);
require('includes/application_top.php');

if ($_SESSION['customer_country_id'] != 999) {
    exit;
}

if (empty($_POST['data'])) {
    exit;
}

// Read payload from form-encoded 'data' or raw JSON
$raw = $_POST['data'] ?? file_get_contents('php://input');
$payload = json_decode($raw, true);

if (!$payload) { echo "OK"; exit; } // be lenient; front-end may expect plain OK
$items = [];
if (!empty($payload['coords']) && is_array($payload['coords'])) {
  $items = $payload['coords'];
} elseif (isset($payload[0]) && is_array($payload[0])) {
  // sometimes client sends a bare array
  $items = $payload;
} else {
  echo "OK"; exit;
}

foreach ($items as $item) {
  // --- Parse id
  $rawId   = isset($item['id']) ? (string)$item['id'] : '';
  $prod_id = (int)preg_replace('/\D+/', '', $rawId);
  if ($prod_id <= 0) { continue; }

  // --- Position (editor CSS px, top-left box)
  $left = isset($item['coordLeft'])  ? (float)$item['coordLeft']  : 0.0;
  $top  = isset($item['coordTop'])   ? (float)$item['coordTop']   : 0.0;

  // --- Size from client (may be missing for some items)
  $w_px = isset($item['coordWidth'])  ? (float)$item['coordWidth']  : 0.0;
  $h_px = isset($item['coordHeight']) ? (float)$item['coordHeight'] : 0.0;

  // --- Fallback to DB if needed
  if ($w_px <= 0.0 || $h_px <= 0.0) {
    $q = tep_db_query("SELECT products_w, products_h FROM products WHERE products_id=".(int)$prod_id." LIMIT 1");
    if ($row = tep_db_fetch_array($q)) {
      if ($w_px <= 0.0) $w_px = (float)$row['products_w'];
      if ($h_px <= 0.0) $h_px = (float)$row['products_h'];
    }
  }

  // --- Last-resort safe defaults (editor canvas defaults)
  if ($w_px <= 0.0) $w_px = 44.0;
  if ($h_px <= 0.0) $h_px = 36.0;

  // --- SAVE BOTTOM-CENTER ANCHOR (matches renderer/editor math)
  // Ax = left + width/2,  Ay = top + height
  $x_save = (int)round($left + ($w_px / 2.0));
  $y_save = (int)round($top  +  $h_px);

  $sets = [
    "products_x = " . $x_save,
    "products_y = " . $y_save,
  ];

  // Only persist size if client actually sent a positive size (don’t clobber DB with 0)
  if (isset($item['coordWidth'])  && (float)$item['coordWidth']  > 0) $sets[] = "products_w = " . (int)round($w_px);
  if (isset($item['coordHeight']) && (float)$item['coordHeight'] > 0) $sets[] = "products_h = " . (int)round($h_px);

  $sql = "UPDATE products SET " . implode(", ", $sets) . " WHERE products_id = " . (int)$prod_id . " LIMIT 1";
  tep_db_query($sql);
}

echo "OK";


