<?php
include "db.php";
session_start();
if (!isset($_SESSION['email'])) {
  header("Location:login.php");
}
?>

<!DOCTYPE html>
<html lang="en" dir="ltr" data-bs-theme="light" data-color-theme="Blue_Theme" data-layout="vertical">

<head>
    <!-- Required meta tags -->
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!-- Favicon icon-->
    <link rel="shortcut icon" type="image/png" href="../sglogo.png" />

    <!-- Core Css -->
    <link rel="stylesheet" href="assets/css/styles.css" />

    <title>Admin || Blogs Data</title>
    <link rel="stylesheet" href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-bs4.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-bs4.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

</head>

<style>
table.table-bordered.dataTable th,
table.table-bordered.dataTable td {
    border-bottom-width: 1px;
    color: #000000d4;
}
.table-striped > tbody > tr:nth-of-type(odd) > * {
    color: #000000d4;
}
@media (min-width: 576px) {
    .modal-dialog {
        max-width: 650px;
        margin-left: auto;
    }
}
</style>

<body class="link-sidebar">
    <!-- Preloader -->

    <div id="main-wrapper">
        <!-- Sidebar Start -->

        <?php
    include "header.php";
    ?>

        <div class="body-wrapper">
            <div class="container-fluid">
                <div class="card card-body py-3">
                    <div class="row align-items-center">
                        <div class="col-12">
                            <div class="d-sm-flex align-items-center justify-space-between">
                                <h4 class="mb-4 mb-sm-0 card-title">Blogs Data</h4>
                                <nav aria-label="breadcrumb" class="ms-auto">
                                    <ol class="breadcrumb">
                                        <li class="breadcrumb-item d-flex align-items-center gap-2">
                                            <a class="text-muted text-decoration-none d-flex" href="index.php">
                                                <iconify-icon icon="solar:home-2-line-duotone" class="fs-6">
                                                </iconify-icon>
                                            </a>

                                            <!-- Blog Button -->
                                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal"
                                                data-bs-target="#blogFormModal"><i class="fa fa-plus"></i>
                                                Add Blog
                                            </button>
                                        </li>
                                    </ol>

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

                <!-- Blog Form Modal -->
<div class="modal fade" id="blogFormModal" tabindex="-1" aria-labelledby="blogFormModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post" action="insert_blog.php" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title" id="blogFormModalLabel">Add Blog</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body">
          <div class="mb-3">
            <label for="blogTitle" class="form-label">Title</label>
            <input type="text" class="form-control" name="blog_title" id="blogTitle" >
          </div>

          <div class="mb-3">
            <label for="blogImage" class="form-label">Image</label>
            <input type="file" class="form-control" name="blog_image" id="blogImage">
          </div>

          <div class="mb-3">
            <label for="blogContent" class="form-label">Content</label>
            <textarea class="form-control" id="summernote" name="blog_content" id="blogContent" rows="4" ></textarea>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Submit</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>

                <div class="datatables">
                    <!-- start File export -->
                    <div class="card">
                        <div class="card-body">

                            <div class="table-responsive" >

<table id="file_export" class="table w-100 table-striped table-bordered display ">
    <thead>
        <tr>
            <th>Sr.No</th>
            <th>Title</th>
            <th>Image</th>
            <th>Content</th>
            <th>Created At</th>
            <th>Action</th>  
        </tr>
    </thead>
    <tbody>
        <?php
        $sql = "SELECT * FROM blogs ORDER BY id DESC";
        $result = mysqli_query($conn, $sql);
        $sr = 1;

        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                ?>
                <tr id="row-<?= $row['id'] ?>">
                    <td><?= $sr++ ?></td>
                    <td style="text-wrap: auto;max-width: 250px;" ><?= htmlspecialchars($row['title']) ?></td>
                    <td>
                        <?php if (!empty($row['image'])) { ?>
                            <img src="blogs/<?= htmlspecialchars($row['image']) ?>" alt="Blog Image" width="100">
                        <?php } else { echo "No Image"; } ?>
                    </td>
                    <td style="text-wrap: auto;max-width: 500px;" >
                            <?= $row['content'] ?> 
                    </td>
                    <td><?= date("d-m-Y h:i A", strtotime($row['created_at'])) ?></td>
                    <td class="text-nowrap" >
    <!-- Edit Button -->
    <button class="btn btn-primary btn-sm me-1 editBlogBtn" 
            data-id="<?= $row['id'] ?>"
            data-bs-toggle="modal" 
            data-bs-target="#editBlogModal<?=$row['id']?>">
        <i class="fas fa-edit"></i>
    </button>

    <!-- Delete Button -->
    <button class="btn btn-danger btn-sm deleteBlogBtn" data-id="<?= $row['id'] ?>">
        <i class="fas fa-trash-alt"></i>
    </button>
