<?php
// importxlsxmlibre.php

// 1) Carga de dependencias
require __DIR__ . '/../../vendor/autoload.php';  // Ajusta si tu estructura de carpetas es distinta
require_once 'config/db.php';                  // Asegúrate de que $conn quede disponible

use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

// 2) Solicitar al usuario la ruta del archivo XLSX
// — Formulario web para subir XLSX —
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Importar XLSX</title></head><body>';
    echo '<h1>Importar SKU desde XLSX</h1>';
    echo '<form method="POST" enctype="multipart/form-data">';
    echo '  <input type="file" name="xlsxfile" accept=".xlsx" required>';
    echo '  <button type="submit">Importar</button>';
    echo '</form></body></html>';
    exit;
}

// — Manejo del archivo subido —
if (!isset($_FILES['xlsxfile']) || $_FILES['xlsxfile']['error'] !== UPLOAD_ERR_OK) {
    die("Error al subir el archivo.\n");
}
$filepath = $_FILES['xlsxfile']['tmp_name'];


// 3) Leer la hoja "Publicaciones"
$reader = new Xlsx();
try {
    $spreadsheet = $reader->load($filepath);
} catch (\Exception $e) {
    die("Error al leer el archivo XLSX: " . $e->getMessage() . "\n");
}

$sheetName = 'Publicaciones';
if (! $spreadsheet->sheetNameExists($sheetName)) {
    die("Error: la hoja '{$sheetName}' no existe.\n");
}
$sheet = $spreadsheet->getSheetByName($sheetName);

// 4) Recorrer filas y actualizar tb_product_variants.sku
$highestRow = $sheet->getHighestRow();
$updates     = 0;

for ($row = 2; $row <= $highestRow; $row++) {
    $variantId = trim((string)$sheet->getCell("B{$row}")->getValue());
    $newSku    = trim((string)$sheet->getCell("C{$row}")->getValue());

    if ($variantId === '') {
        $newSku = 'N/R';
    }

    // Solo procesar si hay variante (o marcamos N/R)
    $stmt = $conn->prepare("
        UPDATE tb_product_variants
           SET sku = ?
         WHERE variant_id = ?
    ");
    $stmt->bind_param('ss', $newSku, $variantId);
    $stmt->execute();
    if ($stmt->error) {
        echo "[ERROR fila {$row} variant_id={$variantId}] {$stmt->error}\n";
    } else {
        echo "Fila {$row}: variant_id={$variantId} → sku='{$newSku}'\n";
        $updates++;
    }
    $stmt->close();
}

echo "\nTotal variantes procesadas: {$updates}\n";

// 5) Actualizar tb_products.sku con los primeros 9 caracteres de la SKU de variante
//    (se asume que todas las variantes de un mismo product_id generan el mismo prefijo)
$sql = "
    UPDATE tb_products p
    JOIN (
        SELECT product_id, SUBSTRING(sku,1,9) AS new_sku
          FROM tb_product_variants
         GROUP BY product_id
    ) v ON p.id = v.product_id
       SET p.sku = v.new_sku
";
$stmt = $conn->prepare($sql);
$stmt->execute();
if ($stmt->error) {
    echo "[ERROR actualizando tb_products] {$stmt->error}\n";
} else {
    echo "Se actualizaron tb_products.sku con los primeros 9 caracteres de la variante.\n";
}
$stmt->close();

// 6) Cerrar conexión
$conn->close();

echo "Importación finalizada correctamente.\n";
