<?php
require_once "../includes/auth.php";
require_once "../config/db.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id']);
    $title = $_POST['title'] ?? '';
    $desc = $_POST['description'] ?? '';

    // صورة OG
    $image_name = null;
    if (!empty($_FILES['image']['name'])) {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $image_name = uniqid() . '.' . $ext;
        move_uploaded_file($_FILES['image']['tmp_name'], "../uploads/seo/" . $image_name);

        // حذف الصورة القديمة إذا كانت موجودة
        $old = $pdo->query("SELECT image FROM seo_pages WHERE id = $id")->fetchColumn();
        if ($old && file_exists("../uploads/seo/$old")) {
            unlink("../uploads/seo/$old");
        }

        $stmt = $pdo->prepare("UPDATE seo_pages SET title=?, description=?, image=? WHERE id=?");
        $stmt->execute([$title, $desc, $image_name, $id]);
    } else {
        $stmt = $pdo->prepare("UPDATE seo_pages SET title=?, description=? WHERE id=?");
        $stmt->execute([$title, $desc, $id]);
    }

    header("Location: index.php");
    exit;
}
?>
