<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include ('include/header.php');
$page_title = WEB_NAME . " | Blog Management";

// ── Fetch all posts ───────────────────────────────────────────────────────
try {
    $posts = $pdo->query(
        "SELECT id, title, category, author, status, views, thumbnail, created_at
         FROM blog_posts ORDER BY created_at DESC"
    )->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $posts = [];
}

// ── Published / Draft counts ─────────────────────────────────────────────
$total_published = 0;
$total_draft     = 0;
$total_views     = 0;
foreach ($posts as $p) {
    if ($p['status'] === 'published') $total_published++;
    else $total_draft++;
    $total_views += (int)$p['views'];
}
?>
<title><?php echo $page_title; ?></title>

<!-- Summernote + SweetAlert2 CSS — load before footer closes the document -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-bs4.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<!-- Container Fluid -->
<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800"><i class="fas fa-blog mr-2"></i>Blog Management</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active">Blog</li>
    </ol>
  </div>

  <!-- ── Stats Row ─────────────────────────────────────────────────────── -->
  <div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-primary shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Posts</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo count($posts); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-file-alt fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Published</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $total_published; ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-check-circle fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Drafts</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $total_draft; ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-pencil-alt fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-info shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Views</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($total_views); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-eye fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Action Bar ─────────────────────────────────────────────────────── -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center flex-wrap gap-2"
         style="background:linear-gradient(135deg,#0201FD,#111199);">
      <h6 class="m-0 font-weight-bold text-white"><i class="fas fa-list mr-1"></i> All Blog Posts</h6>
      <button class="btn btn-light btn-sm font-weight-bold" onclick="openCreateModal()">
        <i class="fas fa-plus mr-1"></i> New Post
      </button>
    </div>
    <div class="card-body">

      <?php if (empty($posts)): ?>
        <div class="text-center py-5">
          <i class="fas fa-blog fa-4x text-gray-300 mb-3"></i>
          <p class="text-muted">No blog posts yet. Create your first post!</p>
          <button class="btn btn-primary" onclick="openCreateModal()"><i class="fas fa-plus mr-1"></i> New Post</button>
        </div>
      <?php else: ?>

      <div class="table-responsive">
        <table class="table table-bordered table-hover" id="blogTable" width="100%" cellspacing="0">
          <thead class="thead-light">
            <tr>
              <th width="60">Thumbnail</th>
              <th>Title</th>
              <th width="110">Category</th>
              <th width="90">Author</th>
              <th width="90">Status</th>
              <th width="80">Views</th>
              <th width="130">Date</th>
              <th width="130" class="text-center">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($posts as $post): ?>
            <tr>
              <td class="text-center align-middle">
                <?php if (!empty($post['thumbnail'])): ?>
                  <img src="<?php echo htmlspecialchars($post['thumbnail']); ?>"
                       alt="" style="width:50px;height:38px;object-fit:cover;border-radius:4px;">
                <?php else: ?>
                  <div style="width:50px;height:38px;background:#eee;border-radius:4px;display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-image text-muted" style="font-size:16px;"></i>
                  </div>
                <?php endif; ?>
              </td>
              <td class="align-middle">
                <strong><?php echo htmlspecialchars($post['title']); ?></strong>
              </td>
              <td class="align-middle">
                <span class="badge badge-primary"><?php echo htmlspecialchars($post['category']); ?></span>
              </td>
              <td class="align-middle small"><?php echo htmlspecialchars($post['author']); ?></td>
              <td class="align-middle">
                <?php if ($post['status'] === 'published'): ?>
                  <span class="badge badge-success">Published</span>
                <?php else: ?>
                  <span class="badge badge-warning text-dark">Draft</span>
                <?php endif; ?>
              </td>
              <td class="align-middle text-center"><?php echo number_format($post['views']); ?></td>
              <td class="align-middle small"><?php echo date('M d, Y', strtotime($post['created_at'])); ?></td>
              <td class="align-middle text-center">
                <button class="btn btn-sm btn-info mr-1" title="Edit"
                        onclick="openEditModal(<?php echo $post['id']; ?>)">
                  <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-danger" title="Delete"
                        onclick="deletePost(<?php echo $post['id']; ?>, '<?php echo htmlspecialchars(addslashes($post['title'])); ?>')">
                  <i class="fas fa-trash"></i>
                </button>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <?php endif; ?>
    </div>
  </div>

