<?php
require 'aws-sdk/aws-autoloader.php';
$config = require 'config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

function send_json_response($status, $message, $data = []) {
    echo json_encode(['status' => $status, 'msg' => $message, 'data' => $data]);
    exit;
}

$s3Client = new S3Client($config['s3']);
$bucket = $config['s3']['bucket_name'];
$endpoint = $config['s3']['endpoint'];

$fileToUploadPath = null;
$originalFileName = 'pasted_image.png';
// =================================================================
// PERUBAHAN 1: Siapkan variabel untuk menampung tipe file
// =================================================================
$mimeType = 'application/octet-stream'; // Tipe file default jika tidak terdeteksi

if (isset($_POST['pastedImage'])) {
    $data = $_POST['pastedImage'];
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $decodedImage = base64_decode($data);
    
    // =================================================================
    // PERUBAHAN 2: Deteksi tipe file dari gambar yang di-paste
    // =================================================================
    $mimeType = str_replace('data:', '', $type);

    if (strlen($decodedImage) > $config['app']['max_file_size']) {
        send_json_response('error', 'Ukuran gambar dari clipboard melebihi batas.');
    }
    
    $tempFile = tmpfile();
    fwrite($tempFile, $decodedImage);
    fseek($tempFile, 0);
    $fileToUploadPath = stream_get_meta_data($tempFile)['uri'];

} elseif (isset($_FILES['fileToUpload']) && $_FILES['fileToUpload']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['fileToUpload'];
    
    // =================================================================
    // PERUBAHAN 3: Ambil tipe file dari file yang di-upload
    // =================================================================
    $mimeType = $file['type'];

    if ($file['size'] > $config['app']['max_file_size']) {
        send_json_response('error', 'Ukuran file melebihi batas ' . ($config['app']['max_file_size'] / 1024 / 1024) . ' MB.');
    }
    if (!in_array($mimeType, $config['app']['allowed_mimes'])) {
        send_json_response('error', 'Tipe file tidak diizinkan.');
    }
    
    $fileToUploadPath = $file['tmp_name'];
    $originalFileName = basename($file['name']);
} else {
    send_json_response('error', 'Tidak ada file yang dipilih atau ditempelkan.');
}

$sanitizedFileName = preg_replace('/[^\w\._]+/', '', str_replace(' ', '_', $originalFileName));
$uniqueFileName = uniqid() . '_' . $sanitizedFileName;
$year = date('Y');
$month = date('m');
$s3Key = "$year/$month/$uniqueFileName";

try {
    // =================================================================
    // PERUBAHAN 4: Tambahkan 'ContentType' dan 'ContentDisposition'
    // =================================================================
    $result = $s3Client->putObject([
        'Bucket'             => $bucket,
        'Key'                => $s3Key,
        'SourceFile'         => $fileToUploadPath,
        'ACL'                => 'public-read',
        'ContentType'        => $mimeType, // Memberitahu browser jenis filenya
        'ContentDisposition' => 'inline'    // Meminta browser untuk menampilkan file, bukan mengunduh
    ]);

    $publicUrl = rtrim($endpoint, '/') . '/' . $bucket . '/' . $s3Key;
    
    send_json_response('success', 'File berhasil di-upload!', ['url' => $publicUrl]);

} catch (S3Exception $e) {
    send_json_response('error', 'Gagal meng-upload ke S3: ' . $e->getMessage());
} finally {
    if (isset($tempFile) && is_resource($tempFile)) {
        fclose($tempFile);
    }
}
