<?php
header('Content-Type: application/json');

// بيانات الاتصال (كما وردت في كودك)
$db_conn = new mysqli("localhost", "nameco1_academy_user", "amar197026@A", "nameco1_academy_db");
$db_conn->set_charset("utf8mb4");

if ($db_conn->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'فشل الاتصال بالقاعدة']);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);

if ($data) {
    $page_name = $db_conn->real_escape_string($data['page_name']);
    $permalink = $db_conn->real_escape_string($data['permalink']);
    $full_html = $db_conn->real_escape_string($data['full_html']);

    // التحقق: هل الصفحة موجودة مسبقاً؟ (لتحديثها بدل تكرارها)
    $check = $db_conn->query("SELECT id FROM academy_pages WHERE page_name = '$page_name'");
    
    if ($check->num_rows > 0) {
        $sql = "UPDATE academy_pages SET permalink='$permalink', full_html='$full_html' WHERE page_name='$page_name'";
    } else {
        $sql = "INSERT INTO academy_pages (page_name, permalink, full_html) VALUES ('$page_name', '$permalink', '$full_html')";
    }

    if ($db_conn->query($sql)) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => $db_conn->error]);
    }
}
$db_conn->close();
?>