<?php
// admin/upload_image.php — TinyMCE image handler (secure)
@session_start();
require_once __DIR__ . '/../config/helpers.php';

// Pastikan user login/otorisasi (opsional, jika ada helper)
if (function_exists('require_login')) { require_login(); }

header('Content-Type: application/json; charset=utf-8');

if (empty($_FILES['file']['name'])) {
  echo json_encode(['error' => 'Tidak ada file.']); exit;
}

// Validasi ukuran & mime
$f = $_FILES['file'];
if ($f['error'] !== UPLOAD_ERR_OK) { echo json_encode(['error'=>'Upload error.']); exit; }
if ($f['size'] > 2*1024*1024) { echo json_encode(['error'=>'Ukuran maksimal 2MB.']); exit; }

$extOk = preg_match('~\.(jpe?g|png|webp)$~i', $f['name']);
if (!$extOk) { echo json_encode(['error'=>'Format harus JPG/PNG/WEBP.']); exit; }

$fi = new finfo(FILEINFO_MIME_TYPE);
$mime = $fi->file($f['tmp_name']);
$allowed = ['image/jpeg','image/png','image/webp'];
if (!in_array($mime, $allowed, true)) {
  echo json_encode(['error'=>'File bukan gambar valid.']); exit;
}

// Simpan ke uploads/news/editor/
$basePublic = realpath(__DIR__ . '/../public');
$dirAbs = $basePublic . '/uploads/news/editor';
$dirRel = 'uploads/news/editor';
if (!is_dir($dirAbs)) @mkdir($dirAbs, 0775, true);

$safeBase = preg_replace('/[^A-Za-z0-9_\.-]/', '_', basename($f['name']));
$newName  = time().'_'.bin2hex(random_bytes(3)).'_'.$safeBase;
$destAbs  = $dirAbs . '/' . $newName;

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

// Kembalikan URL absolut/relatif sesuai helper yang ada
if (function_exists('base_url')) {
  echo json_encode(['location' => base_url($dirRel.'/'.$newName)]); exit;
} else {
  // fallback relatif dari /public
  echo json_encode(['location' => '/'.$dirRel.'/'.$newName]); exit;
}
