<?php include 'header.php'; ?>

<div class="container py-3">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4 d-none d-md-block">
        <ol class="breadcrumb mb-0 small">
            <li class="breadcrumb-item"><a href="/" class="text-success text-decoration-none"><?php echo __('home'); ?></a></li>
            <?php 
                $db = db_pdo();
                $catName = $db->query("SELECT name FROM categories WHERE id = " . ($apk['category_id'] ?: 0))->fetchColumn();
                $catSlug = $db->query("SELECT slug FROM categories WHERE id = " . ($apk['category_id'] ?: 0))->fetchColumn();
            ?>
            <li class="breadcrumb-item"><a href="/?category=<?php echo $catSlug; ?>" class="text-success text-decoration-none"><?php echo $catName ?: 'Apps'; ?></a></li>
            <li class="breadcrumb-item active text-muted" aria-current="page"><?php echo $apk['title']; ?></li>
        </ol>
    </nav>

    <div class="row g-4">
        <!-- Main Content -->
        <div class="col-lg-8">
            <div class="bg-white p-3 p-md-5 rounded-4 shadow-sm mb-4">
                <!-- Header Section -->
                <div class="d-flex align-items-start mb-4">
                    <?php 
                        $icon = !empty($apk['icon_path']) ? '/'.$apk['icon_path'] : $apk['image_url'];
                    ?>
                    <img src="<?php echo $icon; ?>" class="rounded-4 me-3 me-md-4 shadow-sm" width="80" height="80" alt="<?php echo $apk['title']; ?>" style="object-fit: cover; min-width: 80px;">
                    <div>
                        <h1 class="h4 fw-bold mb-1 d-flex align-items-center flex-wrap">
                            <?php echo $apk['title']; ?> 
                            <span class="badge bg-light text-muted fw-normal ms-2 fs-6">v<?php echo $apk['version']; ?></span>
                        </h1>
                        <p class="text-muted small mb-3"><?php echo __('official_version_text'); ?></p>
                        
                        <div class="d-flex flex-wrap gap-2 mb-0">
                            <span class="badge bg-success-subtle text-success border border-success-subtle px-2 py-1 fw-medium rounded">
                                <i class="bi bi-download me-1"></i> <?php echo number_format($apk['total_downloads']); ?>
                            </span>
                            <span class="badge bg-info-subtle text-info border border-info-subtle px-2 py-1 fw-medium rounded">
                                <i class="bi bi-shield-check me-1"></i> <?php echo __('verified'); ?>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Action Button -->
                <div class="mb-4" id="main-download-btn-area">
                    <a href="/download/<?php echo $apk['slug']; ?>" target="_blank" class="btn btn-success btn-lg w-100 py-3 rounded-pill fw-bold shadow-sm mb-2">
                        <i class="bi bi-download me-2"></i> <?php echo __('download_now'); ?>
                    </a>
                    <p class="text-muted text-center x-small mt-2" style="font-size: 0.75rem;">
                        <?php echo __('agree_terms_text'); ?>
                    </p>
                </div>

                <!-- Description -->
                <div class="mb-5">
                    <h4 class="fw-bold h5 mb-3"><?php echo __('description'); ?></h4>
                    <div class="text-muted small lh-lg">
                        <?php echo nl2br(htmlspecialchars($apk['description'])); ?>
                    </div>
                </div>

                <!-- Features & Requirements Grid -->
                <div class="row g-3 mb-5">
                    <div class="col-md-6">
                        <div class="p-4 rounded-4 bg-light h-100 border-0">
                            <h6 class="fw-bold mb-3 d-flex align-items-center">
                                <span class="p-1 bg-white rounded shadow-sm me-2 d-flex align-items-center justify-content-center" style="width: 28px; height: 28px;">
                                    <i class="bi bi-star-fill text-warning" style="font-size: 0.8rem;"></i>
                                </span>
                                <?php echo __('main_features'); ?>
                            </h6>
                            <ul class="list-unstyled mb-0 text-muted small">
                                <li class="mb-2 d-flex align-items-center"><i class="bi bi-check-circle-fill text-success me-2"></i> <?php echo __('feature_original'); ?></li>
                                <li class="mb-2 d-flex align-items-center"><i class="bi bi-check-circle-fill text-success me-2"></i> <?php echo __('feature_no_extra'); ?></li>
                                <li class="mb-2 d-flex align-items-center"><i class="bi bi-check-circle-fill text-success me-2"></i> <?php echo __('feature_fast'); ?></li>
                                <li class="d-flex align-items-center"><i class="bi bi-check-circle-fill text-success me-2"></i> <?php echo __('feature_regular'); ?></li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="p-4 rounded-4 bg-light h-100 border-0">
                            <h6 class="fw-bold mb-3 d-flex align-items-center">
                                <span class="p-1 bg-white rounded shadow-sm me-2 d-flex align-items-center justify-content-center" style="width: 28px; height: 28px;">
                                    <i class="bi bi-gear-fill text-secondary" style="font-size: 0.8rem;"></i>
                                </span>
                                <?php echo __('system_requirements'); ?>
                            </h6>
                            <ul class="list-unstyled mb-0 text-muted small">
                                <li class="mb-2 d-flex align-items-center"><i class="bi bi-info-circle me-2"></i> <?php echo __('req_android'); ?></li>
                                <li class="mb-2 d-flex align-items-center"><i class="bi bi-memory me-2"></i> <?php echo __('req_ram'); ?></li>
                                <li class="mb-2 d-flex align-items-center"><i class="bi bi-hdd-network me-2"></i> <?php echo __('req_internet'); ?></li>
                                <li class="d-flex align-items-center"><i class="bi bi-cpu me-2"></i> <?php echo __('req_cpu'); ?></li>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- Safety Banner -->
                <div class="bg-success rounded-4 p-4 text-center">
                    <h6 class="fw-bold text-white mb-2"><?php echo __('safe_question'); ?></h6>
                    <p class="text-white text-opacity-75 small mb-0">
                        <?php echo __('safe_answer'); ?>
                    </p>
                </div>
            </div>

            <!-- Related Apps Section -->
            <?php 
                $relatedApks = $db->query("SELECT * FROM apks WHERE category_id = " . ($apk['category_id'] ?: 0) . " AND id != " . $apk['id'] . " LIMIT 6")->fetchAll();
                if ($relatedApks):
            ?>
            <div class="mb-5">
                <h4 class="fw-bold h5 mb-3 d-flex align-items-center">
                    <i class="bi bi-grid-fill text-success me-2"></i> Similar Apps
                </h4>
                <div class="row g-2">
                    <?php foreach ($relatedApks as $rapk): ?>
                        <div class="col-4 col-md-4">
                            <a href="/apk/<?php echo $rapk['slug']; ?>" class="text-decoration-none">
                                <div class="card border-0 shadow-sm rounded-4 text-center p-2 h-100 hover-lift">
                                    <img src="<?php echo !empty($rapk['icon_path']) ? '/'.$rapk['icon_path'] : $rapk['image_url']; ?>" class="rounded-3 mx-auto mb-2 shadow-sm" width="48" height="48" style="object-fit: cover;">
                                    <h6 class="card-title fw-bold mb-0 text-truncate small" style="font-size: 0.7rem;"><?php echo $rapk['title']; ?></h6>
                                </div>
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Sidebar / Additional Info -->
        <div class="col-lg-4">
            <div class="position-sticky" style="top: 5.5rem;">
                <div class="bg-white p-4 rounded-4 shadow-sm mb-4 text-center border-0 py-5">
                    <h5 class="fw-bold mb-3 h6"><?php echo __('share_earn'); ?></h5>
                    <p class="text-muted small mb-4 lh-sm"><?php echo __('share_earn_text'); ?></p>
                    <div class="input-group mb-3 border rounded-pill p-1">
                        <?php 
                            $ref = isset($_SESSION['user_id']) ? $db->query("SELECT referral_code FROM users WHERE id = ".$_SESSION['user_id'])->fetchColumn() : '';
                            $shareLink = 'http://'.$_SERVER['HTTP_HOST'].'/apk/'.$apk['slug'].($ref ? '?ref='.$ref : '');
                        ?>
                        <input type="text" class="form-control form-control-sm border-0 bg-transparent ps-3" id="shareLink" value="<?php echo $shareLink; ?>" readonly>
                        <button class="btn btn-success btn-sm rounded-pill px-3" type="button" onclick="copyShareLink()"><?php echo __('copy'); ?></button>
                    </div>
                    <?php if (!$ref): ?>
                        <a href="/login" class="small text-success text-decoration-none fw-medium"><?php echo __('login_to_earn'); ?></a>
                    <?php endif; ?>
                </div>

                <!-- Report / Request Section -->
                <div class="bg-light p-4 rounded-4 mb-4 border-0">
                    <h6 class="fw-bold mb-3 d-flex align-items-center">
                        <i class="bi bi-flag-fill text-danger me-2"></i> Support & Issues
                    </h6>
                    <p class="text-muted small mb-3">Found a problem with this app or want to request a newer version?</p>
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-outline-danger btn-sm rounded-pill" data-bs-toggle="modal" data-bs-target="#reportModal" onclick="setReportType('Report Issue')">
                            <i class="bi bi-exclamation-triangle me-1"></i> Report Issue
                        </button>
                        <button type="button" class="btn btn-outline-dark btn-sm rounded-pill" data-bs-toggle="modal" data-bs-target="#reportModal" onclick="setReportType('Request Update')">
                            <i class="bi bi-arrow-repeat me-1"></i> Request Update
                        </button>
                    </div>
                </div>

                <div class="bg-dark text-white p-4 rounded-4 shadow-sm text-center border-0 d-none d-lg-block">
                    <div class="bg-success bg-opacity-10 rounded-circle d-inline-flex p-3 mb-3">
                        <i class="bi bi-trophy text-success h4 mb-0"></i>
                    </div>
                    <h5 class="fw-bold mb-3 h6"><?php echo __('referral_program'); ?></h5>
                    <p class="small text-white-50 mb-4 lh-sm"><?php echo __('referral_program_text'); ?></p>
                    <a href="/register" class="btn btn-success fw-bold w-100 rounded-pill py-2 shadow-sm"><?php echo __('get_started'); ?></a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Report/Request Modal -->
