<?php
// api/marca_sync.php — Copia nuevas marcas tb_datadai.marca -> tb_inv_marca
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

session_start();
require_once __DIR__ . '/../conex.php';
mysqli_set_charset($conn,'utf8mb4');

/* Cambia el destino aquí si usas otra tabla: */
$DESTINO = 'tb_inv_marca';
$ORIGEN  = 'tb_datadai';

try {
  mysqli_begin_transaction($conn);

  $sql = "
    INSERT INTO {$DESTINO} (nombre, condicion)
    SELECT DISTINCT TRIM(marca) AS nombre, 1
    FROM {$ORIGEN}
    WHERE TRIM(marca) <> ''
      AND NOT EXISTS (
        SELECT 1 FROM {$DESTINO} t
        WHERE t.nombre = TRIM({$ORIGEN}.marca)
      )
  ";
  $ok = mysqli_query($conn, $sql);
  if ($ok === false) throw new Exception('Error al sincronizar: '.mysqli_error($conn));

  $insertados = mysqli_affected_rows($conn);
  mysqli_commit($conn);

  echo json_encode(['success'=>true,'message'=>'Sincronización completada','inserted'=>$insertados]);
} catch (Throwable $e) {
  mysqli_rollback($conn);
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
