<?php
/**
 * Plugin Name: ULesson Cloud Storage
 * Description: Connects WordPress LMS to Oracle Cloud Storage.
 */

require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
use Aws\S3\S3Client;

// 1. The function to connect to Oracle Cloud
function get_oci_client() {
    return new S3Client([
        'version'     => 'latest',
        'region'      => 'af-casablanca-1', // Your region
        'endpoint'    => 'https://axnegx2emcvn.compat.objectstorage.af-casablanca-1.oraclecloud.com',
        'use_path_style_endpoint' => true, // <--- ADD THIS LINE TO FIX THE SSL CERTIFICATE ERROR
        'credentials' => [
            'key'    => 'b23e3b53d1d142668bd4a89db53aeba7979f4d32',
            'secret' => 'ci/O3T5LiQsJRmaJRCTwHLXPE92OKg0QQ/QbXhPEzH4=',
        ],
    ]);
}

// 2. The API Endpoint to get a secure upload link
add_action('rest_api_init', function () {
    register_rest_route('ulesson/v1', '/get-upload-url/', [
        'methods' => 'POST',
        'callback' => 'generate_oci_upload_link',
        'permission_callback' => '__return_true' // In production, change to is_user_logged_in
    ]);
});

function generate_oci_upload_link($request) {
    $s3 = get_oci_client();
    $filename = 'lessons/' . sanitize_file_name($request->get_param('filename'));
    
    $cmd = $s3->getCommand('PutObject', [
        'Bucket' => 'lms-lesson-assets',
        'Key'    => $filename,
    ]);

    $presignedRequest = $s3->createPresignedRequest($cmd, '+20 minutes');
    return ['url' => (string)$presignedRequest->getUri()];
}