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

session_start();

// ----------------------
// AUTH CHECK
// ----------------------
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$username = $_SESSION['admin_username'] ?? 'Admin';

// ----------------------
// CONFIG
// ----------------------
require_once __DIR__ . '/../config.php';

// ----------------------
// HEADER + LAYOUT
// ----------------------
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';

// ----------------------
// TYPE MAP
// ----------------------
$typeMap = [
    1 => 'news',
    2 => 'article',
    3 => 'guide',
    4 => 'blog'
];

// ----------------------
// MEDIA ALERTS
// ----------------------
$mediaAlertsStmt = $pdo->query("
SELECT id, title, url, published_at, source_name
FROM media_alerts
    ORDER BY published_at DESC
    LIMIT 10
");

$mediaAlerts = $mediaAlertsStmt->fetchAll(PDO::FETCH_ASSOC);

// ----------------------
// MISSING META DESCRIPTIONS
// ----------------------
$metaStmt = $pdo->query("
    SELECT COUNT(*) 
    FROM posts
    WHERE meta_description IS NULL
    OR meta_description = ''
");

$missingMeta = $metaStmt->fetchColumn();

// ----------------------
// MISSING FEATURED IMAGES
// ----------------------
$missingImageStmt = $pdo->query("
    SELECT COUNT(*)
    FROM posts
    WHERE image_path IS NULL
    OR image_path = ''
");

$missingImages = $missingImageStmt->fetchColumn();

// ----------------------
// TOP POSTS
// ----------------------
$topPostsStmt = $pdo->query("
    SELECT 
        posts.title,
        posts.slug,
        posts.post_location,
        COUNT(page_views.id) as total_views
    FROM page_views
    JOIN posts ON posts.id = page_views.post_id
    GROUP BY posts.id
    ORDER BY total_views DESC
    LIMIT 5
");

$topPosts = $topPostsStmt->fetchAll(PDO::FETCH_ASSOC);

// ----------------------
// TOP AUTHORS
// ----------------------
$topAuthorsStmt = $pdo->query("
    SELECT 
        admin_users.display_name,
        admin_users.username,
        COUNT(posts.id) as post_count
    FROM posts
    JOIN admin_users ON posts.created_by = admin_users.id
    GROUP BY admin_users.id
    ORDER BY post_count DESC
    LIMIT 3
");

$topAuthors = $topAuthorsStmt->fetchAll(PDO::FETCH_ASSOC);

// ----------------------
// RECENT ARTICLES
// ----------------------
$recentPostsStmt = $pdo->query("
    SELECT 
        title,
        slug,
        post_location
    FROM posts
    ORDER BY created_at DESC
    LIMIT 3
");

$recentPosts = $recentPostsStmt->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="container">

<?php

$hour = (int) date('H');

if ($hour < 12) {
    $greeting = 'Good Morning';
    $icon = '☀️';
} elseif ($hour < 17) {
    $greeting = 'Good Afternoon';
    $icon = '🌤️';
} else {
    $greeting = 'Good Evening';
    $icon = '🌙';
}

?>

<div class="text-dark d-flex align-items-center gap-2 mb-3">

    <span style="font-size: 1.8rem;">
        <?= $icon ?>
    </span>

    <h2 class="mb-0">
        <?= $greeting ?>, <?= htmlspecialchars($username) ?>
    </h2>

</div>

<!-- MEDIA ALERT TICKER -->
<?php if (!empty($mediaAlerts)): ?>

<div class="card shadow-sm border-0 mb-4">

    <div class="card-body py-2 px-3">

        <div 
            id="mediaTicker"
            class="d-flex align-items-center"
            style="
                min-height: 24px;
                font-size: 0.95rem;
                font-weight: 500;
            "
        >

            <?php foreach ($mediaAlerts as $index => $alert): ?>

                <?php
                $isNew = strtotime($alert['published_at']) >= strtotime('-3 days');
                $isBreaking = date('Y-m-d', strtotime($alert['published_at'])) === date('Y-m-d');

                ?>


                <div 
                    class="media-alert-item"
                    style="<?= $index !== 0 ? 'display:none;' : '' ?>"
                >

                    <?php if ($isNew): ?>

                        <span class="badge bg-danger me-2">
                            NEW
                        </span>

                    <?php endif; ?>
                    
                    <?php if ($isBreaking): ?>

                        <span class="badge bg-danger me-2">
                            BREAKING
                        </span>

                    <?php endif; ?>
                    

                    <span class="text-muted me-2">
                        <?= date('d/m/Y', strtotime($alert['published_at'])) ?>:
                    </span>
                    
                                        <span class="fw-semibold me-2">
 <?= htmlspecialchars($alert['source_name']) ?> &nbsp;-</span><a 
    href="<?= htmlspecialchars($alert['url']) ?>"
    target="_blank"
    class="text-dark text-decoration-none"
><?= htmlspecialchars($alert['title']) ?>
</a>

<a 
    href="/admin/generate-draft.php?id=<?= (int)$alert['id'] ?>"
    class="btn btn-sm btn-dark ms-3 py-0 px-2" style="color: #FFF !important"
>
    Generate Draft
</a>
                </div>

            <?php endforeach; ?>

        </div>

    </div>

</div>

<?php endif; ?>

<div class="row g-4">

    <!-- RECENT ARTICLES -->
    <div class="col-12">
        <div class="card shadow-sm border-0">
            <div class="card-body">

                <h5 class="mb-4">📰 Latest Published</h5>

                <?php if (!empty($recentPosts)): ?>

                    <div class="row">

                        <?php foreach ($recentPosts as $index => $post): ?>

                            <?php
                            $postType = $typeMap[$post['post_location']] ?? 'article';
                            ?>

                            <div class="col-md-4 mb-3">

                                <a 
                                    href="/<?= $postType ?>/<?= htmlspecialchars($post['slug']) ?>"
                                    target="_blank"
                                    class="text-decoration-none text-dark"
                                >

                                    <div class="d-flex align-items-start gap-2">

                                        <span class="fw-bold text-muted">
                                            #<?= $index + 1 ?>
                                        </span>

                                        <span style="font-size: 0.95rem; line-height: 1.4;">
                                            <?= htmlspecialchars($post['title']) ?>
                                        </span>

                                    </div>

                                </a>

                            </div>

                        <?php endforeach; ?>

                    </div>

                <?php else: ?>

                    <p>No recent articles yet.</p>

                <?php endif; ?>

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

    <!-- TOP AUTHORS -->
    <div class="col-md-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">

                <h5 class="mb-3">✍️ Top Contributors</h5>

                <?php if (!empty($topAuthors)): ?>

                    <ul class="list-unstyled mb-2">

                        <?php foreach ($topAuthors as $index => $author): ?>

                            <li class="mb-3">

                                <strong>
                                    #<?= $index + 1 ?>

                                    <?= htmlspecialchars(
                                        $author['display_name']
                                        ?: $author['username']
                                    ) ?>
                                </strong>

                                <br>

                                <small class="text-muted">
                                    <?= $author['post_count'] ?> posts published
                                </small>

                            </li>

                        <?php endforeach; ?>

                    </ul>

                <?php else: ?>

                    <p>No contributor data yet.</p>

                <?php endif; ?>

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

    <!-- TOP POSTS -->
    <div class="col-md-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">

                <h5 class="mb-3">🔥 Top Performing Posts</h5>

                <?php if (!empty($topPosts)): ?>

                    <ul class="list-unstyled mb-0">

                        <?php foreach ($topPosts as $index => $post): ?>

                            <?php
                            $postType = $typeMap[$post['post_location']] ?? 'article';
                            ?>

                            <li class="mb-3 d-flex align-items-start gap-2">

                                <span class="text-muted fw-bold">
                                    •
                                </span>

                                <a 
                                    href="/<?= $postType ?>/<?= htmlspecialchars($post['slug']) ?>"
                                    target="_blank"
                                    class="text-decoration-none text-dark"
                                    style="line-height: 1.4;"
                                >
                                    <?= htmlspecialchars($post['title']) ?>
                                </a>

                            </li>

                        <?php endforeach; ?>

                    </ul>

                <?php else: ?>

                    <p>No post data yet.</p>

                <?php endif; ?>

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

    <!-- CONTENT HEALTH -->
    <div class="col-md-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">

                <h5 class="mb-3">⚠️ Content Health</h5>

                <ul class="list-unstyled mb-0">

                    <li class="mb-2">
                        <?= $missingMeta ?> posts missing meta descriptions
                    </li>

                    <li>
                        <?= $missingImages ?> posts missing featured images
                    </li>

                </ul>

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

</div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {

    const items = document.querySelectorAll('.media-alert-item');

    let current = 0;

    if (items.length <= 1) return;

    setInterval(() => {

        items[current].style.display = 'none';

        current = (current + 1) % items.length;

        items[current].style.display = 'block';

    }, 4000);

});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>