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

// Add extra columns if they don't exist (MySQL 5.x compatible)
mysqli_report(MYSQLI_REPORT_OFF);
$db_name = $conn->query("SELECT DATABASE()")->fetch_row()[0];
$cols = [];
$res = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='$db_name' AND TABLE_NAME='blogs'");
while ($r = $res->fetch_assoc()) $cols[] = $r['COLUMN_NAME'];
if (!in_array('is_favorite', $cols)) $conn->query("ALTER TABLE blogs ADD COLUMN is_favorite TINYINT(1) NOT NULL DEFAULT 0");
if (!in_array('deleted_at',  $cols)) $conn->query("ALTER TABLE blogs ADD COLUMN deleted_at DATETIME DEFAULT NULL");
if (!in_array('status',      $cols)) $conn->query("ALTER TABLE blogs ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'published'");

$cols_services = [];
$res_services = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='$db_name' AND TABLE_NAME='services'");
while ($r = $res_services->fetch_assoc()) $cols_services[] = $r['COLUMN_NAME'];
if (!in_array('is_favorite', $cols_services)) $conn->query("ALTER TABLE services ADD COLUMN is_favorite TINYINT(1) NOT NULL DEFAULT 0");
if (!in_array('deleted_at',  $cols_services)) $conn->query("ALTER TABLE services ADD COLUMN deleted_at DATETIME DEFAULT NULL");
if (!in_array('status',      $cols_services)) $conn->query("ALTER TABLE services ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'published'");
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// ---- AJAX handlers ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $id = (int)$_POST['id'];
    $type = $_POST['type'] ?? 'blog';
    $table = ($type === 'services') ? 'services' : 'blogs';
    switch ($_POST['action']) {
        case 'favorite':
            $conn->query("UPDATE $table SET is_favorite = NOT is_favorite WHERE id = $id");
            $row = $conn->query("SELECT is_favorite FROM $table WHERE id = $id")->fetch_assoc();
            echo json_encode(['success' => true, 'is_favorite' => (bool)$row['is_favorite']]);
            break;
        case 'trash':
            $ok = $conn->query("UPDATE $table SET deleted_at = NOW() WHERE id = $id");
            if (!$ok) { echo json_encode(['success' => false, 'message' => $conn->error]); break; }
            echo json_encode(['success' => true]);
            break;
        case 'restore':
            $ok2 = $conn->query("UPDATE $table SET deleted_at = NULL WHERE id = $id");
            if (!$ok2) { echo json_encode(['success' => false, 'message' => $conn->error]); break; }
            echo json_encode(['success' => true]);
            break;
        case 'permanent_delete':
            $ok3 = $conn->query("DELETE FROM $table WHERE id = $id");
            if (!$ok3) { echo json_encode(['success' => false, 'message' => $conn->error]); break; }
            echo json_encode(['success' => true]);
            break;
    }
    exit;
}

// Toggle filter
$view = $_GET['view'] ?? 'active';
$search = $_GET['search'] ?? '';
$safeSearch = $conn->real_escape_string($search);

if ($view === 'trash') {
    $where = "deleted_at IS NOT NULL";
} elseif ($view === 'favorites') {
    $where = "deleted_at IS NULL AND is_favorite = 1";
} elseif ($view === 'pending') {
    $where = "deleted_at IS NULL AND status = 'draft'";
} else {
    $where = "deleted_at IS NULL";
}

if ($safeSearch) $where .= " AND title LIKE '%$safeSearch%'";
$blogsQuery = "SELECT id, title, content, image_url, created_at, deleted_at, is_favorite, status, 'blog' AS post_type FROM blogs WHERE $where";
$servicesQuery = "SELECT id, title, description AS content, image_url, created_at, deleted_at, is_favorite, status, 'services' AS post_type FROM services WHERE $where";

if ($view === 'blogs_only') {
    $unifiedQuery = "$blogsQuery ORDER BY created_at DESC";
} elseif ($view === 'services_only') {
    $unifiedQuery = "$servicesQuery ORDER BY created_at DESC";
} else {
    $unifiedQuery = "$blogsQuery UNION ALL $servicesQuery ORDER BY created_at DESC";
}