<div class="modal fade" id="reportModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 rounded-4 overflow-hidden">
            <div class="modal-header bg-dark text-white py-4 border-0">
                <h5 class="modal-title fw-bold" id="reportModalLabel">Report Issue</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="report-form">
                <input type="hidden" name="apk_name" value="<?php echo htmlspecialchars($apk['title']); ?>">
                <input type="hidden" name="subject" id="report-subject" value="Report Issue">
                <div class="modal-body p-4">
                    <div id="report-alert"></div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Your Email</label>
                        <input type="email" class="form-control" name="email" placeholder="email@example.com" required>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-bold">Message / Details</label>
                        <textarea class="form-control" name="message" rows="4" placeholder="Please describe the issue or your request..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-light px-4 rounded-pill" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success px-4 rounded-pill" id="report-submit-btn">Send</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Sticky Download Bar (Mobile Only) -->
<div class="sticky-download-bar" id="sticky-download-bar">
    <div class="d-flex align-items-center">
        <img src="<?php echo $icon; ?>" class="rounded-2 me-3" width="40" height="40" alt="<?php echo $apk['title']; ?>">
        <div class="flex-grow-1 overflow-hidden">
            <h6 class="fw-bold mb-0 text-truncate" style="font-size: 0.9rem;"><?php echo $apk['title']; ?></h6>
            <span class="x-small text-muted" style="font-size: 0.7rem;">v<?php echo $apk['version']; ?></span>
        </div>
        <a href="/download/<?php echo $apk['slug']; ?>" class="btn btn-success btn-sm rounded-pill px-3 fw-bold">
            Download
        </a>
    </div>
