<?php
include "session.php";
header('Content-Type: application/json');

require_once __DIR__ . '/../db.php';

$body = json_decode(file_get_contents('php://input'), true);
$product_id   = intval($body['product_id'] ?? 0);
$html_content = $body['html_content'] ?? '';

if (!$product_id || empty($html_content)) {
    echo json_encode(['success' => false, 'message' => 'بيانات غير كاملة']);
    exit;
}

// INSERT أو UPDATE إذا كانت موجودة
$stmt = $pdo->prepare("
    INSERT INTO landing_pages (product_id, html_content)
    VALUES (:pid, :html)
    ON DUPLICATE KEY UPDATE html_content = :html2, updated_at = NOW()
");

// لجعل ON DUPLICATE يعمل نحتاج UNIQUE على product_id
// تأكد من إضافة: ALTER TABLE landing_pages ADD UNIQUE KEY uq_product (product_id);

$stmt->execute([
    ':pid'   => $product_id,
    ':html'  => $html_content,
    ':html2' => $html_content
]);

echo json_encode(['success' => true]);