</div><!-- /container-fluid -->


<!-- ════════════════════════════════════════════════════════════════
     CREATE / EDIT MODAL
════════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="blogModal" tabindex="-1" role="dialog" aria-labelledby="blogModalLabel">
  <div class="modal-dialog modal-xl" role="document">
    <div class="modal-content">

      <div class="modal-header" style="background:linear-gradient(135deg,#0201FD,#111199);">
        <h5 class="modal-title text-white font-weight-bold" id="blogModalLabel">
          <i class="fas fa-blog mr-2"></i> <span id="modalTitleText">New Blog Post</span>
        </h5>
        <button type="button" class="close text-white" data-dismiss="modal">
          <span>&times;</span>
        </button>
      </div>

      <div class="modal-body">
        <!-- Hidden post id for edit mode -->
        <input type="hidden" id="post_id" value="">

        <div class="row">
          <!-- Left column -->
          <div class="col-lg-8">

            <div class="form-group">
              <label><strong>Post Title <span class="text-danger">*</span></strong></label>
              <input type="text" class="form-control form-control-lg" id="post_title"
                     placeholder="Enter an engaging blog post title..." oninput="autoSlug()">
            </div>

            <div class="form-group">
              <label><strong>Content <span class="text-danger">*</span></strong></label>
              <textarea id="post_content" class="form-control" rows="15"
                        placeholder="Write your blog post content here..."></textarea>
            </div>

            <div class="form-group">
              <label><strong>Excerpt / Short Description <span class="text-danger">*</span></strong></label>
              <textarea class="form-control" id="post_excerpt" rows="3"
                        placeholder="Brief summary shown on the blog listing page (1–2 sentences)..."></textarea>
            </div>

          </div>

          <!-- Right column -->
          <div class="col-lg-4">

            <!-- Publish box -->
            <div class="card shadow-sm mb-3">
              <div class="card-header bg-light py-2">
                <strong><i class="fas fa-cog mr-1"></i> Publish Settings</strong>
              </div>
              <div class="card-body">
                <div class="form-group mb-2">
                  <label><strong>Status</strong></label>
                  <select class="form-control" id="post_status">
                    <option value="published">✅ Published</option>
                    <option value="draft">📝 Draft</option>
                  </select>
                </div>
                <div class="form-group mb-2">
                  <label><strong>Category</strong></label>
                  <input type="text" class="form-control" id="post_category"
                         placeholder="e.g. SMM Tips, Privacy, Marketing">
                  <small class="text-muted">Type a new or existing category</small>
                </div>
                <div class="form-group mb-2">
                  <label><strong>Author</strong></label>
                  <input type="text" class="form-control" id="post_author"
                         value="<?php echo htmlspecialchars($admin_data['full_name'] ?? $admin_data['username'] ?? 'Admin'); ?>">
                </div>
                <div class="form-group mb-0">
                  <label><strong>Read Time</strong></label>
                  <div class="input-group">
                    <input type="text" class="form-control" id="post_read_time"
                           value="5 min read" placeholder="5 min read">
                  </div>
                </div>
              </div>
            </div>

            <!-- URL Slug -->
            <div class="card shadow-sm mb-3">
              <div class="card-header bg-light py-2">
                <strong><i class="fas fa-link mr-1"></i> URL Slug</strong>
              </div>
              <div class="card-body">
                <div class="input-group">
                  <div class="input-group-prepend">
                    <span class="input-group-text" style="font-size:11px;">/blog-details.php?slug=</span>
                  </div>
                  <input type="text" class="form-control" id="post_slug"
                         placeholder="auto-generated-from-title">
                </div>
                <small class="text-muted">Auto-generated — edit if needed</small>
              </div>
            </div>

            <!-- Thumbnail upload -->
            <div class="card shadow-sm mb-3">
              <div class="card-header bg-light py-2">
                <strong><i class="fas fa-image mr-1"></i> Thumbnail Image</strong>
              </div>
              <div class="card-body">
                <!-- Current thumbnail preview -->
                <div id="thumbnailPreviewWrap" class="mb-2" style="display:none;">
                  <img id="thumbnailPreview" src="" alt="Thumbnail"
                       style="width:100%;height:150px;object-fit:cover;border-radius:6px;border:1px solid #ddd;">
                  <button type="button" class="btn btn-sm btn-outline-danger btn-block mt-1"
                          onclick="clearThumbnail()">
                    <i class="fas fa-times mr-1"></i> Remove Image
                  </button>
                </div>
                <input type="file" class="form-control-file" id="post_thumbnail_file"
                       accept="image/jpeg,image/png,image/webp,image/gif"
                       onchange="previewThumbnail(this)">
                <small class="text-muted">JPG, PNG, WEBP or GIF. Max 2MB. Leave blank to keep existing.</small>
                <!-- Hidden: stores the existing URL when editing -->
                <input type="hidden" id="post_thumbnail_existing" value="">
              </div>
            </div>

          </div><!-- /col-lg-4 -->
        </div><!-- /row -->
      </div><!-- /modal-body -->

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary px-4" onclick="savePost()">
          <i class="fas fa-save mr-1"></i> <span id="saveBtnText">Publish Post</span>
        </button>
      </div>

    </div>
  </div>
