<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();
$pageTitle = 'Downloads Management';
$success = $error = '';
$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM downloads WHERE id=?", [$id]);
  header('Location: /admin/downloads.php?deleted=1'); exit;
}
if ($action === 'toggle' && $id) {
  Database::execute("UPDATE downloads SET is_active = NOT is_active WHERE id=?", [$id]);
  header('Location: /admin/downloads.php'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $title    = trim($_POST['title'] ?? '');
  $desc     = trim($_POST['description'] ?? '');
  $category = trim($_POST['category'] ?? 'General');
  $fileType = trim($_POST['file_type'] ?? 'pdf');
  $sort     = (int)($_POST['sort_order'] ?? 0);
  if (!$title) { $error = 'Title is required.'; }
  else {
    $filePath = $_POST['existing_file'] ?? null;
    $fileSize = $_POST['existing_size'] ?? null;
    if (!empty($_FILES['file']['tmp_name'])) {
      $origName = $_FILES['file']['name'];
      $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
      $fname = 'dl_' . time() . '_' . preg_replace('/[^a-z0-9\-_]/', '', strtolower(pathinfo($origName, PATHINFO_FILENAME))) . '.' . $ext;
      if (move_uploaded_file($_FILES['file']['tmp_name'], UPLOAD_DIR . $fname)) {
        $filePath = $fname;
        $fileType = $ext;
        $bytes = $_FILES['file']['size'];
        $fileSize = $bytes < 1048576 ? round($bytes/1024) . ' KB' : round($bytes/1048576, 1) . ' MB';
      }
    }
    if (!$filePath) { $error = 'Please upload a file.'; }
    else {
      if ($id) {
        Database::execute("UPDATE downloads SET title=?,description=?,file_path=?,file_type=?,file_size=?,category=?,sort_order=? WHERE id=?",
          [$title,$desc,$filePath,$fileType,$fileSize,$category,$sort,$id]);
        $success = 'Download updated.';
      } else {
        Database::execute("INSERT INTO downloads (title,description,file_path,file_type,file_size,category,sort_order,is_active) VALUES (?,?,?,?,?,?,?,1)",
          [$title,$desc,$filePath,$fileType,$fileSize,$category,$sort]);
        $success = 'Download added.'; $id = Database::lastInsertId(); $action = 'edit';
      }
    }
  }
}
$dl = ($action==='edit'||$action==='new') && $id ? Database::fetchOne("SELECT * FROM downloads WHERE id=?",[$id]) : null;
$dls = $action==='list' ? Database::fetchAll("SELECT * FROM downloads ORDER BY category,sort_order,id") : [];
include dirname(__DIR__) . '/includes/admin-header.php';
?>

<div class="p-6 max-w-5xl">
  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">⬇ Downloads Manager</h1>
    <div class="flex gap-3">
      <a href="/downloads.php" target="_blank" class="btn-outline text-sm px-3 py-2">View Public Page ↗</a>
      <a href="?action=new" class="btn-primary text-sm px-4 py-2">+ Upload File</a>
    </div>
  </div>
  <?php if (isset($_GET['deleted'])): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4">Deleted.</div><?php endif; ?>
  <div class="card-dark overflow-hidden">
    <table class="w-full text-sm">
      <thead class="bg-navy-700 text-xs text-gray-400 uppercase">
        <tr><th class="px-4 py-3 text-left">Title</th><th class="px-4 py-3 text-left">Category</th><th class="px-4 py-3 text-left">Type</th><th class="px-4 py-3 text-left">Size</th><th class="px-4 py-3 text-left">Downloads</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$dls): ?><tr><td colspan="7" class="px-4 py-8 text-center text-gray-500">No files yet. <a href="?action=new" class="text-orange-400">Upload first file →</a></td></tr><?php endif; ?>
        <?php foreach ($dls as $d): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3 font-medium max-w-xs truncate"><?= e($d['title']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($d['category']) ?></td>
          <td class="px-4 py-3 text-orange-400 font-semibold uppercase text-xs"><?= e($d['file_type']) ?></td>
          <td class="px-4 py-3 text-gray-400 text-xs"><?= e($d['file_size'] ?: '—') ?></td>
          <td class="px-4 py-3 text-gray-400"><?= number_format($d['downloads_count']) ?></td>
          <td class="px-4 py-3"><a href="?action=toggle&id=<?= $d['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $d['is_active'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>"><?= $d['is_active'] ? 'Active' : 'Hidden' ?></a></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $d['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <a href="/uploads/<?= e($d['file_path']) ?>" target="_blank" class="text-xs text-blue-400 hover:underline">View</a>
            <a href="?action=delete&id=<?= $d['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Delete this download?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php else: ?>
  <div class="flex items-center gap-3 mb-6">
    <a href="/admin/downloads.php" class="text-gray-400 hover:text-white text-sm">← All Downloads</a>
    <h1 class="text-xl font-bold"><?= $id ? 'Edit Download' : 'Upload New File' ?></h1>
  </div>
  <?php if ($success): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="bg-red-600/10 border border-red-600/30 text-red-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($error) ?></div><?php endif; ?>
  <form method="POST" enctype="multipart/form-data" class="card-dark p-6 max-w-2xl">
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Document Title *</label>
      <input type="text" name="title" value="<?= e($dl['title'] ?? '') ?>" class="input-field" required placeholder="e.g. API 6A Gate Valve Datasheet">
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Description</label>
      <textarea name="description" rows="3" class="input-field" placeholder="Brief description of the document..."><?= e($dl['description'] ?? '') ?></textarea>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Category</label>
        <input type="text" name="category" value="<?= e($dl['category'] ?? 'General') ?>" class="input-field" list="dl-cats">
        <datalist id="dl-cats"><option>Datasheets</option><option>API Standards</option><option>Pressure-Temperature Tables</option><option>Material Certificates</option><option>Catalogues</option><option>General</option></datalist>
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Sort Order</label>
        <input type="number" name="sort_order" value="<?= e($dl['sort_order'] ?? 0) ?>" class="input-field" min="0">
      </div>
    </div>
    <div class="mb-5">
      <label class="block text-xs text-gray-400 mb-1">File (PDF, XLSX, DOC, DWG, ZIP)</label>
      <?php if (!empty($dl['file_path'])): ?>
      <div class="text-xs text-green-400 mb-1 flex items-center gap-2">
        📎 Current file: <?= e(basename($dl['file_path'])) ?> <?= $dl['file_size'] ? "({$dl['file_size']})" : '' ?>
        <a href="/uploads/<?= e($dl['file_path']) ?>" target="_blank" class="text-blue-400 underline">view</a>
        <input type="hidden" name="existing_file" value="<?= e($dl['file_path']) ?>">
        <input type="hidden" name="existing_size" value="<?= e($dl['file_size']) ?>">
      </div>
      <?php endif; ?>
      <input type="file" name="file" class="text-sm text-gray-400 <?= empty($dl) ? 'required' : '' ?>">
      <p class="text-xs text-gray-500 mt-1">Max size: 50MB. Upload a new file to replace the existing one.</p>
    </div>
    <div class="flex gap-3">
      <button type="submit" class="btn-primary px-6 py-2.5">Save</button>
      <a href="/admin/downloads.php" class="btn-outline px-6 py-2.5">Cancel</a>
    </div>
  </form>
  <?php endif; ?>
</div>

<?php include dirname(__DIR__) . '/includes/admin-footer.php'; ?>
