@extends('admin.layout')

@section('header-title', 'Kütüphane İçeriği Düzenle')

@push('styles')
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<style>
    .ql-editor { min-height: 400px; }
    .action-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        background: #fff;
        color: #64748b;
        text-decoration: none;
        cursor: pointer;
        transition: all 0.15s;
        font-size: 13px;
        font-weight: 500;
    }
    .action-btn:hover { border-color: #3b82f6; color: #3b82f6; }
</style>
@endpush

@section('header-actions')
<a href="{{ route('admin.library-contents.index') }}" class="header-action-btn">
    <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
    Geri
</a>
@endsection

@section('content')

@if(session('success'))
    <div class="flash-msg flash-success" style="margin-bottom:20px;">
        <svg style="width:20px;height:20px;" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        {{ session('success') }}
    </div>
@endif

@if($errors->any())
    <div class="flash-msg flash-error" style="margin-bottom:20px;">
        <svg style="width:20px;height:20px;flex-shrink:0;" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        <div>
            @foreach($errors->all() as $error)
                <div>{{ $error }}</div>
            @endforeach
        </div>
    </div>
@endif

<div style="display:grid;grid-template-columns:1fr 280px;gap:20px;align-items:start;">

    {{-- Main Form --}}
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">✏️ İçerik Düzenle: {{ $libraryContent->title }}</h3>
        </div>
        <div class="card-body">
            <form action="{{ route('admin.library-contents.update', $libraryContent) }}" method="POST" enctype="multipart/form-data" id="editForm">
                @csrf
                @method('PUT')

                <div class="form-group">
                    <label class="form-label">Başlık <span style="color:#ef4444;">*</span></label>
                    <input type="text" name="title" id="titleInput" value="{{ old('title', $libraryContent->title) }}"
                        class="form-control" placeholder="İçerik başlığı" required autofocus>
                </div>

                <div class="form-group">
                    <label class="form-label">Slug</label>
                    <input type="text" name="slug" id="slugInput" value="{{ old('slug', $libraryContent->slug) }}"
                        class="form-control" placeholder="Otomatik oluşturulur">
                    <div class="form-hint">Boş bırakılırsa başlıktan otomatik oluşturulur.</div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Kategori <span style="color:#ef4444;">*</span></label>
                        <select name="category_id" class="form-control form-select" required>
                            <option value="">— Kategori Seçin —</option>
                            @foreach($categories as $id => $name)
                                <option value="{{ $id }}" {{ old('category_id', $libraryContent->category_id) == $id ? 'selected' : '' }}>{{ $name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Tür <span style="color:#ef4444;">*</span></label>
                        <select name="type" class="form-control form-select" required>
                            <option value="article" {{ old('type', $libraryContent->type) == 'article' ? 'selected' : '' }}>📄 Makale</option>
                            <option value="table"   {{ old('type', $libraryContent->type) == 'table'   ? 'selected' : '' }}>📊 Tablo</option>
                            <option value="list"    {{ old('type', $libraryContent->type) == 'list'    ? 'selected' : '' }}>📋 Liste</option>
                            <option value="pdf"     {{ old('type', $libraryContent->type) == 'pdf'     ? 'selected' : '' }}>📕 PDF</option>
                            <option value="mixed"   {{ old('type', $libraryContent->type) == 'mixed'   ? 'selected' : '' }}>🗂️ Karma</option>
                        </select>
                    </div>
                </div>

                {{-- Featured Image --}}
                <div class="form-group">
                    <label class="form-label">Öne Çıkan Görsel</label>

                    @if($libraryContent->featured_image)
                        <div style="margin-bottom:12px;padding:12px;background:#f8fafc;border-radius:8px;border:1px solid #e2e8f0;">
                            <div style="font-size:12px;color:#64748b;margin-bottom:8px;">Mevcut Görsel:</div>
                            <img src="{{ asset($libraryContent->featured_image) }}" alt="Mevcut görsel"
                                 style="max-width:200px;max-height:150px;border-radius:8px;object-fit:cover;display:block;">
                            <label style="display:flex;align-items:center;gap:8px;margin-top:10px;cursor:pointer;font-size:13px;color:#ef4444;">
                                <input type="checkbox" name="remove_featured_image" value="1">
                                Bu görseli sil
                            </label>
                        </div>
                    @endif

                    <div style="margin-bottom:12px;">
                        <label style="display:block;margin-bottom:6px;font-weight:500;color:#0f172a;">Yeni Dosya Yükle</label>
                        <input type="file" name="featured_image" accept="image/*" class="form-control">
                        <div class="form-hint">JPG, PNG, GIF (Max 2MB). Yükleme mevcut görselin yerini alır.</div>
                    </div>
                    <div style="border-top:1px solid #e2e8f0;padding-top:12px;">
                        <label style="display:block;margin-bottom:6px;font-weight:500;color:#0f172a;">Ya da URL Girin</label>
                        <input type="url" name="featured_image_url" value="{{ old('featured_image_url') }}"
                            class="form-control" placeholder="https://example.com/image.jpg">
                        <div class="form-hint">URL girerseniz dosya yüklemesi yerine URL kullanılır.</div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">İçerik</label>
                    <div id="editor" style="background:white;"></div>
                    <textarea name="content" id="contentInput" style="display:none;">{{ old('content', is_string($libraryContent->content) ? $libraryContent->content : (is_array($libraryContent->content) && isset($libraryContent->content['blocks'][0]['data']['text']) ? $libraryContent->content['blocks'][0]['data']['text'] : '')) }}</textarea>
                    <div class="form-hint">WYSIWYG editörü kullanarak içeriği düzenleyin.</div>
                </div>

                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                    <button type="submit" class="btn btn-primary">
                        <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5" style="width:15px;height:15px;"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                        Güncelle
                    </button>
                    <a href="{{ route('admin.library-contents.index') }}" class="btn btn-secondary">İptal</a>
                    <form action="{{ route('admin.library-contents.destroy', $libraryContent) }}" method="POST" onsubmit="return confirm('Bu içeriği silmek istediğinizden emin misiniz?');" style="margin-left:auto;">
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger">
                            <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5" style="width:15px;height:15px;"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                            Sil
                        </button>
                    </form>
                </div>
            </form>
        </div>
    </div>

    {{-- Sidebar --}}
    <div style="display:flex;flex-direction:column;gap:16px;">
        {{-- Content Info --}}
        <div class="card">
            <div class="card-header"><h3 class="card-title">📊 İçerik Bilgileri</h3></div>
            <div class="card-body" style="padding:16px;">
                <div style="display:flex;flex-direction:column;gap:10px;font-size:13px;">
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:#64748b;">Slug:</span>
                        <code style="font-size:11px;color:#0f172a;background:#f1f5f9;padding:4px 8px;border-radius:4px;">{{ $libraryContent->slug }}</code>
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:#64748b;">Tür:</span>
                        <strong>{{ $libraryContent->type }}</strong>
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:#64748b;">Görüntülenme:</span>
                        <strong>{{ number_format($libraryContent->views) }}</strong>
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:#64748b;">Oluşturulma:</span>
                        <strong>{{ $libraryContent->created_at->format('d.m.Y H:i') }}</strong>
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:#64748b;">Güncelleme:</span>
                        <strong>{{ $libraryContent->updated_at->format('d.m.Y H:i') }}</strong>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><h3 class="card-title">🎨 Editör İpuçları</h3></div>
            <div class="card-body" style="padding:16px;font-size:13px;">
                <div style="display:flex;flex-direction:column;gap:8px;color:#64748b;">
                    <div>✓ Başlıklar, paragraflar ve listeler kullanın</div>
                    <div>✓ Metin stillerini (kalın, italik) uygulayın</div>
                    <div>✓ Linkler ve resimler ekleyin</div>
                    <div>✓ Tablolar oluşturun</div>
                    <div>✓ Yazı tipi ve renk değiştirin</div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><h3 class="card-title">🔗 Hızlı İşlemler</h3></div>
            <div class="card-body" style="padding:16px;">
                <div style="display:flex;flex-direction:column;gap:8px;">
                    <a href="{{ route('library.show', [$libraryContent->category->slug, $libraryContent->slug]) }}" target="_blank"
                        class="action-btn" style="width:auto;padding:8px 12px;text-decoration:none;">
                        <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" style="width:14px;height:14px;vertical-align:middle;margin-right:6px;"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                        Ön İzleme
                    </a>
                    <a href="{{ route('admin.library-categories.index') }}" class="action-btn" style="width:auto;padding:8px 12px;text-decoration:none;">
                        <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" style="width:14px;height:14px;vertical-align:middle;margin-right:6px;"><path stroke-linecap="round" stroke-linejoin="round" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/></svg>
                        Kategoriler
                    </a>
                </div>
            </div>
        </div>
    </div>

</div>

<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
    // Initialize Quill editor
    const quill = new Quill('#editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                [{ 'header': [2, 3, 4, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'script': 'sub'}, { 'script': 'super' }],
                [{ 'indent': '-1'}, { 'indent': '+1' }],
                [{ 'size': ['small', false, 'large', 'huge'] }],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'align': [] }],
                ['link', 'image'],
                ['clean']
            ]
        },
        placeholder: 'İçeriğinizi yazın...'
    });

    // Load existing content
    const existingContent = document.getElementById('contentInput').value;
    if (existingContent) {
        quill.root.innerHTML = existingContent;
    }

    // Sync Quill content to hidden textarea before form submission
    document.getElementById('editForm').addEventListener('submit', function() {
        document.getElementById('contentInput').value = quill.root.innerHTML;
    });

    // Auto-generate slug from title
    document.getElementById('titleInput').addEventListener('input', function() {
        const slugInput = document.getElementById('slugInput');
        if (!slugInput.dataset.manual) {
            slugInput.value = this.value
                .toLowerCase()
                .replace(/ğ/g,'g').replace(/ü/g,'u').replace(/ş/g,'s')
                .replace(/ı/g,'i').replace(/ö/g,'o').replace(/ç/g,'c')
                .replace(/[^a-z0-9\s-]/g,'')
                .trim()
                .replace(/\s+/g,'-')
                .replace(/-+/g,'-');
        }
    });

    document.getElementById('slugInput').addEventListener('input', function() {
        this.dataset.manual = 'true';
    });
</script>

@endsection