</td>

                </tr>

                <!-- Edit Blog Modal -->
<div class="modal fade" id="editBlogModal<?=$row['id']?>" tabindex="-1" aria-labelledby="editBlogModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form method="post" action="update_blog.php" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title">Edit Blog</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="edit_id" value="<?=$row['id']?>" >

          <div class="mb-3">
            <label>Title</label>
            <input type="text" name="edit_title" class="form-control" value="<?=$row['title']?>">
          </div>

          <div class="mb-3">
            <label>Image</label>
            <input type="file" name="edit_image" class="form-control">
            <img id="previewImage" src="blogs/<?=$row['image']?>" style="max-width:100px; margin-top:5px;" />
          </div>

          <div class="mb-3">
            <label>Content</label>
            <textarea name="edit_content" id="summernote" class="form-control summernote"><?=$row['content']?></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-success" type="submit">Update</button>
        </div>
      </form>
    </div>
  </div>
</div>

                <?php
            }
        }
        ?>
    </tbody>
</table>

                            </div>
                        </div>
                    </div>
                    <!-- end File export -->

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

    <!-- SweetAlert CDN -->

<script>
$(document).ready(function() {
    $('.deleteBlogBtn').click(function() {
        var blogId = $(this).data('id');

        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this blog deletion!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                
                $.ajax({
                    url: 'delete_blog.php',
                    type: 'POST',
                    data: { id: blogId },
                    success: function(response) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Deleted!',
                            text: 'The blog has been deleted.',
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload(); // Refresh page to update table
                        });
                    },
                    error: function() {
                        Swal.fire('Error!', 'Failed to delete blog.', 'error');
                    }
                });
            }
        });
    });
});
</script>


    <script>
    function handleColorTheme(e) {
        document.documentElement.setAttribute("data-color-theme", e);
    }
    </script>
    </div>

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const deleteButtons = document.querySelectorAll(".deleteBtn");

        deleteButtons.forEach(button => {
            button.addEventListener("click", function() {
                const contactId = this.dataset.id;

                Swal.fire({
                    title: "Are you sure?",
                    text: "This contact will be deleted!",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#d33",
                    cancelButtonColor: "#3085d6",
                    confirmButtonText: "Yes, delete it!"
                }).then((result) => {
                    if (result.isConfirmed) {
                        fetch("delete_contact.php", {
                                method: "POST",
                                headers: {
                                    "Content-Type": "application/x-www-form-urlencoded"
                                },
                                body: "delete_id=" + contactId
                            })
                            .then(response => response.text())
                            .then(data => {
                                if (data === "success") {
                                    document.getElementById("row-" + contactId)
                                        .remove();
                                    Swal.fire("Deleted!",
                                        "The contact has been deleted.",
                                        "success");
                                } else {
                                    Swal.fire("Error!", "Failed to delete contact.",
                                        "error");
                                }
                            });
                    }
                });
            });
        });
    });
    </script>

<script>
    $('textarea#summernote').summernote({
        placeholder: 'Add Blog description',
        tabsize: 2,
        height: 100,
  toolbar: [
        ['style', ['style']],
        ['font', ['bold', 'italic', 'underline', 'clear']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['height', ['height']],
        ['table', ['table']],
        ['insert', ['link', 'picture', 'hr']],
        ['help', ['help']]
      ],
      });
      $('textarea[id^="summernote-"]').each(function() {
      var textareaId = $(this).attr('id'); 
      $('#' + textareaId).summernote({
        placeholder: 'Enter text here',
        tabsize: 2,
        height: 100,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'italic', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['height', ['height']],
          ['table', ['table']],
          ['insert', ['link', 'picture', 'hr']],
          ['help', ['help']]
        ]
      });
    });
</script>

    <div class="dark-transparent sidebartoggler"></div>
    <script src="assets/js/vendor.min.js"></script>
    <!-- Import Js Files -->
    <script src="assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/simplebar/dist/simplebar.min.js"></script>
    <script src="assets/js/theme/app.init.js"></script>
    <script src="assets/js/theme/theme.js"></script>
    <script src="assets/js/theme/app.min.js"></script>
    <script src="assets/js/theme/sidebarmenu-default.js"></script>

    <!-- solar icons -->
    <script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.8/dist/iconify-icon.min.js"></script>

    <!-- highlight.js (code view) -->
    <script src="assets/js/highlights/highlight.min.js"></script>
    <script>
    hljs.initHighlightingOnLoad();


    document.querySelectorAll("pre.code-view > code").forEach((codeBlock) => {
        codeBlock.textContent = codeBlock.innerHTML;
    });
    </script>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>

    <script src="assets/js/datatable/datatable-advanced.init.js"></script>
</body>


</html>