<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config.php'; // adjust path to your DB connection
require_once __DIR__ . '/layout.php';  // includes auth + header + sidebar + topbar
require_once __DIR__ . '/includes/header.php';

$search = trim($_GET['search'] ?? '');

try {
    if ($search !== '') {
        $stmt = $pdo->prepare("
            SELECT 
                p.id,
                p.title, 
                p.tags, 
                p.slug,
                p.tagline,
                p.post_location, 
                p.featured,
                p.status,
                p.created_at
            FROM posts p
            LEFT JOIN post_locations pl ON p.post_location = pl.key_name
            WHERE 
                p.title LIKE ?
                OR p.tagline LIKE ?
                OR p.slug LIKE ?
                OR p.tags LIKE ?
                OR p.post_location LIKE ?
            ORDER BY p.created_at DESC
        ");

        $searchTerm = '%' . $search . '%';

        $stmt->execute([
            $searchTerm,
            $searchTerm,
            $searchTerm,
            $searchTerm,
            $searchTerm
        ]);
    } else {
        $stmt = $pdo->query("
            SELECT 
                p.id,
                p.title, 
                p.tags, 
                p.slug,
                p.tagline,
                p.post_location, 
                p.featured,
                p.status,
                p.created_at
            FROM posts p
            LEFT JOIN post_locations pl ON p.post_location = pl.key_name
            ORDER BY p.created_at DESC
        ");
    }

    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}
?>

<h1>All Posts</h1>

<div class="d-flex justify-content-between align-items-center mb-3 gap-3 flex-wrap">
  <form method="get" class="d-flex gap-2" style="max-width: 500px; width: 100%;">
    <input 
      type="text" 
      name="search" 
      class="form-control" 
      placeholder="Search posts..." 
      value="<?= htmlspecialchars($search) ?>"
    >

    <button type="submit" class="btn btn-sm btn-primary" style="width: 90px;">Search</button>

    <?php if ($search !== ''): ?>
      <a href="posts.php" class="btn btn-sm btn-outline-secondary" style="width: 80px;">Clear</a>
    <?php endif; ?>
  </form>

  <a href="create-post.php" class="btn btn-sm btn-success" style="width: 120px;">Create Post</a>
</div>

<?php if ($search !== ''): ?>
  <p class="text-muted">
    Showing results for: <strong><?= htmlspecialchars($search) ?></strong>
  </p>
<?php endif; ?>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Title</th>
            <th>Tag Line</th>
            <th>Tags</th>
            <th>Type</th>
            <th>Created</th>
            <th>Featured</th>
            <th>Status</th>
            <th>Edit</th>
            <th>View</th>            
        </tr>
    </thead>
    <tbody>
        <?php if (empty($posts)): ?>
            <tr>
                <td colspan="10" class="text-center">
                    <?= $search !== '' ? 'No posts found matching your search.' : 'No posts found.' ?>
                </td>
            </tr>
        <?php else: ?>
            <?php foreach ($posts as $post): ?>
<tr>

    <td>
        <?= !empty($post['title']) ? htmlspecialchars($post['title']) : '' ?>
    </td>

    <td>
        <?= !empty($post['tagline']) ? htmlspecialchars($post['tagline']) : '' ?>
    </td>

    <td>
        <?= !empty($post['tags']) ? htmlspecialchars($post['tags']) : '' ?>
    </td>

    <td>
        <?= !empty($post['post_location']) ? htmlspecialchars($post['post_location']) : '' ?>
    </td>

    <td>
        <?= !empty($post['created_at']) ? date('d M Y', strtotime($post['created_at'])) : '' ?>
    </td>

    <td>
        <?= !empty($post['featured']) ? 'Yes' : '' ?>
    </td>

    <td>

        <?php if (($post['status'] ?? '') === 'draft'): ?>

            <span class="badge bg-warning text-dark">
                Draft
            </span>

        <?php else: ?>

            <span class="badge bg-success">
                Published
            </span>

        <?php endif; ?>

    </td>

    <td>

        <a
            href="edit-post.php?id=<?= (int)$post['id'] ?>"
            class="btn btn-sm btn-primary"
        >
            Edit
        </a>

    </td>

    <td>

        <?php if (!empty($post['slug'])): ?>

            <a
                href="/site/<?= !empty($post['post_location']) ? urlencode($post['post_location']) . '/' : '' ?><?= urlencode($post['slug']) ?>"
                class="btn btn-sm btn-secondary"
                target="_blank"
            >
                View
            </a>

        <?php endif; ?>

    </td>

</tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>