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

// ----------------------
// CONFIG + LAYOUT
// ----------------------
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/layout.php';

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

// ----------------------
// TYPE MAP
// ----------------------
$typeMap = [
    1 => 'news',
    2 => 'article',
    3 => 'guide',
    4 => 'blog',
    'news' => 'news',
    'article' => 'article',
    'guide' => 'guide',
    'blog' => '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 = (int)$metaStmt->fetchColumn();

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

$missingImages = (int)$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 4
");

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

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

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

// ----------------------
// GREETING
// ----------------------
$hour = (int)date('H');

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

function getPostUrl(array $post, array $typeMap): string
{
    $postLocation = $post['post_location'] ?? '';
    $postType = $typeMap[$postLocation] ?? 'article';

    if (empty($post['slug'])) {
        return '#';
    }

    return '/' . $postType . '/' . rawurlencode($post['slug']);
}
?>

<div class="dashboard-page">

    <div id="tsGenerateLoader" class="ts-generate-loader">
        <div class="ts-generate-loader-content">
            <div class="ts-loader-spinner"></div>

            <h4>Generating Article</h4>

            <p>
                Please wait whilst the article builds.
            </p>
        </div>
    </div>

    <section class="dashboard-hero">
        <div class="dashboard-hero-main">
            <div class="dashboard-greeting-icon">
                <?= htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') ?>
            </div>

            <div>
                <p class="dashboard-kicker">
                    ThrillSense Newsdesk
                </p>

                <h1>
                    <?= htmlspecialchars($greeting, ENT_QUOTES, 'UTF-8') ?>, <?= htmlspecialchars($username, ENT_QUOTES, 'UTF-8') ?>
                </h1>

                <p>
                    Here’s what is happening across content, alerts and performance.
                </p>
            </div>
        </div>

        <div class="dashboard-hero-actions">
            <a href="/admin/create-post" class="btn btn-dark">
                Create Post
            </a>

            <a href="/admin/posts" class="btn btn-outline-secondary">
                View Posts
            </a>
        </div>
    </section>

    <?php if (!empty($mediaAlerts)): ?>
        <section class="dashboard-ticker-card">

            <div id="mediaTicker" class="dashboard-ticker">
                <?php foreach ($mediaAlerts as $index => $alert): ?>

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

                    <div
                        class="media-alert-item dashboard-ticker-item"
                        style="<?= $index !== 0 ? 'display:none;' : '' ?>"
                    >
                        <div class="dashboard-ticker-content">
                            <div class="dashboard-ticker-badges">
                                <?php if ($isBreaking): ?>
                                    <span class="dashboard-alert-badge dashboard-alert-breaking">
                                        Breaking
                                    </span>
                                <?php elseif ($isNew): ?>
                                    <span class="dashboard-alert-badge dashboard-alert-new">
                                        New
                                    </span>
                                <?php endif; ?>
                            </div>

                            <div class="dashboard-ticker-copy">
                                <span class="dashboard-ticker-date">
                                    <?= htmlspecialchars(date('d/m/Y', $publishedTime), ENT_QUOTES, 'UTF-8') ?>
                                </span>

                                <strong>
                                    <?= htmlspecialchars($alert['source_name'], ENT_QUOTES, 'UTF-8') ?>
                                </strong>

                                <a
                                    href="<?= htmlspecialchars($alert['url'], ENT_QUOTES, 'UTF-8') ?>"
                                    target="_blank"
                                    rel="noopener"
                                >
                                    <?= htmlspecialchars($alert['title'], ENT_QUOTES, 'UTF-8') ?>
                                </a>
                            </div>
                        </div>

                        <a
                            href="/admin/generate-draft.php?id=<?= (int)$alert['id'] ?>"
                            class="btn btn-sm btn-dark generate-draft-btn dashboard-ticker-button"
                        >
                            Generate Draft
                        </a>
                    </div>

                <?php endforeach; ?>
            </div>
        </section>
    <?php endif; ?>

    <section class="dashboard-grid">

        <article class="dashboard-panel dashboard-panel-wide">
            <div class="dashboard-panel-header">
                <div>
                    <h2 class="dashboard-panel-kicker">
                        Latest Published
                    </h2>
                </div>

                <a href="/admin/posts?status=published" class="dashboard-panel-link">
                    View all
                </a>
            </div>

            <?php if (!empty($recentPosts)): ?>
                <div class="dashboard-latest-list">
                    <?php foreach ($recentPosts as $index => $post): ?>
                        <a
                            href="<?= htmlspecialchars(getPostUrl($post, $typeMap), ENT_QUOTES, 'UTF-8') ?>"
                            target="_blank"
                            rel="noopener"
                            class="dashboard-latest-item"
                        >
                            <span class="dashboard-list-number">
                                <?= (int)($index + 1) ?>
                            </span>

                            <span>
                                <?= htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="dashboard-empty-text">
                    No recent articles yet.
                </p>
            <?php endif; ?>
        </article>

        <article class="dashboard-panel">
            <div class="dashboard-panel-header">
                <div>
                    <p class="dashboard-panel-kicker">
                        Contributors
                    </p>

                    <h2>
                        Top Contributors
                    </h2>
                </div>
            </div>

            <?php if (!empty($topAuthors)): ?>
                <div class="dashboard-ranked-list">
                    <?php foreach ($topAuthors as $index => $author): ?>
                        <div class="dashboard-ranked-item">
                            <span class="dashboard-list-number">
                                <?= (int)($index + 1) ?>
                            </span>

                            <div>
                                <strong>
                                    <?= htmlspecialchars($author['display_name'] ?: $author['username'], ENT_QUOTES, 'UTF-8') ?>
                                </strong>

                                <span>
                                    <?= (int)$author['post_count'] ?> posts published
                                </span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="dashboard-empty-text">
                    No contributor data yet.
                </p>
            <?php endif; ?>
        </article>

        <article class="dashboard-panel">
            <div class="dashboard-panel-header">
                <div>
                    <p class="dashboard-panel-kicker">
                        Performance
                    </p>

                    <h2>
                        Top Posts
                    </h2>
                </div>
            </div>

            <?php if (!empty($topPosts)): ?>
                <div class="dashboard-ranked-list">
                    <?php foreach ($topPosts as $index => $post): ?>

                        <?php
                        $totalViews = (int)$post['total_views'];

                        $fireEmoji = '';

                        if ($totalViews > 1000) {
                            $fireEmoji = '🔥🔥🔥';
                        } elseif ($totalViews > 750) {
                            $fireEmoji = '🔥🔥';
                        } elseif ($totalViews > 500) {
                            $fireEmoji = '🔥';
                        }
                        ?>

                        <a
                            href="<?= htmlspecialchars(getPostUrl($post, $typeMap), ENT_QUOTES, 'UTF-8') ?>"
                            target="_blank"
                            rel="noopener"
                            class="dashboard-ranked-item dashboard-ranked-link"
                        >
                            <span class="dashboard-list-number">
                                <?= (int)($index + 1) ?>
                            </span>

                            <div>
                                <strong>
                                    <?= htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8') ?>
                                    <?= $fireEmoji ?>
                                </strong>

<?php /*
<span>
    <?= number_format($totalViews) ?> views
</span>
*/ ?>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="dashboard-empty-text">
                    No post data yet.
                </p>
            <?php endif; ?>
        </article>

        <article class="dashboard-panel">
            <div class="dashboard-panel-header">
                <div>
                    <p class="dashboard-panel-kicker">
                        Checks
                    </p>

                    <h2>
                        Content Health
                    </h2>
                </div>
            </div>

            <div class="dashboard-health-list">
                <div class="dashboard-health-item <?= $missingMeta > 0 ? 'needs-attention' : '' ?>">
                    <span>
                        <?= (int)$missingMeta ?>
                    </span>

                    <p>
                        posts missing meta descriptions
                    </p>
                </div>

                <div class="dashboard-health-item <?= $missingImages > 0 ? 'needs-attention' : '' ?>">
                    <span>
                        <?= (int)$missingImages ?>
                    </span>

                    <p>
                        posts missing featured images
                    </p>
                </div>
            </div>
        </article>

    </section>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const items = document.querySelectorAll('.media-alert-item');
    const ticker = document.getElementById('mediaTicker');

    let current = 0;
    let interval;

    if (!ticker || items.length <= 1) {
        return;
    }

    function startTicker() {
        stopTicker();

        interval = setInterval(function () {
            items[current].style.display = 'none';

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

            items[current].style.display = 'flex';
        }, 4500);
    }

    function stopTicker() {
        if (interval) {
            clearInterval(interval);
        }
    }

    startTicker();

    ticker.addEventListener('mouseenter', stopTicker);
    ticker.addEventListener('mouseleave', startTicker);
    ticker.addEventListener('focusin', stopTicker);
    ticker.addEventListener('focusout', startTicker);
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const generateButtons = document.querySelectorAll('.generate-draft-btn');
    const loader = document.getElementById('tsGenerateLoader');

    if (!loader) {
        return;
    }

    generateButtons.forEach(function (button) {
        button.addEventListener('click', function () {
            loader.style.display = 'flex';
        });
    });
});
</script>

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