<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/utils.php';

// Dulu hanya PPT/PPTX, sekarang tambah PDF
$ALLOW_EXT = ['ppt', 'pptx', 'pdf'];
$MAX_SIZE_MB = 50;
$MAX_SIZE = $MAX_SIZE_MB * 1024 * 1024;

try {
  if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']); exit;
  }

  $title = trim($_POST['title'] ?? '');
  if ($title === '') { echo json_encode(['error' => 'Judul harus diisi']); exit; }

  if (!isset($_FILES['ppt_file']) || $_FILES['ppt_file']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['error' => 'File belum dipilih / gagal diunggah']); exit;
  }

  $f = $_FILES['ppt_file'];
  if ($f['size'] <= 0) { echo json_encode(['error' => 'File kosong']); exit; }
  if ($f['size'] > $MAX_SIZE) { echo json_encode(['error' => "Maksimal ukuran {$MAX_SIZE_MB} MB"]); exit; }

  $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
  if (!in_array($ext, $ALLOW_EXT, true)) {
    echo json_encode(['error' => 'Hanya .ppt / .pptx / .pdf']); exit;
  }

  $safeBase = preg_replace('/[^a-zA-Z0-9_\-\.]+/', '_', pathinfo($f['name'], PATHINFO_FILENAME));
  $finalName = $safeBase . '_' . substr(make_uuid(), 0, 8) . '.' . $ext;

  $uploadDir = __DIR__ . '/uploads';
  if (!is_dir($uploadDir)) {
    if (!mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
      echo json_encode(['error' => 'Gagal membuat folder uploads']); exit;
    }
  }

  $dest = $uploadDir . '/' . $finalName;
  if (!move_uploaded_file($f['tmp_name'], $dest)) {
    echo json_encode(['error' => 'Gagal menyimpan file']); exit;
  }

  // MIME
  $finfo = finfo_open(FILEINFO_MIME_TYPE);
  $mime = finfo_file($finfo, $dest);
  finfo_close($finfo);

  // URL absolut publik
  $url = file_public_url($dest);

  // Simpan metadata
  $db = read_db();
  $item = [
    'id'          => make_uuid(),
    'title'       => $title,
    'filename'    => $finalName,
    'url'         => $url,
    'size'        => filesize($dest),
    'mime'        => $mime,
    'uploaded_at' => date('Y-m-d H:i:s')
  ];
  $db[] = $item;
  if (!write_db($db)) {
    @unlink($dest);
    echo json_encode(['error' => 'Gagal menyimpan metadata']); exit;
  }

  echo json_encode(['ok' => true, 'message' => 'Berhasil diupload', 'data' => $item]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['error' => 'Kesalahan internal', 'detail' => $e->getMessage()]);
}