<?php
// admin/download.php - CRUD Downloadable Files for admin
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$db = get_db();
// Auto-migrate download table
$db->exec("CREATE TABLE IF NOT EXISTS download (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    file TEXT NOT NULL,
    kategori TEXT DEFAULT '',
    description TEXT,
    date TEXT NOT NULL
)");
// Add kategori column if not exists (for migration)
try { $db->query("SELECT kategori FROM download LIMIT 1"); } catch (Exception $e) {
  $db->exec("ALTER TABLE download ADD COLUMN kategori TEXT DEFAULT ''");
}

$action = $_GET['action'] ?? '';
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Add Download
if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $kategori = trim($_POST['kategori'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $date = date('Y-m-d');
    $file = null;
    if (!empty($_FILES['file']['name'])) {
        $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['file']['name']);
        $dest = __DIR__ . '/../data/uploads/' . $fileName;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
            $file = $fileName;
        }
    }
    if ($file) {
        $stmt = $db->prepare("INSERT INTO download (title, file, kategori, description, date) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$title, $file, $kategori, $description, $date]);
    }
    header('Location: download.php?msg=added'); exit;
}

// Edit Download
if ($action === 'edit' && $id && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $kategori = trim($_POST['kategori'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $file = $_POST['old_file'] ?? null;
    if (!empty($_FILES['file']['name'])) {
        $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['file']['name']);
        $dest = __DIR__ . '/../data/uploads/' . $fileName;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
            $file = $fileName;
        }
    }
    if ($file) {
        $stmt = $db->prepare("UPDATE download SET title=?, file=?, kategori=?, description=? WHERE id=?");
        $stmt->execute([$title, $file, $kategori, $description, $id]);
    }
    header('Location: download.php?msg=updated'); exit;
}

// Delete Download
if ($action === 'delete' && $id) {
    $stmt = $db->prepare("SELECT file FROM download WHERE id=?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row && !empty($row['file'])) {
        $filePath = __DIR__ . '/../data/uploads/' . $row['file'];
        if (file_exists($filePath)) unlink($filePath);
    }
    $stmt = $db->prepare("DELETE FROM download WHERE id=?");
    $stmt->execute([$id]);
    header('Location: download.php?msg=deleted'); exit;
}

// Fetch download list
$downloads = $db->query("SELECT * FROM download ORDER BY date DESC, id DESC")->fetchAll(PDO::FETCH_ASSOC);
// Fetch single download for edit
$edit = null;
if ($action === 'edit' && $id) {
    $stmt = $db->prepare("SELECT * FROM download WHERE id=?");
    $stmt->execute([$id]);
    $edit = $stmt->fetch(PDO::FETCH_ASSOC);
}

include '_header.php';
?>
<div class="container-fluid">
  <h1 class="mt-3 mb-4">Manajemen Download</h1>
  <?php if (!empty($_GET['msg'])): ?>
    <div class="alert alert-success">File download berhasil <?php echo e($_GET['msg']); ?>.</div>
  <?php endif; ?>
  <div class="row">
    <div class="col-md-5">
      <div class="card mb-4">
        <div class="card-header">Tambah / Edit File Download</div>
        <div class="card-body">
          <form method="post" enctype="multipart/form-data" action="download.php?action=<?php echo $edit ? 'edit&id=' . $edit['id'] : 'add'; ?>">
            <div class="mb-2">
              <label>Judul</label>
              <input type="text" name="title" class="form-control" required value="<?php echo e($edit['title'] ?? ''); ?>">
            </div>
            <div class="mb-2">
              <label>Kategori</label>
              <input type="text" name="kategori" class="form-control" placeholder="Misal: Formulir, Pengumuman, dll" value="<?php echo e($edit['kategori'] ?? ''); ?>">
            </div>
            <div class="mb-2">
              <label>Deskripsi</label>
              <textarea name="description" class="form-control" rows="2"><?php echo e($edit['description'] ?? ''); ?></textarea>
            </div>
            <div class="mb-2">
              <label>File</label>
              <input type="file" name="file" class="form-control" <?php echo $edit ? '' : 'required'; ?>>
              <?php if (!empty($edit['file'])): ?>
                <a href="../data/uploads/<?php echo e($edit['file']); ?>" target="_blank">File saat ini</a>
                <input type="hidden" name="old_file" value="<?php echo e($edit['file']); ?>">
              <?php endif; ?>
            </div>
            <button type="submit" class="btn btn-primary">Simpan</button>
            <?php if ($edit): ?>
              <a href="download.php" class="btn btn-secondary">Batal</a>
            <?php endif; ?>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-7">
      <div class="card mb-4">
        <div class="card-header">Daftar File Download</div>
        <div class="card-body p-0">
          <table class="table table-striped mb-0">
            <thead><tr><th>Judul</th><th>Kategori</th><th>Tanggal</th><th>File</th><th>Aksi</th></tr></thead>
            <tbody>
              <?php foreach ($downloads as $d): ?>
                <tr>
                  <td><?php echo e($d['title']); ?></td>
                  <td><?php echo e($d['kategori'] ?? ''); ?></td>
                  <td><?php echo e($d['date']); ?></td>
                  <td><?php if ($d['file']): ?><a href="../data/uploads/<?php echo e($d['file']); ?>" target="_blank">Download</a><?php endif; ?></td>
                  <td>
                    <a href="download.php?action=edit&id=<?php echo $d['id']; ?>" class="btn btn-sm btn-warning">Edit</a>
                    <a href="download.php?action=delete&id=<?php echo $d['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus file ini?')">Hapus</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<?php include '_footer.php'; ?>
