<?php
ini_set('memory_limit', '512M');

// CONFIGURACIÓN
$ck = 'ck_e053c8194efa9500c5105b97a0d95f3f24845dd9';
$cs = 'cs_68da475989d53a2651d57fcf4d2b40d8ba7cfe22';
$woocommerce_base_url = 'https://sucasaconectada.com/wp-json/wc/v3/products';
$baseUrl = "https://www.securitydoctorscr.com/products.json?page=";
$json_url = __DIR__ . '/products.json';
$old_json_url = __DIR__ . '/products_old.json';
$email = 'info@sucasaconectada.com';
$tasa_dolar = obtenerTipoCambio();


//PASO importar Json 

if (file_exists($json_url)) {
    unlink($json_url);
    echo "🗑️ Archivo $json_url eliminado.\n";
}

$allProducts = [];
$page = 1;
 echo "🔍 Consultando página ";

while (true) {
    $url = $baseUrl . $page;
    echo "$page, ";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' .
        '(KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        echo "❌ Error HTTP $httpCode en página $page. Se detiene.<br>";
        break;
    }

    $data = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "❌ Error de JSON en página $page: " . json_last_error_msg() . "<br>";
        break;
    }

    if (empty($data['products'])) {
        echo "Descarga completa.<br>";
        break;
    }

    $allProducts = array_merge($allProducts, $data['products']);
    $page++;
}

file_put_contents($json_url, json_encode(['products' => $allProducts], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
echo "✅ Se guardaron " . count($allProducts) . " productos en $json_url<br>";


// PASO : Obtener productos de WooCommerce
$current_products = wc_get_all_products();

echo "<b>Total producto en SuCasa ".count($current_products)."</b><br>";
$product_index_by_shopify_id = [];
foreach ($current_products as $prod) {
    foreach ($prod['meta_data'] as $meta) {
        if ($meta['key'] === 'product_id') {
            $product_index_by_shopify_id[(string)$meta['value']] = $prod;
        }
    }
    echo "• <b>{$prod['name']}</b> (product_id: {$product_id_meta})<br>";
}

$data = $data['products'];
echo "<br><br><b>Total productos en JSON: " . count($data) . "</b><br>";

// PASO : Comparar productos
$old_json = file_exists($old_json_url) ? json_decode(file_get_contents($old_json_url), true) : [];
$old_ids = array_column($old_json, 'id');
$data = json_decode(file_get_contents($json_url), true);
$data = $data['products'];

$nuevos = [];
$actualizados = [];
$ids_json = [];

foreach ($data as $item) {
    $shopify_id = (string)$item['id'];
    $ids_json[] = $shopify_id;

    $precio_colones = ceil($item['variants'][0]['price'] * $tasa_dolar * 1.10)+3500;
    $precio_colones = ceil($precio_colones / 500) * 500;
    $title = $item['title'];
    $slug = slugify($title);
    $descripcion = $item['body_html'];

    $prod = null;

    // 1. Buscar por product_id
    if (isset($product_index_by_shopify_id[$shopify_id])) {
        $prod = $product_index_by_shopify_id[$shopify_id];
    } else {
        // 2. Buscar por título si no hay coincidencia por ID
        foreach ($current_products as $p) {
            if (strcasecmp(trim($p['name']), trim($title)) === 0) {
                $prod = $p;
                break;
            }
        }
    }

    if ($prod) {
        echo "• Actualizando <b>{$title}</b> a <b>{$precio_colones}</b><br>";
        $product_id = $prod['id'];
        $data_update = [
            'name' => $title,
            'slug' => $slug,
            'regular_price' => (string)$precio_colones,
            'description' => $descripcion,
            'categories' => $prod['categories'],
        ];

        $imagenes = [];
        if (!empty($item['images'])) {
            foreach ($item['images'] as $img) {
                if (!empty($img['src'])) {
                    $imagenes[] = ['src' => $img['src']];
                }
            }
        }

        if (!empty($imagenes)) {
            $data_update['images'] = $imagenes;
        }

        $ch = curl_init("{$woocommerce_base_url}/$product_id?consumer_key=$ck&consumer_secret=$cs");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data_update));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_exec($ch);
        curl_close($ch);

        $actualizados[] = $title;
    }

    if (!in_array($item['id'], $old_ids)) {
        $nuevos[] = $title;
    }
}

// PASO 3: Eliminar productos que ya no están
$eliminados = [];
foreach ($product_index_by_shopify_id as $shopify_id => $prod) {
    if (!in_array($shopify_id, $ids_json)) {
        $ch = curl_init("{$woocommerce_base_url}/{$prod['id']}?consumer_key=$ck&consumer_secret=$cs&force=true");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_exec($ch);
        curl_close($ch);
        $eliminados[] = $prod['name'];
    }
}

// PASO 4: Enviar correos
if (!empty($nuevos)) {
    enviarCorreo("📦 Productos NUEVOS (solo notificación)", $nuevos);
}

if (!empty($actualizados)) {
    enviarCorreo("✅ Productos ACTUALIZADOS", $actualizados);
}

if (!empty($eliminados)) {
    enviarCorreo("🗑 Productos ELIMINADOS", $eliminados);
}

// PASO 5: Actualizar JSON
@unlink($old_json_url);
rename($json_url, $old_json_url);


echo "<br><br><b>Fin</b>";

function slugify($text) {
    $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
    $text = preg_replace('/[^a-zA-Z0-9\/\_|+ -]/', '', $text);
    $text = strtolower(trim($text, '-'));
    $text = preg_replace('/[\/\_|+ -]+/', '-', $text);
    return $text;
}

function enviarCorreo($asunto, $contenido) {
    global $email;
    if (!empty($contenido)) {
        mail($email, $asunto, implode("<br>", $contenido));
    }
}

function obtenerTipoCambio() {
    $url = "https://open.er-api.com/v6/latest/USD";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    if (isset($data['result']) && $data['result'] === 'success') {
        return floatval($data['rates']['CRC']);
    }
    return null;
}

function wc_get_all_products() {
    global $ck, $cs, $woocommerce_base_url;
    $products = [];
    $page = 1;
    do {
        $url = "$woocommerce_base_url?consumer_key=$ck&consumer_secret=$cs&per_page=100&page=$page";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        $batch = json_decode($response, true);
        if (is_array($batch)) {
            $products = array_merge($products, $batch);
        } else {
            echo "Error al obtener productos: $response<br>";
        }
        $page++;
    } while (!empty($batch));

    return $products;
}
?>