<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
$pageTitle = 'Downloads & Technical Library';
$currentPage = 'downloads';

$cat = trim($_GET['cat'] ?? '');
if ($cat) {
  $items = Database::fetchAll("SELECT * FROM downloads WHERE is_active=1 AND category=? ORDER BY sort_order, created_at DESC", [$cat]);
} else {
  $items = Database::fetchAll("SELECT * FROM downloads WHERE is_active=1 ORDER BY category, sort_order, created_at DESC");
}
$cats = Database::fetchAll("SELECT DISTINCT category FROM downloads WHERE is_active=1 ORDER BY category");

// Track download
if (isset($_GET['dl']) && is_numeric($_GET['dl'])) {
  $file = Database::fetchOne("SELECT * FROM downloads WHERE id=? AND is_active=1", [(int)$_GET['dl']]);
  if ($file) {
    Database::execute("UPDATE downloads SET downloads_count=downloads_count+1 WHERE id=?", [$file['id']]);
    header('Location: /uploads/' . $file['file_path']);
    exit;
  }
}

include __DIR__ . '/includes/header.php';
?>

<section class="pt-28 pb-16 bg-navy-900">
  <div class="max-w-7xl mx-auto px-4">
    <div class="text-center mb-12">
      <div class="inline-flex items-center gap-2 bg-orange-600/10 border border-orange-600/30 rounded-full px-4 py-1.5 text-xs font-medium text-orange-400 uppercase tracking-wider mb-4">
        Technical Resources
      </div>
      <h1 class="text-4xl md:text-5xl font-black font-display mb-4">Downloads & <span class="text-orange-500">Tech Library</span></h1>
      <p class="text-gray-400 max-w-2xl mx-auto">Download technical datasheets, specification summaries, API standard guides, and product catalogues. All documents are free to download.</p>
    </div>

    <!-- Category Filter -->
    <?php if (count($cats) > 1): ?>
    <div class="flex flex-wrap gap-2 justify-center mb-8">
      <a href="/downloads.php" class="px-4 py-2 rounded-lg text-sm font-medium transition-colors <?= !$cat ? 'bg-orange-600 text-white' : 'bg-navy-700 text-gray-400 hover:bg-navy-600' ?>">All</a>
      <?php foreach ($cats as $c): ?>
      <a href="/downloads.php?cat=<?= urlencode($c['category']) ?>" class="px-4 py-2 rounded-lg text-sm font-medium transition-colors <?= $cat === $c['category'] ? 'bg-orange-600 text-white' : 'bg-navy-700 text-gray-400 hover:bg-navy-600' ?>"><?= e($c['category']) ?></a>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <?php if ($items): ?>
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
      <?php foreach ($items as $dl): ?>
      <div class="card-dark p-5 hover:border-orange-600/50 transition-all group">
        <div class="flex items-start gap-4">
          <div class="w-12 h-12 rounded-xl bg-orange-600/10 border border-orange-600/20 flex items-center justify-center flex-shrink-0">
            <?php
            $ext = strtolower($dl['file_type'] ?? pathinfo($dl['file_path'], PATHINFO_EXTENSION));
            $icons = ['pdf' => '📄', 'xlsx' => '📊', 'xls' => '📊', 'doc' => '📝', 'docx' => '📝', 'dwg' => '📐', 'zip' => '🗜️'];
            echo $icons[$ext] ?? '📎';
            ?>
          </div>
          <div class="flex-1 min-w-0">
            <h3 class="font-semibold text-white text-sm leading-snug mb-1"><?= e($dl['title']) ?></h3>
            <?php if ($dl['description']): ?>
            <p class="text-xs text-gray-400 leading-relaxed line-clamp-2 mb-2"><?= e($dl['description']) ?></p>
            <?php endif; ?>
            <div class="flex items-center gap-3 text-xs text-gray-500">
              <?php if ($dl['file_size']): ?><span><?= e($dl['file_size']) ?></span><?php endif; ?>
              <span class="uppercase font-semibold text-orange-400"><?= strtoupper(e($dl['file_type'] ?: 'PDF')) ?></span>
              <?php if ($dl['downloads_count']): ?><span><?= number_format($dl['downloads_count']) ?> downloads</span><?php endif; ?>
            </div>
          </div>
        </div>
        <div class="mt-4 flex items-center justify-between">
          <span class="text-xs bg-navy-600 text-gray-400 px-2.5 py-1 rounded-full"><?= e($dl['category']) ?></span>
          <a href="/downloads.php?dl=<?= $dl['id'] ?>" class="flex items-center gap-1.5 text-xs font-semibold text-orange-500 hover:text-white bg-orange-600/10 hover:bg-orange-600 px-3 py-1.5 rounded-lg transition-all">
            ⬇ Download
          </a>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <!-- Empty state with sample categories -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
      <?php foreach ([
        ['📄', 'Product Datasheets', 'Technical specifications for valves, flanges, fittings, and spares'],
        ['📋', 'API Standard Guides', 'Plain-language summaries of API 6A, 6D, 600, ASME B16.5 and more'],
        ['📊', 'Pressure-Temperature Tables', 'ANSI/ASME class rating tables for common flange materials'],
      ] as [$ic, $t, $d]): ?>
      <div class="card-dark p-6 text-center">
        <div class="text-4xl mb-3"><?= $ic ?></div>
        <h3 class="font-bold text-white mb-2"><?= $t ?></h3>
        <p class="text-sm text-gray-400"><?= $d ?></p>
      </div>
      <?php endforeach; ?>
    </div>
    <div class="text-center py-8">
      <div class="text-4xl mb-4">📚</div>
      <h3 class="text-xl font-semibold mb-2">Library Coming Soon</h3>
      <p class="text-gray-400 mb-6">Technical documents are being uploaded. In the meantime, contact us for any specific datasheet or specification.</p>
      <a href="/contact.php" class="btn-primary px-6 py-2.5">Request a Document</a>
    </div>
    <?php endif; ?>

    <!-- Request a document -->
    <?php if ($items): ?>
    <div class="mt-12 card-dark p-6 text-center border-orange-600/30">
      <h3 class="font-bold mb-2">Can't find what you need?</h3>
      <p class="text-gray-400 text-sm mb-4">Contact us and we'll source the exact datasheet, drawing, or technical document you require.</p>
      <a href="/contact.php" class="btn-primary px-6 py-2.5">Request a Document</a>
    </div>
    <?php endif; ?>
  </div>
</section>

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