$blogs = $conn->query($unifiedQuery);

// Count badges
$trashCount   = $conn->query("SELECT SUM(c) AS c FROM (SELECT COUNT(*) c FROM blogs WHERE deleted_at IS NOT NULL UNION ALL SELECT COUNT(*) c FROM services WHERE deleted_at IS NOT NULL) t")->fetch_assoc()['c'];
$favCount     = $conn->query("SELECT SUM(c) AS c FROM (SELECT COUNT(*) c FROM blogs WHERE deleted_at IS NULL AND is_favorite = 1 UNION ALL SELECT COUNT(*) c FROM services WHERE deleted_at IS NULL AND is_favorite = 1) t")->fetch_assoc()['c'];
$activeCount  = $conn->query("SELECT SUM(c) AS c FROM (SELECT COUNT(*) c FROM blogs WHERE deleted_at IS NULL UNION ALL SELECT COUNT(*) c FROM services WHERE deleted_at IS NULL) t")->fetch_assoc()['c'];
$pendingCount = $conn->query("SELECT SUM(c) AS c FROM (SELECT COUNT(*) c FROM blogs WHERE deleted_at IS NULL AND status = 'draft' UNION ALL SELECT COUNT(*) c FROM services WHERE deleted_at IS NULL AND status = 'draft') t")->fetch_assoc()['c'];
$blogsOnlyCount    = $conn->query("SELECT COUNT(*) c FROM blogs WHERE deleted_at IS NULL")->fetch_assoc()['c'];
$servicesOnlyCount = $conn->query("SELECT COUNT(*) c FROM services WHERE deleted_at IS NULL")->fetch_assoc()['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Blogs & Services</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="dashboard.css">
</head>
<body>
<div class="d-flex">
    <!-- Sidebar -->
    <div class="sidebar d-flex flex-column flex-shrink-0 p-3 text-white" style="width: 280px;">
        <a href="dashboard.php" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
            <span class="fs-4">Admin Panel</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
            <li class="nav-item">
                <a href="dashboard.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a>
            </li>
            <li>
                <a href="manage_services.php"><i class="fas fa-tools me-2"></i> Manage Services</a>
            </li>
            <li>
                <a href="manage_pages.php"><i class="fas fa-file-alt me-2"></i> Manage Content</a>
            </li>
            <li>
                <a href="manage_blogs.php" class="active"><i class="fas fa-blog me-2"></i> Manage Blogs</a>
            </li>
            <li>
                <a href="job_applications.php"><i class="fas fa-briefcase me-2"></i> Job Applications</a>
            </li>
            <li>
                <a href="contact_messages.php"><i class="fas fa-envelope me-2"></i> Messages</a>
            </li>
            <li>
                <a href="wp/post.php"><i class="fas fa-pen me-2"></i> Add New Post</a>
            </li>
            <li>
                <a href="#"><i class="fas fa-newspaper me-2"></i> Blog</a>
            </li>
            <li>
                <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
            </li>
        </ul>
    </div>

    <!-- Main Content -->
    <div class="main-content w-100">

        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h4 class="mb-0 fw-bold">Manage Blogs</h4>
                <small class="text-muted"><?= $activeCount ?> posts published</small>
            </div>
            <a href="wp/post.php" class="btn btn-primary px-4">
                <i class="fas fa-plus me-2"></i>Add New Post
            </a>
        </div>

        <!-- Filter tabs + Search -->
        <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
            <div class="view-tabs">
                <a href="?view=active<?= $search ? '&search='.urlencode($search) : '' ?>" class="view-tab <?= $view === 'active' ? 'active' : '' ?>">
                    <i class="fas fa-list me-1"></i> All
                    <span class="badge bg-secondary ms-1"><?= $activeCount ?></span>
                </a>
                <a href="?view=favorites<?= $search ? '&search='.urlencode($search) : '' ?>" class="view-tab <?= $view === 'favorites' ? 'active' : '' ?>">
                    <i class="fas fa-star me-1"></i> Favorites
                    <?php if ($favCount > 0): ?><span class="badge bg-warning text-dark ms-1"><?= $favCount ?></span><?php endif; ?>
                </a>
                <a href="?view=pending<?= $search ? '&search='.urlencode($search) : '' ?>" class="view-tab <?= $view === 'pending' ? 'active' : '' ?>" style="border-color:#f59e0b; <?= $view==='pending'?'background:#f59e0b;color:white;':'' ?>">
                    <i class="fas fa-clock me-1"></i> Pending
                    <?php if ($pendingCount > 0): ?><span class="badge ms-1" style="background:<?= $view==='pending'?'white;color:#f59e0b':'#f59e0b' ?>"><?= $pendingCount ?></span><?php endif; ?>
                </a>
                <a href="?view=trash<?= $search ? '&search='.urlencode($search) : '' ?>" class="view-tab <?= $view === 'trash' ? 'active' : '' ?>">
                    <i class="fas fa-trash me-1"></i> Recycle Bin
                    <?php if ($trashCount > 0): ?><span class="badge bg-danger ms-1"><?= $trashCount ?></span><?php endif; ?>
                </a>
                <a href="?view=blogs_only<?= $search ? '&search='.urlencode($search) : '' ?>" class="view-tab <?= $view === 'blogs_only' ? 'active' : '' ?>">
                    <i class="fas fa-blog me-1"></i> Blog Posts
                    <span class="badge bg-primary ms-1"><?= $blogsOnlyCount ?></span>
                </a>
                <a href="?view=services_only<?= $search ? '&search='.urlencode($search) : '' ?>" class="view-tab <?= $view === 'services_only' ? 'active' : '' ?>">
                    <i class="fas fa-tools me-1"></i> Services Posts
                    <span class="badge bg-info text-dark ms-1"><?= $servicesOnlyCount ?></span>
                </a>
            </div>

            <form method="GET" class="search-box" style="width: 280px;">
                <input type="hidden" name="view" value="<?= htmlspecialchars($view) ?>">
                <i class="fas fa-search"></i>
                <input type="text" name="search" class="form-control" placeholder="Search posts…" value="<?= htmlspecialchars($search) ?>" id="searchInput">
            </form>
        </div>

        <!-- Table -->
        <div class="blog-table">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th style="width:40px"></th>
                        <th style="width:64px">Image</th>
                        <th>Title</th>
                        <th style="width:130px">Date</th>
                        <th style="width:170px">Actions</th>
                    </tr>
                </thead>
                <tbody id="blogsTable">
                <?php if ($blogs && $blogs->num_rows > 0):
                    while ($row = $blogs->fetch_assoc()):
                        $isFav = !empty($row['is_favorite']);
                        $inTrash = !empty($row['deleted_at']);
                ?>
                    <tr id="row-<?= $row['id'] ?>-<?= $row['post_type'] ?>">
                        <!-- Star -->
                        <td>
                            <button class="star-btn <?= $isFav ? 'favorited' : '' ?>"
                                onclick="toggleFavorite(<?= $row['id'] ?>, '<?= $row['post_type'] ?>', this)"
                                title="<?= $isFav ? 'Remove from favorites' : 'Mark as favorite' ?>">
                                <i class="<?= $isFav ? 'fas' : 'far' ?> fa-star"></i>
                            </button>
                        </td>
                        <!-- Thumbnail -->
                        <td>
                            <?php if ($row['image_url']): ?>
                                <img src="<?= htmlspecialchars($row['image_url']) ?>" alt="" class="blog-thumb">
                            <?php else: ?>
                                <div class="blog-thumb d-flex align-items-center justify-content-center bg-light text-muted" style="font-size:22px; border-radius:8px;">
                                    <i class="fas fa-image"></i>
                                </div>
                            <?php endif; ?>
                        </td>
                        <!-- Title + excerpt -->
                        <td class="blog-title-cell">
                            <p class="blog-title">
                                <?php if ($row['post_type'] === 'services'): ?>
                                    <span class="badge bg-info text-dark me-2">Service</span>
                                <?php else: ?>
                                    <span class="badge bg-primary me-2">Blog</span>
                                <?php endif; ?>
                                <?= htmlspecialchars($row['title']) ?>
                            </p>
                            <?php
                            $excerpt = '';
                            if (!empty($row['content'])) {
                                $decoded = json_decode($row['content'], true);
                                if ($decoded && isset($decoded['blocks'])) {
                                    foreach ($decoded['blocks'] as $block) {
                                        if (isset($block['data']['text']) && strlen($block['data']['text']) > 0) {
                                            $excerpt = strip_tags($block['data']['text']);
                                            break;
                                        }
                                    }
                                } else {
                                    $excerpt = strip_tags($row['content'] ?? '');
                                }
                            }
                            ?>
                            <?php if ($excerpt): ?>
                                <p class="blog-excerpt"><?= htmlspecialchars(mb_substr($excerpt, 0, 80)) ?></p>
                            <?php endif; ?>
                        </td>
                        <!-- Date -->
                        <td>
                            <span class="text-muted" style="font-size:13px;">
                                <?= date('d M Y', strtotime($row['created_at'])) ?>
                            </span>
                            <?php if ($inTrash): ?>
                                <br><small class="text-danger">Deleted <?= date('d M', strtotime($row['deleted_at'])) ?></small>
                            <?php endif; ?>
                        </td>
                        <!-- Actions -->
                        <td>
                        <div class="action-btns">
                            <?php if (!$inTrash): ?>
                                <!-- View Live -->
                                <?php if ($row['post_type'] === 'services'): ?>
                                    <a href="service-detail/<?= urlencode($row['title']) ?>" class="btn-icon-sm" style="color: #0d6efd; border-color: #0d6efd;" title="View Live" target="_blank">
                                        <i class="fas fa-external-link-alt"></i>
                                    </a>
                                <?php else: ?>
                                    <a href="blog_post/<?= urlencode($row['title']) ?>" class="btn-icon-sm" style="color: #0d6efd; border-color: #0d6efd;" title="View Live" target="_blank">
                                        <i class="fas fa-external-link-alt"></i>
                                    </a>
                                <?php endif; ?>
                                
                                <!-- Edit -->
                                <a href="wp/post.php?edit=<?= $row['id'] ?>&type=<?= $row['post_type'] ?>"
                                   class="btn-icon-sm edit"
                                   title="Edit post">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <!-- Trash -->
                                <button type="button" class="btn-icon-sm trash"
                                        onclick="trashBlog(<?= $row['id'] ?>, '<?= $row['post_type'] ?>')"
                                        title="Move to trash">
                                    <i class="fas fa-trash"></i>
                                </button>
                            <?php else: ?>
                                <!-- Restore -->
                                <button type="button" class="btn-icon-sm restore"
                                        onclick="restoreBlog(<?= $row['id'] ?>, '<?= $row['post_type'] ?>')"
                                        title="Restore post">
                                    <i class="fas fa-undo"></i>
                                </button>
                                <!-- Permanent Delete -->
                                <button type="button" class="btn-icon-sm danger"
                                        onclick="permanentDelete(<?= $row['id'] ?>, '<?= $row['post_type'] ?>')"
                                        title="Delete permanently">
                                    <i class="fas fa-times"></i>
                                </button>
                            <?php endif; ?>
                        </div>
                            </div>
                        </td>
                    </tr>
                <?php endwhile; else: ?>
                    <tr>
                        <td colspan="5">
                            <div class="empty-state">
                                <i class="fas <?= $view === 'trash' ? 'fa-trash' : ($view === 'favorites' ? 'fa-star' : 'fa-edit') ?>"></i>
                                <?php if ($view === 'trash'): ?>
                                    Recycle bin is empty.
                                <?php elseif ($view === 'favorites'): ?>
                                    No favorite posts yet. Click the ⭐ star on any post to mark it.
                                <?php elseif ($search): ?>
                                    No results for "<strong><?= htmlspecialchars($search) ?></strong>"
                                <?php else: ?>
                                    No posts yet. <a href="wp/post.php">Create your first post →</a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>

<!-- Toast -->
<div id="toast"></div>

<!-- Custom Confirm Modal -->
<div class="modal-overlay" id="confirmModal">
    <div class="modal-box">
        <h5 id="modalTitle">Are you sure?</h5>
        <p id="modalMsg">This action cannot be undone.</p>
        <div class="modal-actions">
            <button class="modal-btn cancel" onclick="closeModal()">Cancel</button>
            <button class="modal-btn" id="modalConfirmBtn" onclick="modalCallback()">Confirm</button>
        </div>
    </div>
</div>

<script>
var _modalCb = null;

function confirmModal(title, msg, btnClass, cb) {
    document.getElementById('modalTitle').textContent  = title;
    document.getElementById('modalMsg').textContent    = msg;
    var btn = document.getElementById('modalConfirmBtn');
    btn.className = 'modal-btn ' + btnClass;
    btn.textContent = title;
    _modalCb = cb;
    document.getElementById('confirmModal').classList.add('show');
}
function closeModal() {
    document.getElementById('confirmModal').classList.remove('show');
    _modalCb = null;
}
function modalCallback() {
    var cb = _modalCb;
    closeModal();
    if (cb) cb();
}
// Close on overlay click
document.getElementById('confirmModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});
function toast(msg, type) {
    var c = document.getElementById('toast');
    var d = document.createElement('div');
    d.className = 'toast-msg ' + (type || '');
    d.textContent = msg;
    c.appendChild(d);
    setTimeout(function() { d.remove(); }, 3000);
}

function toggleFavorite(id, type, btn) {
    fetch('manage_blogs.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=favorite&id=' + id + '&type=' + type
    }).then(r => r.json()).then(function(data) {
        if (data.success) {
            var icon = btn.querySelector('i');
            if (data.is_favorite) {
                btn.classList.add('favorited');
                icon.className = 'fas fa-star';
                btn.title = 'Remove from favorites';
                toast('Added to favorites ⭐', 'success');
            } else {
                btn.classList.remove('favorited');
                icon.className = 'far fa-star';
                btn.title = 'Mark as favorite';
                toast('Removed from favorites', '');
            }
        }
    });
}

function trashBlog(id, type) {
    confirmModal('Move to Trash', 'Move this post to the recycle bin?', 'confirm-trash', function() {
        fetch('manage_blogs.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=trash&id=' + id + '&type=' + type
        }).then(function(r) { return r.json(); }).then(function(data) {
            if (data.success) {
                var row = document.getElementById('row-' + id + '-' + type);
                row.classList.add('removing');
                setTimeout(function() { row.remove(); }, 300);
                toast('Post moved to trash 🗑️', '');
            } else {
                toast('Error: ' + (data.message || 'Could not trash post'), 'error');
            }
        }).catch(function(e) { toast('Network error: ' + e.message, 'error'); });
    });
}

