<?php
/**
 * Admin - Sayfa Düzenle
 * Konum: /magaza/admin/sayfalar/duzenle.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';
adminCheck();

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: index.php");
    exit;
}

$id = (int)$_GET['id'];
$mesaj = '';

function createSlug($str) {
    $search = array('ç','Ç','ğ','Ğ','ı','İ','ö','Ö','ş','Ş','ü','Ü',' ');
    $replace = array('c','c','g','g','i','i','o','o','s','s','u','u','-');
    $str = str_replace($search, $replace, mb_strtolower(trim($str)));
    $str = preg_replace('/[^a-z0-9\-]/', '', $str);
    return preg_replace('/-+/', '-', $str);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $slug = trim($_POST['slug']);
    $content = $_POST['content'];
    $meta_title = trim($_POST['meta_title']);
    $meta_description = trim($_POST['meta_description']);
    $status = isset($_POST['status']) ? 1 : 0;

    if (empty($slug)) { $slug = createSlug($title); }

    try {
        $stmt = $db->prepare("UPDATE pages SET title = ?, slug = ?, content = ?, meta_title = ?, meta_description = ?, status = ? WHERE id = ?");
        $stmt->execute([$title, $slug, $content, $meta_title, $meta_description, $status, $id]);
        $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Sayfa başarıyla güncellendi.</div>";
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: Bu URL (Slug) başka bir sayfa tarafından kullanılıyor.</div>";
        } else {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Sistem Hatası: " . $e->getMessage() . "</div>";
        }
    }
}

// Mevcut Veriyi Çek
$stmt = $db->prepare("SELECT * FROM pages WHERE id = ?");
$stmt->execute([$id]);
$sayfa = $stmt->fetch();

if (!$sayfa) die("Sayfa bulunamadı.");

require_once '../header.php';
?>

<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-8">
        <h2 class="fw-bold mb-0">
            <a href="index.php" class="btn btn-sm btn-outline-secondary me-2 border-2"><i class="bi bi-arrow-left"></i></a>
            Sayfa Düzenle: <span class="text-primary"><?= htmlspecialchars($sayfa['title']) ?></span>
        </h2>
    </div>
    <div class="col-md-4 text-md-end mt-3 mt-md-0">
        <a href="../../sayfa.php?slug=<?= $sayfa['slug'] ?>" target="_blank" class="btn btn-outline-dark fw-bold shadow-sm"><i class="bi bi-box-arrow-up-right me-1"></i> Sayfayı Gör</a>
    </div>
</div>

<?= $mesaj ?>

<form action="" method="POST">
    <div class="row text-dark">
        <div class="col-lg-8">
            <div class="card shadow-sm border-0 rounded-4 mb-4">
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold">Sayfa Başlığı <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control form-control-lg border-2" value="<?= htmlspecialchars($sayfa['title']) ?>" required>
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label fw-bold">Sayfa İçeriği</label>
                        <textarea name="content" id="summernote" class="form-control"><?= htmlspecialchars($sayfa['content']) ?></textarea>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card shadow-sm border-0 rounded-4 mb-4">
                <div class="card-header bg-white py-3 border-bottom"><h6 class="mb-0 fw-bold"><i class="bi bi-gear-fill text-secondary me-2"></i>Sayfa Ayarları</h6></div>
                <div class="card-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-bold small">Özel Bağlantı (Slug)</label>
                        <input type="text" name="slug" class="form-control border-2" value="<?= htmlspecialchars($sayfa['slug']) ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold small">SEO: Meta Title</label>
                        <input type="text" name="meta_title" class="form-control border-2" value="<?= htmlspecialchars($sayfa['meta_title'] ?? '') ?>">
                    </div>
                    <div class="mb-4">
                        <label class="form-label fw-bold small">SEO: Meta Description</label>
                        <textarea name="meta_description" class="form-control border-2" rows="3"><?= htmlspecialchars($sayfa['meta_description'] ?? '') ?></textarea>
                    </div>
                    
                    <div class="form-check form-switch mb-4 fs-5">
                        <input class="form-check-input cursor-pointer" type="checkbox" name="status" id="statusSwitch" <?= $sayfa['status'] == 1 ? 'checked' : '' ?>>
                        <label class="form-check-label fs-6 ms-2" for="statusSwitch">Sayfa Aktif Olsun</label>
                    </div>

                    <button type="submit" class="btn btn-success btn-lg w-100 fw-bold shadow-sm rounded-pill">
                        <i class="bi bi-arrow-repeat me-1"></i> Değişiklikleri Kaydet
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
<script>
    $(document).ready(function() {
        $('#summernote').summernote({
            height: 400,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'underline', 'clear']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'video']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ]
        });
    });
</script>

<?php require_once '../footer.php'; ?>