<?php
// Check if a file is requested for download
if (isset($_GET['file']) && !empty($_GET['file'])) {
    $fileName = basename($_GET['file']);
    $filePath = dirname(__DIR__) . '/download/' . $fileName;
    $countsFile = __DIR__ . '/counts/counts.json';

    // Validate file exists and is safe
    if (file_exists($filePath) && !is_dir($filePath) && preg_match('/^[a-zA-Z0-9._-]+$/i', $fileName)) {
        // Update download count
        $counts = file_exists($countsFile) ? json_decode(file_get_contents($countsFile), true) : [];
        $counts[$fileName] = isset($counts[$fileName]) ? $counts[$fileName] + 1 : 1;
        file_put_contents($countsFile, json_encode($counts));

        // Serve the file
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    } else {
        // File not found, show error (or redirect to list)
        header('HTTP/1.1 404 Not Found');
        echo "<h1>404 File Not Found</h1>";
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
   
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Downloads | Precision Repeaters by Red's Engineering</title>
    <meta name="description" content="Download manuals, firmware updates, and resources for FieldLink products by Red's Engineering.">
    <meta name="keywords" content="FieldLink, Red's Engineering, GMRS repeater, downloads, manuals, firmware">
    <meta name="author" content="Red's Engineering">
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Roboto', sans-serif; }
        body { overflow-y: scroll; line-height: 1.6; color: #333; background: linear-gradient(135deg, #f0f4f8, #d9e2ec); overflow-x: hidden; }
        header { background: linear-gradient(90deg, #1a3c5e, #2a5678); color: white; padding: 2rem; text-align: center; box-shadow: 0 4px 10px rgba(0,0,0,0.2); min-height: 100px; }
        h1 { font-size: 3rem; }
        nav { background: #2a5678; padding: 1rem; position: sticky; top: 0; z-index: 1000; box-shadow: 0 2px 5px rgba(0,0,0,0.1); min-height: 60px; }
        nav ul.nav-menu { list-style: none; display: flex; justify-content: center; gap: 2rem; margin: 0; padding: 0; }
        nav a { color: white; text-decoration: none; font-weight: 600; padding: 0.5rem 1rem; transition: all 0.3s ease; }
        nav a:hover { color: #ffcc00; background: rgba(255,255,255,0.1); border-radius: 5px; }
        .hamburger { display: none; background: none; border: none; color: #ffcc00; font-size: 1.5rem; cursor: pointer; padding: 0.5rem; }
        .container { max-width: 1200px; margin: 0 auto; padding: 3rem 1rem; }
        .section { background: white; padding: 2rem; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-bottom: 2rem; }
        h2 { color: #1a3c5e; font-size: 2.5rem; margin-bottom: 1.5rem; }
        footer { background: linear-gradient(90deg, #1a3c5e, #2a5678); color: white; text-align: center; padding: 1.5rem; }
        footer a { color: #ffcc00; text-decoration: none; }
        footer a:hover { color: #fff; }

        /* Downloads List Styling */
        .downloads-list { list-style: none; margin-top: 1rem; }
        .downloads-list li { padding: 1rem; border-bottom: 1px solid #ddd; display: flex; align-items: center; justify-content: space-between; }
        .downloads-list li:last-child { border-bottom: none; }
        .file-info { display: flex; align-items: center; flex-grow: 1; }
        .file-icon { width: 24px; height: 24px; vertical-align: middle; margin-right: 12px; }
        .file-details { flex-grow: 1; }
        .file-name { font-weight: bold; color: #2980b9; font-size: 1.1rem; }
        .file-name:hover { text-decoration: underline; }
        .file-description { font-size: 0.9rem; color: #666; margin-top: 0.25rem; }
        .download-count { font-size: 0.9rem; color: #555; margin: 0 1rem; }
        .download-link a { color: #2980b9; text-decoration: none; font-weight: bold; padding: 0.5rem 1rem; border: 1px solid #2980b9; border-radius: 5px; transition: all 0.3s ease; }
        .download-link a:hover { background: #2980b9; color: white; text-decoration: none; }

        @media (max-width: 768px) {
            .hamburger { display: block; position: absolute; top: 1rem; left: 1rem; }
            nav ul.nav-menu { display: none; flex-direction: column; gap: 1rem; background: #2a5678; position: absolute; top: 100%; left: 0; width: 100%; padding: 1rem; box-shadow: 0 4px 10px rgba(0,0,0,0.2); }
            nav ul.nav-menu.active { display: flex; }
            nav a { display: block; padding: 0.75rem 1rem; }
            h1 { font-size: 2rem; }
            h2 { font-size: 1.8rem; }
            .container { padding: 2rem 1rem; }
            .section { padding: 1.5rem; }
            .downloads-list li { flex-direction: column; align-items: flex-start; }
            .download-count { margin: 0.5rem 0; }
            .download-link { margin-top: 0.5rem; }
        }
    </style>
</head>
<body>
    <header>
        <h1>Downloads</h1>
    </header>
      <nav aria-label="Main navigation">
        <button class="hamburger" aria-label="Toggle navigation menu" aria-expanded="false" aria-controls="nav-menu">☰</button>
        <ul class="nav-menu" id="nav-menu">
            <li><a href="/index.html">Home</a></li>
            <li><a href="https://www.fieldlink.us/products/">Products</a></li>
            <li><a href="https://www.fieldlink.us/store/">Store</a></li>
            <li><a href="https://www.fieldlink.us/documentation/">Documentation</a></li>
            <li><a href="https://www.fieldlink.us/downloads/">Downloads</a></li>
            <li><a href="https://www.fieldlink.us/faq/">FAQ</a></li>
            <li><a href="https://www.fieldlink.us/contact/">Contact</a></li>
        </ul>
    </nav>
    <div class="container">
        <section class="section">
            <h2>Downloads</h2>
            <ul class="downloads-list">
                <?php
                $directory = dirname(__DIR__) . '/download'; // Scan /download
                $webPath = '/download';
                $countsFile = __DIR__ . '/counts/counts.json'; // Counts in /downloads/counts
                $files = scandir($directory);

                // Custom descriptions array
                $customDescriptions = [
                    'manual-v1.2.pdf' => 'Comprehensive user manual for FieldLink SRPT-02 (Version 1.2, 40 pages).',
                    'firmware-2025.zip' => 'Latest firmware update for FieldLink Xtreme (Released April 2025).',
                    'faq.pdf' => 'Frequently asked questions about GMRS repeater setup and troubleshooting.',
                    'config-data.csv' => 'Sample radio configuration data for FieldLink SRPT-03.',
                    'whitepaper-gmrs.pdf' => 'White paper on GMRS technology trends in 2025.',
                    'SRPT-02-03-Case.stl' => '3D model for SRPT-02 and SRPT-03 case.',
                    'FieldLink-solar-solution-white-paper.pdf' => 'White paper on solar-powered solutions for FieldLink products.'
                ];

                $counts = file_exists($countsFile) ? json_decode(file_get_contents($countsFile), true) : [];

                $fileList = [];
                foreach ($files as $file) {
                    if ($file !== '.' && $file !== '..' && !is_dir($directory . '/' . $file)) {
                        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                        $mtime = filemtime($directory . '/' . $file);
                        $priority = 4;
                        if ($extension === 'pdf') $priority = 1;
                        elseif ($extension === 'zip') $priority = 2;
                        elseif ($extension === 'csv' || $extension === 'stl') $priority = 3;

                        $fileList[] = [
                            'name' => $file,
                            'extension' => $extension,
                            'mtime' => $mtime,
                            'priority' => $priority
                        ];
                    }
                }

                usort($fileList, function($a, $b) {
                    if ($a['priority'] === $b['priority']) {
                        return $b['mtime'] <=> $a['mtime'];
                    }
                    return $a['priority'] <=> $b['priority'];
                });

                foreach ($fileList as $fileInfo) {
                    $file = $fileInfo['name'];
                    $extension = $fileInfo['extension'];
                    $downloadCount = isset($counts[$file]) ? $counts[$file] : 0;

                    $icon = '/icons/file-icon.png';
                    // Use custom description if available, otherwise fall back to generic
                    $description = isset($customDescriptions[$file]) ? $customDescriptions[$file] : 'Miscellaneous File';

                    if ($extension === 'pdf' && !isset($customDescriptions[$file])) {
                        $icon = '/icons/pdf-icon.png';
                        $description = 'User Manual or Documentation';
                    } elseif ($extension === 'zip' && !isset($customDescriptions[$file])) {
                        $icon = '/icons/zip-icon.png';
                        $description = 'Firmware Update';
                    } elseif ($extension === 'stl' && !isset($customDescriptions[$file])) {
                        $icon = '/icons/stl-icon.png';
                        $description = '3D Model File';
                    } elseif ($extension === 'csv' && !isset($customDescriptions[$file])) {
                        $icon = '/icons/csv-icon.png';
                        $description = 'Radio Configuration Data';
                    }

                    echo "<li>";
                    echo "<div class='file-info'>";
                    echo "<img src=\"$icon\" alt=\"$extension icon\" class=\"file-icon\">";
                    echo "<div class='file-details'>";
                    echo "<span class='file-name'>$file</span>";
                    echo "<div class='file-description'>$description</div>";
                    echo "</div>";
                    echo "</div>";
                    echo "<span class='download-count'>Downloads: $downloadCount</span>";
                    echo "<div class='download-link'><a href=\"/downloads/index.php?file=" . urlencode($file) . "\">Download</a></div>";
                    echo "</li>";
                }
                ?>
            </ul>
        </section>
    </div>
   <footer aria-label="Footer navigation and copyright">
        <p>
            <a href="https://www.fieldlink.us/documentation/">Docs</a> |
            <a href="https://www.fieldlink.us/contact/">Contact</a> |
            <a href="https://www.fieldlink.us/faq/">FAQ</a> |
            <a href="https://www.fieldlink.us/downloads/">Downloads</a> |
            <a href="https://www.fieldlink.us/gmrs-repeater-builds/">Builds & Videos</a>
        </p>
        <p>© 2026 Red's Engineering. All rights reserved. | <a href="https://www.redsengineering.com">Visit Red's Engineering for HAM Solutions</a></p>
    </footer>
    <script>
        document.querySelector('.hamburger').addEventListener('click', function() {
            document.querySelector('.nav-menu').classList.toggle('active');
        });
    </script>
</body>
</html>