function restoreBlog(id, type) {
    fetch('manage_blogs.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=restore&id=' + id + '&type=' + type
    }).then(function(r) { return r.json(); }).then(function(data) {
        if (data.success) {
            var row = document.getElementById('row-' + id + '-' + type);
            row.classList.add('removing');
            setTimeout(function() { row.remove(); }, 300);
            toast('Post restored ✅', 'success');
        } else {
            toast('Error: ' + (data.message || 'Could not restore post'), 'error');
        }
    }).catch(function(e) { toast('Network error: ' + e.message, 'error'); });
}

function permanentDelete(id, type) {
    confirmModal('Delete Forever', 'Permanently delete this post? This cannot be undone.', 'confirm-delete', function() {
        fetch('manage_blogs.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=permanent_delete&id=' + id + '&type=' + type
        }).then(function(r) { return r.json(); }).then(function(data) {
            if (data.success) {
                var row = document.getElementById('row-' + id + '-' + type);
                row.classList.add('removing');
                setTimeout(function() { row.remove(); }, 300);
                toast('Post permanently deleted', 'error');
            } else {
                toast('Error: ' + (data.message || 'Could not delete post'), 'error');
            }
        }).catch(function(e) { toast('Network error: ' + e.message, 'error'); });
    });
}

// Live search with debounce
var searchTimer;
document.getElementById('searchInput').addEventListener('input', function() {
    clearTimeout(searchTimer);
    var q = this.value;
    searchTimer = setTimeout(function() {
        var url = new URL(window.location.href);
        if (q) url.searchParams.set('search', q);
        else url.searchParams.delete('search');
        window.location.href = url.toString();
    }, 500);
});
</script>

</body>
</html>
