<?php
require_once 'includes/auth.php'; // Ensure only logged-in admins can upload
require_once '../includes/db.php';

if (isset($_FILES['upload'])) {
    $file = $_FILES['upload'];
    $file_tmp = $file['tmp_name'];
    $file_orig_name = $file['name'];
    $file_ext = strtolower(pathinfo($file_orig_name, PATHINFO_EXTENSION));
    
    $allowed_exts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    
    $funcNum = isset($_GET['CKEditorFuncNum']) ? intval($_GET['CKEditorFuncNum']) : 0;
    
    if (in_array($file_ext, $allowed_exts)) {
        $new_file_name = uniqid('art_img_', true) . '.' . $file_ext;
        $dest_dir = __DIR__ . '/../uploads/';
        
        if (!is_dir($dest_dir)) {
            mkdir($dest_dir, 0777, true);
        }
        
        if (move_uploaded_file($file_tmp, $dest_dir . $new_file_name)) {
            // Get public absolute path for CKEditor
            $base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
            // Extract current directory path to generate clean relative path to uploads
            $request_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
            $project_path = str_replace('/admin/upload.php', '', $request_path);
            $url = $base_url . $project_path . '/uploads/' . $new_file_name;
            
            $message = 'Gambar berhasil diunggah!';
            echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
        } else {
            $message = 'Gagal memindahkan file yang diunggah.';
            echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '', '$message');</script>";
        }
    } else {
        $message = 'Format file tidak didukung. Hanya JPG, JPEG, PNG, WEBP, dan GIF yang diperbolehkan.';
        echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '', '$message');</script>";
    }
} else {
    echo "No file uploaded.";
}
