<?php
require_once '../includes/auth.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; // 5MB
$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 {
    // Cek jika ada file yang diupload
    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
    if ($file['size'] > $maxFileSize) {
        throw new Exception('File size too large. Maximum 5MB allowed.');
    }
    
    // Validasi file type
    $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');
    }
    
    // Generate URL untuk akses gambar
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    
    // Remove 'admin/' from path jika ada
    $basePath = str_replace('/admin', '', dirname($_SERVER['PHP_SELF']));
    $basePath = rtrim($basePath, '/');
    
    $imageUrl = $protocol . '://' . $host . $basePath . '/uploads/images/' . $fileName;
    
    // Response success
    echo json_encode([
        'success' => true,
        'url' => $imageUrl,
        'fileName' => $fileName,
        'message' => 'Image uploaded successfully'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>