<?php
/**
 * Resource Detail View
 * Shows a single educational resource with embedded viewer, ratings, and related links.
 */
$typeIconMap = [
    'pdf'          => ['icon' => 'fa-file-pdf', 'color' => 'danger'],
    'video'        => ['icon' => 'fa-play-circle', 'color' => 'primary'],
    'article'      => ['icon' => 'fa-newspaper', 'color' => 'info'],
    'guide'        => ['icon' => 'fa-map', 'color' => 'secondary'],
    'checklist'    => ['icon' => 'fa-list-check', 'color' => 'success'],
    'template'     => ['icon' => 'fa-file-code', 'color' => 'warning'],
    'tip'          => ['icon' => 'fa-lightbulb', 'color' => 'primary'],
];
$typeIcon = $typeIconMap[$resource['category']] ?? ['icon' => 'fa-file', 'color' => 'secondary'];
?>
<div class="container py-4">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="<?= APP_URL ?>/resources" class="text-decoration-none text-primary">Resources</a></li>
            <li class="breadcrumb-item active text-muted"><?= htmlspecialchars($resource['title']) ?></li>
        </ol>
    </nav>

    <div class="row g-4">
        <!-- Main Content -->
        <div class="col-lg-8">
            <!-- Header -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center gap-3 mb-3">
                        <div class="badge-icon-box bg-<?= $typeIcon['color'] ?>-subtle text-<?= $typeIcon['color'] ?> rounded-3 flex-shrink-0" style="width:56px;height:56px;display:flex;align-items:center;justify-content:center;">
                            <i class="fa-solid <?= $typeIcon['icon'] ?> fs-3"></i>
                        </div>
                        <div>
                            <span class="badge bg-<?= $typeIcon['color'] ?>-subtle text-<?= $typeIcon['color'] ?> rounded-pill font-outfit fw-bold text-xs mb-1"><?= ucfirst($resource['category']) ?></span>
                            <h2 class="fw-bold font-outfit text-dark mb-0"><?= htmlspecialchars($resource['title']) ?></h2>
                        </div>
                    </div>
                    <p class="text-muted mb-4"><?= htmlspecialchars($resource['description']) ?></p>
                    <div class="d-flex flex-wrap gap-2 mb-3">
                        <?php if (!empty($resource['module'])): ?>
                            <span class="badge bg-primary-subtle text-primary rounded-pill px-3"><?= ucfirst(str_replace('_', ' ', $resource['module'])) ?></span>
                        <?php endif; ?>
                        <?php foreach (json_decode($resource['tags'] ?? '[]', true) ?? [] as $tag): ?>
                            <span class="badge bg-secondary-subtle text-secondary rounded-pill px-3"><?= htmlspecialchars($tag) ?></span>
                        <?php endforeach; ?>
                    </div>
                    <div class="d-flex gap-3 mt-4 flex-wrap">
                        <?php if (!empty($resource['external_url'])): ?>
                            <a href="<?= htmlspecialchars($resource['external_url']) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-primary rounded-pill px-4 fw-bold font-outfit">
                                <i class="fa-solid fa-external-link me-2"></i>Open Resource
                            </a>
                        <?php endif; ?>
                        <?php if (!empty($resource['file_path'])): ?>
                            <a href="<?= APP_URL ?>/resources/<?= $resource['slug'] ?>/download" class="btn btn-outline-success rounded-pill px-4 fw-bold font-outfit">
                                <i class="fa-solid fa-download me-2"></i>Download
                            </a>
                        <?php endif; ?>
                        <button class="btn btn-outline-secondary rounded-pill px-4 font-outfit fw-bold" id="btn-bookmark" data-id="<?= $resource['id'] ?>">
                            <i class="fa-<?= $resource['is_bookmarked'] ?? false ? 'solid' : 'regular' ?> fa-bookmark me-2"></i><?= $resource['is_bookmarked'] ?? false ? 'Saved' : 'Save' ?>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Resource Viewer -->
            <?php if ($resource['category'] === 'video' && !empty($resource['external_url'])): ?>
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-body p-0 rounded-3 overflow-hidden">
                        <?php
                        // Embed YouTube or other video
                        $embedUrl = $resource['external_url'];
                        if (preg_match('/youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/', $embedUrl, $m)) {
                            $embedUrl = 'https://www.youtube.com/embed/' . $m[1];
                        } elseif (preg_match('/youtu\.be\/([a-zA-Z0-9_-]+)/', $embedUrl, $m)) {
                            $embedUrl = 'https://www.youtube.com/embed/' . $m[1];
                        }
                        ?>
                        <div class="ratio ratio-16x9">
                            <iframe src="<?= htmlspecialchars($embedUrl) ?>" allowfullscreen class="w-100 border-0"></iframe>
                        </div>
                    </div>
                </div>
            <?php elseif ($resource['category'] === 'pdf' && !empty($resource['file_path'])): ?>
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-body p-0 rounded-3 overflow-hidden">
                        <div style="height: 550px;">
                            <embed src="<?= UPLOAD_URL ?>/resources/<?= htmlspecialchars($resource['file_path']) ?>" type="application/pdf" class="w-100 h-100">
                        </div>
                    </div>
                </div>
            <?php elseif (!empty($resource['content'])): ?>
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-body p-4">
                        <div class="text-muted lh-lg resource-content"><?= $resource['content_html'] ?? nl2br(htmlspecialchars($resource['content'])) ?></div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Rating Widget -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-3">Rate This Resource</h6>
                    <form action="<?= APP_URL ?>/resources/<?= $resource['id'] ?>/rate" method="POST" class="d-flex align-items-center gap-3">
                        <?= csrf_field() ?>
                        <div class="star-rating d-flex gap-1" id="star-rating-container">
                            <?php for ($star = 1; $star <= 5; $star++): ?>
                                <button type="button" class="star-btn btn btn-link p-0 fs-4 text-<?= ($resource['user_rating'] ?? 0) >= $star ? 'warning' : 'secondary' ?>" data-value="<?= $star ?>">
                                    <i class="fa-<?= ($resource['user_rating'] ?? 0) >= $star ? 'solid' : 'regular' ?> fa-star"></i>
                                </button>
                            <?php endfor; ?>
                        </div>
                        <input type="hidden" name="rating" id="rating-input" value="<?= $resource['user_rating'] ?? 0 ?>">
                        <button type="submit" class="btn btn-sm btn-primary rounded-pill px-3 font-outfit fw-bold">Submit</button>
                        <div class="text-muted text-sm">
                            Avg: <strong class="text-dark"><?= number_format($resource['avg_rating'] ?? 0, 1) ?></strong> 
                            (<?= $resource['rating_count'] ?? 0 ?> ratings)
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Resource Meta -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-3"><i class="fa-solid fa-info-circle text-info me-2"></i>Resource Details</h6>
                    <ul class="list-unstyled mb-0 text-sm">
                        <?php if (!empty($resource['uploaded_by']) || !empty($resource['first_name'])): ?>
                        <li class="d-flex justify-content-between py-2 border-bottom">
                            <span class="text-muted">Added by</span>
                            <span class="fw-bold text-dark"><?= htmlspecialchars($resource['first_name'] ?? '') ?> <?= htmlspecialchars($resource['last_name'] ?? '') ?></span>
                        </li>
                        <?php endif; ?>
                        <li class="d-flex justify-content-between py-2 border-bottom">
                            <span class="text-muted">Category</span>
                            <span class="fw-bold text-<?= $typeIcon['color'] ?>"><?= ucfirst($resource['category']) ?></span>
                        </li>
                        <?php if (!empty($resource['file_size'])): ?>
                        <li class="d-flex justify-content-between py-2 border-bottom">
                            <span class="text-muted">File Size</span>
                            <span class="fw-bold text-dark"><?= $resource['file_size'] ?></span>
                        </li>
                        <?php endif; ?>
                        <li class="d-flex justify-content-between py-2 border-bottom">
                            <span class="text-muted">Views</span>
                            <span class="fw-bold text-dark"><?= number_format($resource['views'] ?? 0) ?></span>
                        </li>
                        <li class="d-flex justify-content-between py-2">
                            <span class="text-muted">Added</span>
                            <span class="fw-bold text-dark"><?= formatDate($resource['created_at']) ?></span>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- Related Resources -->
            <?php if (!empty($relatedResources)): ?>
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-3"><i class="fa-solid fa-link text-primary me-2"></i>Related Resources</h6>
                    <?php foreach ($relatedResources as $rel): 
                        $relTypeIcon = $typeIconMap[$rel['category']] ?? ['icon' => 'fa-file', 'color' => 'secondary'];
                    ?>
                        <a href="<?= APP_URL ?>/resources/<?= $rel['slug'] ?>" class="text-decoration-none">
                            <div class="d-flex align-items-center gap-3 mb-3">
                                <div class="badge-icon-box bg-<?= $relTypeIcon['color'] ?>-subtle text-<?= $relTypeIcon['color'] ?> rounded-circle flex-shrink-0" style="width:36px;height:36px;display:flex;align-items:center;justify-content:center;">
                                    <i class="fa-solid <?= $relTypeIcon['icon'] ?> text-xs"></i>
                                </div>
                                <div class="flex-grow-1 min-w-0">
                                    <span class="text-dark fw-bold font-outfit text-sm d-block text-truncate"><?= htmlspecialchars($rel['title']) ?></span>
                                    <small class="text-muted text-xs"><?= ucfirst($rel['category']) ?></small>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const stars = document.querySelectorAll('.star-btn');
    const ratingInput = document.getElementById('rating-input');
    stars.forEach(btn => {
        btn.addEventListener('mouseenter', function () {
            const val = parseInt(this.dataset.value);
            stars.forEach((s, i) => {
                const icon = s.querySelector('i');
                if (i < val) { s.classList.add('text-warning'); s.classList.remove('text-secondary'); icon.classList.remove('fa-regular'); icon.classList.add('fa-solid'); }
                else { s.classList.remove('text-warning'); s.classList.add('text-secondary'); icon.classList.add('fa-regular'); icon.classList.remove('fa-solid'); }
            });
        });
        btn.addEventListener('click', function () {
            ratingInput.value = this.dataset.value;
        });
    });
    document.getElementById('star-rating-container').addEventListener('mouseleave', function () {
        const selected = parseInt(ratingInput.value || 0);
        stars.forEach((s, i) => {
            const icon = s.querySelector('i');
            if (i < selected) { s.classList.add('text-warning'); s.classList.remove('text-secondary'); icon.classList.remove('fa-regular'); icon.classList.add('fa-solid'); }
            else { s.classList.remove('text-warning'); s.classList.add('text-secondary'); icon.classList.add('fa-regular'); icon.classList.remove('fa-solid'); }
        });
    });
});
</script>
