<?php
require_once '../includes/auth.php';
require_once '../includes/config.php';

if (!isAdmin()) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit;
}

// Konfigurasi upload
$uploadDir = '../uploads/images/';
$maxFileSize = 5 * 1024 * 1024;
$allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];

// Buat direktori jika belum ada
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Set header JSON
header('Content-Type: application/json');

try {
    if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('No file uploaded or upload error');
    }

    $file = $_FILES['image'];
    
    // Validasi file size dan type
    if ($file['size'] > $maxFileSize) {
        throw new Exception('File size too large. Maximum 5MB allowed.');
    }
    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mimeType, $allowedTypes)) {
        throw new Exception('Invalid file type. Only JPG, PNG, GIF, and WebP allowed.');
    }
    
    // Generate unique filename
    $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $fileName = uniqid() . '_' . time() . '.' . $fileExtension;
    $filePath = $uploadDir . $fileName;
    
    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $filePath)) {
        throw new Exception('Failed to move uploaded file');
    }
    
    // **SOLUSI DINAMIS: Generate URL yang flexible**
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST']; // Ini akan otomatis menyesuaikan
    
    // Base path - otomatis detect
    $scriptPath = dirname($_SERVER['SCRIPT_NAME']);
    $basePath = rtrim(str_replace('/admin', '', $scriptPath), '/');
    
    // **URL yang dinamis - akan bekerja di environment apapun**
    $imageUrl = $protocol . '://' . $host . $basePath . '/uploads/images/' . $fileName;
    
    // Juga simpan relative path untuk fallback
    $relativePath = '/uploads/images/' . $fileName;
    
    // Response success
    echo json_encode([
        'success' => true,
        'url' => $imageUrl,
        'relative_path' => $relativePath,
        'fileName' => $fileName,
        'server_info' => [ // Untuk debug
            'host' => $host,
            'protocol' => $protocol,
            'base_path' => $basePath
        ],
        'message' => 'Image uploaded successfully'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>