</div>


<!-- ── Scripts: load before footer so they are available in DOM ─────────── -->
<!--
    IMPORTANT LOAD ORDER:
    1. jQuery        — already loaded by the theme's header
    2. Summernote JS — must come BEFORE our inline script
    3. SweetAlert2   — must come BEFORE our inline script
    We do NOT re-include Bootstrap — the theme already loads it.
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-bs4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
(function($) {
  'use strict';

  // ── State: content to inject when modal opens ─────────────────────────
  var _pendingContent = '';
  var _summernoteReady = false;

  // ── Init Summernote the FIRST time the modal becomes fully visible ─────
  // Using shown.bs.modal fires after the CSS transition completes,
  // which means the textarea is in the DOM and has non-zero dimensions.
  // This avoids the "toolbar height = 0" bug and the "not a function" error
  // that happens when Summernote tries to initialise on a hidden element.
  $('#blogModal').on('shown.bs.modal', function() {
    if (!_summernoteReady) {
      $('#post_content').summernote({
        height: 380,
        placeholder: 'Write your blog post content here...',
        toolbar: [
          ['style',  ['style']],
          ['font',   ['bold', 'italic', 'underline', 'strikethrough', 'clear']],
          ['color',  ['color']],
          ['para',   ['ul', 'ol', 'paragraph']],
          ['table',  ['table']],
          ['insert', ['link', 'hr']],
          ['view',   ['fullscreen', 'codeview']]
        ]
      });
      _summernoteReady = true;
    }
    // Apply any pending content (set before the modal was shown)
    if (_pendingContent !== null) {
      $('#post_content').summernote('code', _pendingContent);
      _pendingContent = null;
    }
  });

  // Destroy Summernote when modal closes so it re-inits cleanly next time
  $('#blogModal').on('hidden.bs.modal', function() {
    if (_summernoteReady) {
      $('#post_content').summernote('destroy');
      _summernoteReady = false;
    }
    _pendingContent = '';
  });

  // ── DataTable init ────────────────────────────────────────────────────
  $(document).ready(function() {
    if ($.fn.DataTable && $('#blogTable').length) {
      $('#blogTable').DataTable({ order: [[6, 'desc']], pageLength: 15 });
    }
  });

  // ── Helper: open the Bootstrap modal safely, bypassing theme overrides ─
  // Some admin themes (ruang-admin, sb-admin etc.) override $.fn.modal.
  // Calling the native Bootstrap Modal constructor directly always works.
  function showModal() {
    var el = document.getElementById('blogModal');
    if (!el) return;
    // Bootstrap 4 native constructor
    var bsModal = new bootstrap.Modal(el, { backdrop: true, keyboard: true });
    bsModal.show();
  }

  // ── Auto-slug ─────────────────────────────────────────────────────────
  window.autoSlug = function() {
    var title = document.getElementById('post_title').value;
    var slug  = title.toLowerCase()
      .replace(/[^a-z0-9\s-]/g, '')
      .trim()
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-');
    document.getElementById('post_slug').value = slug;
  };

  // ── Thumbnail helpers ─────────────────────────────────────────────────
  window.previewThumbnail = function(input) {
    if (input.files && input.files[0]) {
      if (input.files[0].size > 2 * 1024 * 1024) {
        Swal.fire('File Too Large', 'Thumbnail must be under 2 MB.', 'warning');
        input.value = '';
        return;
      }
      var reader = new FileReader();
      reader.onload = function(e) {
        document.getElementById('thumbnailPreview').src = e.target.result;
        document.getElementById('thumbnailPreviewWrap').style.display = 'block';
      };
      reader.readAsDataURL(input.files[0]);
    }
  };

  window.clearThumbnail = function() {
    document.getElementById('post_thumbnail_file').value     = '';
    document.getElementById('post_thumbnail_existing').value = '';
    document.getElementById('thumbnailPreview').src          = '';
    document.getElementById('thumbnailPreviewWrap').style.display = 'none';
  };

  function showThumbnailPreview(url) {
    if (url) {
      document.getElementById('thumbnailPreview').src = url;
      document.getElementById('thumbnailPreviewWrap').style.display = 'block';
    } else {
      document.getElementById('thumbnailPreviewWrap').style.display = 'none';
    }
  }

  // ── Open Create modal ─────────────────────────────────────────────────
  window.openCreateModal = function() {
    document.getElementById('post_id').value                 = '';
    document.getElementById('post_title').value              = '';
    document.getElementById('post_excerpt').value            = '';
    document.getElementById('post_slug').value               = '';
    document.getElementById('post_category').value           = '';
    document.getElementById('post_read_time').value          = '5 min read';
    document.getElementById('post_status').value             = 'published';
    document.getElementById('post_thumbnail_existing').value = '';
    document.getElementById('post_thumbnail_file').value     = '';
    document.getElementById('thumbnailPreviewWrap').style.display = 'none';
    document.getElementById('modalTitleText').textContent    = 'New Blog Post';
    document.getElementById('saveBtnText').textContent       = 'Publish Post';

    _pendingContent = ''; // clear content for new post
    showModal();
  };

  // ── Open Edit modal ───────────────────────────────────────────────────
  window.openEditModal = function(id) {
    Swal.fire({ title: 'Loading...', allowOutsideClick: false,
                didOpen: function() { Swal.showLoading(); } });

    $.ajax({
      url: 'ajax/blog_handler.php', type: 'POST',
      data: { action: 'get_post', id: id },
      dataType: 'json',
      success: function(res) {
        Swal.close();
        if (res.status !== '1') { Swal.fire('Error', res.msg, 'error'); return; }

        var p = res.post;
        document.getElementById('post_id').value                 = p.id;
        document.getElementById('post_title').value              = p.title;
        document.getElementById('post_excerpt').value            = p.excerpt;
        document.getElementById('post_slug').value               = p.slug;
        document.getElementById('post_category').value           = p.category;
        document.getElementById('post_author').value             = p.author;
        document.getElementById('post_read_time').value          = p.read_time;
        document.getElementById('post_status').value             = p.status;
        document.getElementById('post_thumbnail_existing').value = p.thumbnail || '';
        document.getElementById('post_thumbnail_file').value     = '';
        document.getElementById('modalTitleText').textContent    = 'Edit Blog Post';
        document.getElementById('saveBtnText').textContent       = 'Save Changes';

        _pendingContent = p.content || ''; // will be applied in shown.bs.modal
        showThumbnailPreview(p.thumbnail);
        showModal();
      },
      error: function() { Swal.fire('Error', 'Could not load post data.', 'error'); }
    });
  };

  // ── Save post ─────────────────────────────────────────────────────────
  window.savePost = function() {
    var id        = document.getElementById('post_id').value.trim();
    var title     = document.getElementById('post_title').value.trim();
    var excerpt   = document.getElementById('post_excerpt').value.trim();
    var slug      = document.getElementById('post_slug').value.trim();
    var category  = document.getElementById('post_category').value.trim();
    var author    = document.getElementById('post_author').value.trim();
    var readTime  = document.getElementById('post_read_time').value.trim();
    var status    = document.getElementById('post_status').value;
    var existing  = document.getElementById('post_thumbnail_existing').value;
    var fileInput = document.getElementById('post_thumbnail_file');

    // Get content — fallback to raw textarea value if Summernote is not ready
    var content = _summernoteReady
      ? ($('#post_content').summernote('code') || '').trim()
      : document.getElementById('post_content').value.trim();

    if (!title)    { Swal.fire('Required', 'Post title is required.',    'warning'); return; }
    if (!content || content === '<p><br></p>') {
      Swal.fire('Required', 'Post content cannot be empty.', 'warning'); return;
    }
    if (!excerpt)  { Swal.fire('Required', 'Excerpt is required.',       'warning'); return; }
    if (!category) { Swal.fire('Required', 'Category is required.',      'warning'); return; }

    Swal.fire({ title: 'Saving...', allowOutsideClick: false,
                didOpen: function() { Swal.showLoading(); } });

    var formData = new FormData();
    formData.append('action',              id ? 'update_post' : 'create_post');
    formData.append('id',                  id);
    formData.append('title',               title);
    formData.append('content',             content);
    formData.append('excerpt',             excerpt);
    formData.append('slug',                slug);
    formData.append('category',            category);
    formData.append('author',              author);
    formData.append('read_time',           readTime);
    formData.append('status',              status);
    formData.append('thumbnail_existing',  existing);
    if (fileInput.files.length > 0) {
      formData.append('thumbnail_file', fileInput.files[0]);
    }

    $.ajax({
      url: 'ajax/blog_handler.php', type: 'POST',
      data: formData, processData: false, contentType: false, dataType: 'json',
      success: function(res) {
        if (res.status === '1') {
          Swal.fire({ icon: 'success', title: id ? 'Post Updated!' : 'Post Published!',
                      text: res.msg, timer: 1800, showConfirmButton: false })
              .then(function() { location.reload(); });
        } else {
          Swal.fire('Error', res.msg, 'error');
        }
      },
      error: function() { Swal.fire('Error', 'Server error. Please try again.', 'error'); }
    });
  };

  // ── Delete post ───────────────────────────────────────────────────────
  window.deletePost = function(id, title) {
    Swal.fire({
      title: 'Delete Post?',
      html:  'This will permanently delete:<br><strong>' + title + '</strong>',
      icon: 'warning', showCancelButton: true,
      confirmButtonColor: '#e74a3b',
      confirmButtonText: 'Yes, Delete', cancelButtonText: 'Cancel'
    }).then(function(result) {
      if (!result.isConfirmed) return;
      Swal.fire({ title: 'Deleting...', allowOutsideClick: false,
                  didOpen: function() { Swal.showLoading(); } });
      $.ajax({
        url: 'ajax/blog_handler.php', type: 'POST',
        data: { action: 'delete_post', id: id }, dataType: 'json',
        success: function(res) {
          if (res.status === '1') {
            Swal.fire({ icon: 'success', title: 'Deleted!', text: res.msg,
                        timer: 1500, showConfirmButton: false })
                .then(function() { location.reload(); });
          } else { Swal.fire('Error', res.msg, 'error'); }
        },
        error: function() { Swal.fire('Error', 'Server error.', 'error'); }
      });
    });
  };

})(jQuery);
</script>

<?php include ('include/footer.php'); ?>