<?php
// config/r2.php

require_once __DIR__ . '/../vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// R2 Configuration
define('R2_ACCOUNT_ID', 'b1e3b02ffa903028e4fe0019d4294d82');
define('R2_ACCESS_KEY_ID', '7c1f8724731159cebd4de6120828bde0');
define('R2_SECRET_ACCESS_KEY', '94bd1a89e91faa9a853154d44266c28a6ac9285c2bc7a31b8e9b9978862dc13b');
define('R2_BUCKET_NAME', 'podcasts');
define('R2_PUBLIC_URL', 'https://pub-4a26074f63ae4203a6de95f3b950b21c.r2.dev');

function getR2Client() {
    return new S3Client([
        'version' => 'latest',
        'region'  => 'auto',
        'endpoint' => 'https://' . R2_ACCOUNT_ID . '.r2.cloudflarestorage.com',
        'credentials' => [
            'key'    => R2_ACCESS_KEY_ID,
            'secret' => R2_SECRET_ACCESS_KEY,
        ],
        'http' => [
            'verify' => false,
            'timeout' => 60
        ],
        'use_path_style_endpoint' => true
    ]);
}

function uploadToR2($filePath, $fileName, $contentType) {
    try {
        $client = getR2Client();
        
        $result = $client->putObject([
            'Bucket' => R2_BUCKET_NAME,
            'Key'    => $fileName,
            'Body'   => fopen($filePath, 'r'),
            'ContentType' => $contentType,
            'ACL'    => 'public-read',
        ]);
        
        // Use the public URL format
        $publicUrl = R2_PUBLIC_URL . '/' . $fileName;
        
        return [
            'success' => true,
            'url' => $publicUrl,
            'key' => $fileName
        ];
        
    } catch (AwsException $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

function deleteFromR2($fileName) {
    try {
        $client = getR2Client();
        
        $result = $client->deleteObject([
            'Bucket' => R2_BUCKET_NAME,
            'Key'    => $fileName,
        ]);
        
        return ['success' => true];
        
    } catch (AwsException $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}
?>