</div>

<!-- Share FAB (Mobile Only) -->
<a href="#" class="share-fab" id="mobile-share-btn">
    <i class="bi bi-share-fill"></i>
</a>

<script>
function copyShareLink() {
    var copyText = document.getElementById("shareLink");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    navigator.clipboard.writeText(copyText.value);
    
    const btn = event.target;
    const originalText = btn.innerText;
    btn.innerText = "Copied!";
    btn.classList.replace('btn-success', 'btn-dark');
    setTimeout(() => {
        btn.innerText = originalText;
        btn.classList.replace('btn-dark', 'btn-success');
    }, 2000);
}

function setReportType(type) {
    document.getElementById('reportModalLabel').innerText = type;
    document.getElementById('report-subject').value = type + ': <?php echo addslashes($apk['title']); ?>';
}

document.getElementById('report-form').addEventListener('submit', function(e) {
    e.preventDefault();
    const btn = document.getElementById('report-submit-btn');
    const alertBox = document.getElementById('report-alert');
    
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Sending...';
    
    const formData = new FormData(this);
    
    fetch('/api/report', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = 'Send';
        if (data.success) {
            alertBox.innerHTML = '<div class="alert alert-success border-0 small">' + data.success + '</div>';
            setTimeout(() => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('reportModal'));
                modal.hide();
                alertBox.innerHTML = '';
                this.reset();
            }, 2000);
        } else {
            alertBox.innerHTML = '<div class="alert alert-danger border-0 small">' + data.error + '</div>';
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.innerHTML = 'Send';
        alertBox.innerHTML = '<div class="alert alert-danger border-0 small">An error occurred.</div>';
    });
});

// Sticky Bar Logic
window.addEventListener('scroll', function() {
    const mainBtn = document.getElementById('main-download-btn-area');
    const stickyBar = document.getElementById('sticky-download-bar');
    if (mainBtn && stickyBar) {
        const rect = mainBtn.getBoundingClientRect();
        if (rect.bottom < 0) {
            stickyBar.classList.add('show');
        } else {
            stickyBar.classList.remove('show');
        }
    }
});

// Native Web Share API
document.getElementById('mobile-share-btn').addEventListener('click', function(e) {
    e.preventDefault();
    if (navigator.share) {
        navigator.share({
            title: '<?php echo $apk['title']; ?>',
            text: 'Check out this app on ApkNusa!',
            url: '<?php echo $shareLink; ?>',
        }).catch((error) => console.log('Error sharing', error));
    } else {
        copyShareLink();
    }
});
</script>

<?php include 'footer.php'; ?>
