<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/vendor/autoload.php';
use Aws\S3\S3Client;

// ✅ Connexion PDO MySQL UTF-8 universelle
try {
    $pdo = new PDO(
        'mysql:host=mysql;dbname=forum_database;charset=utf8mb4',
        'myuser',
        'mypassword',
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
        ]
    );
} catch (PDOException $e) {
    die("❌ Erreur de connexion MySQL : " . $e->getMessage());
}

// ✅ Configuration du client MinIO (S3-compatible)
$s3Client = new S3Client([
    'version' => 'latest',
    'region' => 'us-east-1',
    'endpoint' => 'http://minio:9000',
    'use_path_style_endpoint' => true,
    'credentials' => [
        'key' => 'minioadmin',
        'secret' => 'minioadmin'
    ]
]);

$bucketName = 'bucketforum';

// ✅ S’assurer que le bucket existe (création auto si absent)
try {
    $buckets = $s3Client->listBuckets();
    $bucketExists = false;
    foreach ($buckets['Buckets'] as $bucket) {
        if ($bucket['Name'] === $bucketName) {
            $bucketExists = true;
            break;
        }
    }

    if (!$bucketExists) {
        $s3Client->createBucket(['Bucket' => $bucketName]);
        // Rendre le bucket public automatiquement
        $policy = json_encode([
            'Version' => '2012-10-17',
            'Statement' => [[
                'Effect' => 'Allow',
                'Principal' => '*',
                'Action' => ['s3:GetObject'],
                'Resource' => "arn:aws:s3:::{$bucketName}/*"
            ]]
        ]);
        $s3Client->putBucketPolicy([
            'Bucket' => $bucketName,
            'Policy' => $policy
        ]);
    }
} catch (Exception $e) {
    echo "⚠️ Impossible de vérifier/créer le bucket MinIO : " . $e->getMessage();
}
?>
