<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="zytheme">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Blog Management - Granny Restaurant">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">

    <!-- Font Awesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Bootstrap CSS -->
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">

    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <!-- TinyMCE Editor -->
    <!-- Replace 'YOUR_API_KEY_HERE' with your free API key from https://www.tiny.cloud/ -->
    <!-- <script src="https://cdn.tiny.cloud/1/YOUR_API_KEY_HERE/tinymce/6/tinymce.min.js"></script> -->

    <title>Blog Management - Granny Restaurant</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 0;
            z-index: 1000;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 30px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            text-align: center;
            border-bottom: 3px solid #d4a574;
        }

        .sidebar-logo {
            font-size: 40px;
            margin-bottom: 10px;
            display: block;
        }

        .sidebar-header h2 {
            font-size: 20px;
            margin: 10px 0 5px 0;
            font-weight: 700;
        }

        .sidebar-header p {
            font-size: 12px;
            opacity: 0.9;
            margin: 0;
        }

        .admin-name {
            font-size: 11px;
            opacity: 0.8;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar-menu {
            list-style: none;
            padding: 20px 0;
        }

        .sidebar-menu li {
            margin: 0;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 25px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 500;
            border-left: 3px solid transparent;
        }

        .sidebar-menu a:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-left-color: #d4a574;
            padding-left: 28px;
        }

        .sidebar-menu a.active {
            background: rgba(255, 255, 255, 0.15);
            color: white;
            border-left-color: #d4a574;
        }

        .sidebar-menu i {
            width: 20px;
            text-align: center;
            font-size: 16px;
        }

        .sidebar-footer {
            position: absolute;
            width: 100%;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.1);
            /* bottom: 0; */
            /* padding: 20px; */
        }

        .logout-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
        }

        /* Topbar */
        .topbar {
            position: fixed;
            left: 280px;
            top: 0;
            right: 0;
            height: 70px;
            background: white;
            border-bottom: 1px solid #e8e8e8;
            padding: 0 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 999;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .topbar-title {
            font-size: 24px;
            font-weight: 700;
            color: #333;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .topbar-user {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 16px;
        }

        .user-info p {
            margin: 0;
            font-size: 13px;
            color: #999;
        }

        .user-info strong {
            display: block;
            font-size: 14px;
            color: #333;
        }

        /* Main Content */
        .main-content {
            margin-left: 280px;
            margin-top: 70px;
            padding: 30px;
            min-height: calc(100vh - 70px);
        }

        .content-section {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 28px;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .section-title i {
            color: #d4a574;
            font-size: 32px;
        }

        .btn-group {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }

        .btn-action {
            background: linear-gradient(135deg, #d4a574 0%, #c99560 100%);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-action:hover {
            background: linear-gradient(135deg, #c99560 0%, #b8854f 100%);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
        }

        .btn-action-secondary {
            background: #f0f0f0;
            color: #333;
            border: 1px solid #e0e0e0;
        }

        .btn-action-secondary:hover {
            background: #e0e0e0;
        }

        .table-responsive {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        thead {
            background: #f9f9f9;
            border-bottom: 2px solid #e0e0e0;
        }

        th {
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #333;
        }

        td {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        tr:hover {
            background: #fafafa;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-badge.draft {
            background: #fff3cd;
            color: #856404;
        }

        .status-badge.published {
            background: #d4edda;
            color: #155724;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-edit, .btn-delete {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .btn-edit {
            background: #d4a574;
            color: white;
        }

        .btn-edit:hover {
            background: #c99560;
            transform: translateY(-2px);
        }

        .btn-delete {
            background: #e74c3c;
            color: white;
        }

        .btn-delete:hover {
            background: #c0392b;
            transform: translateY(-2px);
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
        }

        .modal.show {
            display: block;
        }

        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 900px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 24px;
            color: #333;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #999;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        input[type="text"],
        input[type="email"],
        input[type="number"],
        input[type="date"],
        select,
        textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: 'Raleway', sans-serif;
            font-size: 14px;
        }

        input[type="text"]:focus,
        input[type="email"]:focus,
        input[type="number"]:focus,
        input[type="date"]:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 120px;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .form-row.full {
            grid-template-columns: 1fr;
        }

        .image-preview {
            margin-top: 10px;
            max-width: 200px;
            max-height: 200px;
            border-radius: 6px;
        }

        .modal-footer {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #f0f0f0;
        }

        .btn-save {
            background: linear-gradient(135deg, #d4a574 0%, #c99560 100%);
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-save:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
        }

        .btn-cancel {
            background: #f0f0f0;
            color: #333;
            padding: 12px 30px;
            border: 1px solid #ddd;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-cancel:hover {
            background: #e0e0e0;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .loading {
            text-align: center;
            padding: 40px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #d4a574;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .tox-tinymce {
            margin-top: 8px;
        }

        .menu-toggle {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #333;
            padding: 10px;
            transition: all 0.3s ease;
        }

        .menu-toggle:hover {
            color: #d4a574;
        }

        @media (max-width: 768px) {
            .menu-toggle {
                display: block;
            }

            .main-content {
                margin-left: 0;
            }

            .topbar {
                left: 0;
            }

            .sidebar {
                transform: translateX(-280px);
                transition: transform 0.3s ease;
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .modal-content {
                width: 95%;
                margin: 20% auto;
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-crown sidebar-logo"></i>
            <h2>Admin Portal</h2>
            <p>Granny Restaurant</p>
            <div class="admin-name" id="sidebarAdminName">Admin</div>
        </div>

        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>Dashboard</span></a></li>
            <li><a href="carousel.php"><i class="fas fa-images"></i> <span>Carousel</span></a></li>
            <li><a href="gallery.php"><i class="fas fa-th-large"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Dine-in Tables</span></a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> <span>Online Tables</span></a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="blog.php" class="active"><i class="fas fa-blog"></i> <span>Blog</span></a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-check"></i> <span>Bookings</span></a></li>
            <li><a href="orders.php"><i class="fas fa-shopping-cart"></i> <span>Orders</span></a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> <span>Contacts</span></a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> <span>Feedback</span></a></li>
            <li><a href="purchase_managers.php"><i class="fas fa-handshake"></i> <span>Purchase Managers</span></a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> <span>Users</span></a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> <span>Settings</span></a></li>
        </ul>

        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i> Logout
            </button>
        </div>
    </div>

    <!-- Top Header -->
    <div class="topbar">
        <div style="display: flex; align-items: center; gap: 20px;">
            <button class="menu-toggle" id="menuToggle">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">Blog Management</div>
        </div>

        <div class="topbar-right">
            <div class="topbar-user">
                <div class="user-avatar" id="userInitial">A</div>
                <div class="user-info">
                    <p>Welcome back</p>
                    <strong id="topbarUserName">Admin</strong>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="content-section">
            <div class="section-title">
                <i class="fas fa-blog"></i>
                Blog Management
            </div>
            <p style="color: #666; margin-bottom: 20px;">Create, edit, and manage blog posts for the restaurant</p>

            <div class="btn-group">
                <button class="btn-action" id="addBlogBtn">
                    <i class="fas fa-plus"></i> Create New Blog
                </button>
            </div>

            <div class="table-responsive">
                <div id="blogsTableContainer">
                    <div class="loading">
                        <div class="spinner"></div>
                        <p>Loading blogs...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Blog Modal -->
    <div id="blogModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Create New Blog</h2>
                <button class="modal-close" onclick="closeBlogModal()">&times;</button>
            </div>

            <form id="blogForm" enctype="multipart/form-data">
                <input type="hidden" id="blogId" name="id">

                <div class="form-row full">
                    <div class="form-group">
                        <label for="blogTitle">Title *</label>
                        <input type="text" id="blogTitle" name="title" required placeholder="Enter blog title">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="blogCategory">Category</label>
                        <input type="text" id="blogCategory" name="category" placeholder="e.g., Recipes, News, Tips">
                    </div>
                    <div class="form-group">
                        <label for="blogStatus">Status</label>
                        <select id="blogStatus" name="status">
                            <option value="draft">Draft</option>
                            <option value="published">Published</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label for="blogExcerpt">Excerpt</label>
                    <textarea id="blogExcerpt" name="excerpt" placeholder="Short description (500 characters max)"></textarea>
                </div>

                <div class="form-group">
                    <label for="blogContent">Content *</label>
                    <textarea id="blogContent" name="content" required placeholder="Enter blog content"></textarea>
                </div>

                <div class="form-group">
                    <label for="blogImage">Featured Image</label>
                    <input type="file" id="blogImage" name="featured_image" accept="image/*">
                    <small style="color: #666;">Max size: 5MB. Formats: JPG, PNG, GIF, WebP</small>
                    <img id="imagePreview" class="image-preview" style="display: none;">
                </div>

                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="blogFeatured" name="featured" value="1">
                        <label for="blogFeatured" style="margin: 0;">Mark as Featured</label>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn-cancel" onclick="closeBlogModal()">Cancel</button>
                    <button type="submit" class="btn-save" id="saveBlogBtn">Save Blog</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../assets/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

    <script>

        // Global variables
        let currentBlogId = null;
        let allBlogs = [];

        // On page load
        document.addEventListener('DOMContentLoaded', function() {
            checkAdminAccess();
            loadBlogs();
            setupEventListeners();
        });

        // Setup event listeners
        function setupEventListeners() {
            document.getElementById('addBlogBtn').addEventListener('click', openBlogModal);
            document.getElementById('blogForm').addEventListener('submit', saveBlog);
            document.getElementById('logoutBtn').addEventListener('click', logout);
            document.getElementById('blogImage').addEventListener('change', previewImage);
            document.getElementById('menuToggle').addEventListener('click', toggleSidebar);
        }

        // Check admin access
        function checkAdminAccess() {
            // Try to get admin data from localStorage using the correct key
            let adminData = localStorage.getItem('admin_user');
            
            // If not in localStorage, try the old key name (for backward compatibility)
            if (!adminData) {
                adminData = localStorage.getItem('adminData');
            }
            
            // If still not found, try sessionStorage
            if (!adminData) {
                adminData = sessionStorage.getItem('admin_user');
            }
            
            // Parse and use the data
            if (adminData) {
                try {
                    adminData = JSON.parse(adminData);
                    document.getElementById('sidebarAdminName').textContent = adminData.name || 'Admin';
                    document.getElementById('topbarUserName').textContent = adminData.name || 'Admin';
                    document.getElementById('userInitial').textContent = (adminData.name || 'A')[0].toUpperCase();
                    return;
                } catch (e) {
                    console.error('Error parsing admin data:', e);
                }
            }
            
            // If no admin data found in localStorage, check backend for session
            fetch('auth_check.php')
                .then(response => response.json())
                .then(data => {
                    if (data.authenticated && data.user) {
                        // Admin is authenticated via session
                        document.getElementById('sidebarAdminName').textContent = data.user.name || 'Admin';
                        document.getElementById('topbarUserName').textContent = data.user.name || 'Admin';
                        document.getElementById('userInitial').textContent = (data.user.name || 'A')[0].toUpperCase();
                        
                        // Store in localStorage for future use
                        localStorage.setItem('admin_user', JSON.stringify(data.user));
                    } else {
                        // Not authenticated, redirect to login
                        window.location.href = 'login.php';
                    }
                })
                .catch(error => {
                    console.error('Auth check error:', error);
                    // If auth check fails, redirect to login to be safe
                    window.location.href = 'login.php';
                });
        }

        // Load all blogs
        function loadBlogs() {
            fetch('../backend/blog_api.php?action=get_blogs_admin')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        allBlogs = data.data || [];
                        renderBlogsTable();
                    } else {
                        showError('Failed to load blogs');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('Error loading blogs');
                });
        }

        // Render blogs table
        function renderBlogsTable() {
            const container = document.getElementById('blogsTableContainer');

            if (allBlogs.length === 0) {
                container.innerHTML = '<div class="no-data"><i class="fas fa-inbox" style="font-size: 40px; color: #ccc; margin-bottom: 15px;"></i><p>No blogs found. Create your first blog post!</p></div>';
                return;
            }

            let html = '<table><thead><tr><th>Title</th><th>Category</th><th>Status</th><th>Featured</th><th>Created</th><th>Actions</th></tr></thead><tbody>';

            allBlogs.forEach(blog => {
                const date = new Date(blog.created_at).toLocaleDateString();
                const statusClass = blog.status === 'published' ? 'published' : 'draft';
                const featured = blog.featured ? '<i class="fas fa-star" style="color: #ffc107;"></i>' : '-';

                html += `<tr>
                    <td><strong>${escapeHtml(blog.title)}</strong></td>
                    <td>${blog.category || '-'}</td>
                    <td><span class="status-badge ${statusClass}">${blog.status}</span></td>
                    <td style="text-align: center;">${featured}</td>
                    <td>${date}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn-edit" onclick="editBlog(${blog.id})">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="btn-delete" onclick="deleteBlog(${blog.id})">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </td>
                </tr>`;
            });

            html += '</tbody></table>';
            container.innerHTML = html;
        }

        // Open blog modal
        function openBlogModal() {
            currentBlogId = null;
            document.getElementById('modalTitle').textContent = 'Create New Blog';
            document.getElementById('blogForm').reset();
            document.getElementById('imagePreview').style.display = 'none';
            document.getElementById('blogContent').value = '';
            document.getElementById('blogModal').classList.add('show');
        }

        // Edit blog
        function editBlog(blogId) {
            fetch(`../backend/blog_api.php?action=get_blog&id=${blogId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const blog = data.data;
                        currentBlogId = blog.id;
                        document.getElementById('modalTitle').textContent = 'Edit Blog';
                        document.getElementById('blogId').value = blog.id;
                        document.getElementById('blogTitle').value = blog.title;
                        document.getElementById('blogCategory').value = blog.category || '';
                        document.getElementById('blogExcerpt').value = blog.excerpt || '';
                        document.getElementById('blogStatus').value = blog.status;
                        document.getElementById('blogFeatured').checked = blog.featured;
                        document.getElementById('blogContent').value = blog.content;

                        if (blog.featured_image) {
                            document.getElementById('imagePreview').src = '../' + blog.featured_image;
                            document.getElementById('imagePreview').style.display = 'block';
                        } else {
                            document.getElementById('imagePreview').style.display = 'none';
                        }

                        document.getElementById('blogModal').classList.add('show');
                    } else {
                        showError('Failed to load blog details');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('Error loading blog');
                });
        }

        // Save blog
        function saveBlog(e) {
            e.preventDefault();

            const formData = new FormData();
            formData.append('action', currentBlogId ? 'update_blog' : 'create_blog');
            formData.append('title', document.getElementById('blogTitle').value);
            formData.append('content', document.getElementById('blogContent').value);
            formData.append('excerpt', document.getElementById('blogExcerpt').value);
            formData.append('category', document.getElementById('blogCategory').value);
            formData.append('status', document.getElementById('blogStatus').value);
            formData.append('featured', document.getElementById('blogFeatured').checked ? 1 : 0);

            if (currentBlogId) {
                formData.append('id', currentBlogId);
            }

            const fileInput = document.getElementById('blogImage');
            if (fileInput.files.length > 0) {
                formData.append('featured_image', fileInput.files[0]);
            }

            document.getElementById('saveBlogBtn').disabled = true;
            document.getElementById('saveBlogBtn').textContent = 'Saving...';

            fetch('../backend/blog_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('saveBlogBtn').disabled = false;
                document.getElementById('saveBlogBtn').textContent = 'Save Blog';

                if (data.success) {
                    showSuccess(data.message);
                    closeBlogModal();
                    loadBlogs();
                } else {
                    showError(data.message);
                }
            })
            .catch(error => {
                document.getElementById('saveBlogBtn').disabled = false;
                document.getElementById('saveBlogBtn').textContent = 'Save Blog';
                console.error('Error:', error);
                showError('Error saving blog');
            });
        }

        // Delete blog
        function deleteBlog(blogId) {
            Swal.fire({
                title: 'Delete Blog?',
                text: 'This action cannot be undone!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74c3c',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = new FormData();
                    formData.append('action', 'delete_blog');
                    formData.append('id', blogId);

                    fetch('../backend/blog_api.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showSuccess('Blog deleted successfully');
                            loadBlogs();
                        } else {
                            showError(data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showError('Error deleting blog');
                    });
                }
            });
        }

        // Preview image
        function previewImage(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    document.getElementById('imagePreview').src = event.target.result;
                    document.getElementById('imagePreview').style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        }

        // Close blog modal
        function closeBlogModal() {
            document.getElementById('blogModal').classList.remove('show');
            currentBlogId = null;
        }

        // Logout
        function logout() {
            Swal.fire({
                title: 'Logout?',
                text: 'Are you sure you want to logout?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, logout'
            }).then((result) => {
                if (result.isConfirmed) {
                    localStorage.removeItem('adminData');
                    window.location.href = 'login.php';
                }
            });
        }

        // Show success message
        function showSuccess(message) {
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: message,
                timer: 3000
            });
        }

        // Show error message
        function showError(message) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }

        // Escape HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Toggle sidebar
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
        }

        // Close sidebar and modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('blogModal');
            const sidebar = document.getElementById('sidebar');
            const menuToggle = document.getElementById('menuToggle');

            // Close modal if clicking outside of it
            if (event.target === modal) {
                closeBlogModal();
            }

            // Close sidebar if clicking outside on mobile
            if (window.innerWidth <= 768) {
                if (!sidebar.contains(event.target) && !menuToggle.contains(event.target)) {
                    sidebar.classList.remove('active');
                }
            }
        }
    </script>
</body>

</html>
