<?php
// require 'vendor/autoload.php';
require 'external/aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\DynamoDb\DynamoDbClient;

use Aws\S3\Exception\S3Exception;

// $bucket = '*** Your Bucket Name ***';
// $keyname = '*** Your Object Key ***';
function GUID()
{
    if (function_exists('com_create_guid') === true) {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

define("ECDN_SECRET_KEY", "W3nYL6grTFH4QtEn");


function decrypt_file1($encryptedContent, $key)
{
    $iv = str_repeat("\0", 16); // must match encrypt
    $decrypted = openssl_decrypt(
        $encryptedContent,
        'aes-128-cfb',
        $key,
        OPENSSL_RAW_DATA,
        $iv
    );
    return $decrypted;
}


function encrypt_file1($source, $destination, $key)
{
    $iv = str_repeat("\0", 16); // 16 bytes for AES-128
    if (!is_file($source)) {
        return false;
    }

    $sourceContent = file_get_contents($source);
    if ($sourceContent === false) {
        return false;
    }

    // AES-128-CFB encryption
    $encryptedSource = openssl_encrypt(
        $sourceContent,
        'aes-128-cfb',
        $key,
        OPENSSL_RAW_DATA,
        $iv
    );

    if ($encryptedSource === false) {
        return false;
    }

    if (file_put_contents($destination, $encryptedSource, LOCK_EX) === false) {
        return false;
    }

    return true;
}
function s4_cloud_upload($quizId, $sectionId, $selectedQuizText, $selectedCourseId, $selectedCourseText, $selectedOrgId, $selectedOrgText, $start_date, $end_date, $seb_required,$target_college_list,$clgId)
{

    $region = 'ap-south-1';
    $version = 'latest';
    // $access_key_id = 'AKIA4ROQEOUP4XZNNHHA'; 
    // $secret_access_key = '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'; 
    $secret_access_key = '3x/C8lc/NRaVYBIo1JZaVb+P4j5Qqrui9iowq1py';
    $access_key_id = 'AKIAU35OCLBBBZZLUSPE';
    $bucket = 'quiklrnexam';
    $s3 = new S3Client([
        'version' => $version,
        'region' => $region,
        'credentials' => [
            'key' => $access_key_id,
            'secret' => $secret_access_key,
        ]
    ]);
    $ddb = new DynamoDbClient([
        'version' => 'latest',
        'region' => $region,
        'credentials' => [
            'key' => $access_key_id,
            'secret' => $secret_access_key,
        ]
    ]);
    $gUid = GUID();
    $file_name = $quizId . "/" . $sectionId . "/quiz_" . $quizId . "_" . $sectionId . ".qquiz";

    $file_temp_src = "../../../tmp/quizFile/quiz_" . $quizId . "_" . $sectionId . ".qquiz";

    // temporary encrypted file path
    $file_encrypted_src = "../../../tmp/quizFile/quiz_" . $quizId . "_" . $sectionId . "_enc.qquiz";

    // ---------------------------Decrypt Code-----------------------------

    // $decrypted_file = "../../../tmp/quizFile/quiz_".$quizId."_".$sectionId."_dec.qquiz";

    //     // read encrypted file content
    //     $encryptedContent = file_get_contents($file_encrypted_src);

    //     // decrypt using our OpenSSL function
    //     $decryptedContent = decrypt_file1($encryptedContent, ECDN_SECRET_KEY);

    //     if ($decryptedContent === false) {
    //         echo "❌ Decryption failed!";
    //         die;
    //     }

    //     // save decrypted file
    //     file_put_contents($decrypted_file, $decryptedContent);

    //     echo "✅ File decrypted and saved at: ".$decrypted_file;
    //     die;

    // ---------------------------Decrypt Code-----------------------------

    // $decrypted = decrypt_file1($file_encrypted_src,ECDN_SECRET_KEY);

    // 🔒 Encrypt before upload
    $enc_status = encrypt_file1($file_temp_src, $file_encrypted_src, ECDN_SECRET_KEY);

    if (!$enc_status) {
        return ['status_code' => 500, 'msg' => "Encryption failed!", 'objectURI' => ''];
    }



    try {
        $result = $s3->putObject([
            'Bucket' => $bucket,
            'Key' => $file_name,
            // 'ACL' => 'public-read',
            'SourceFile' => $file_encrypted_src,  // 🚀 upload encrypted file

        ]);
        $result_arr = $result->toArray();

        $s3_file_link = $result['ObjectURL'];
        
        
        // 📝 Store in DynamoDB
        $ddb->putItem([
            'TableName' => 'quiz',
            'Item' => [
                'quiz_name' => ['S' => $selectedQuizText],
                'host_college_id' => ['S' => (string) $clgId],
                'quiz_id' => ['S' => (string) $quizId],
                'quiz_file_link' => ['S' => $s3_file_link],
                'course_id' => ['S' => (string) $selectedCourseId],
                'course_name' => ['S' => $selectedCourseText],
                'start_time' => ['S' => (string) $start_date],
                'end_time' => ['S' => (string) $end_date],
                'seb_required' => ['N' => (string) $seb_required],
                // 'target_college_list' => [
                //     'L' => [
                //         [
                //             'M' => [
                //                 'college_id' => ['S' => '1'],
                //                 'college_name' => ['S' => 'Quiklrn College']
                //             ]
                //         ]
                //     ]
                // ]
                'target_college_list' => ['L' => $target_college_list]
            ]
        ]);

        $statusMsg = [
            'status_code' => 200,
            'message' => "File uploaded & stored successfully!",
            'objectURI' => $s3_file_link
        ];


        // var_dump($statusMsg);
        if (!empty($result_arr['ObjectURL'])) {
            $s3_file_link = $result_arr['ObjectURL'];
        } else {
            $api_error = 'Upload Failed! S3 Object URL not found.';
        }
    } catch (Aws\S3\Exception\S3Exception $e) {
        $api_error = "Message" . $e->getMessage();
    }

    // if (empty($api_error)) {
    //     $status = 'success';
    //     $statusMsg = ['status_code' => 200, 'msg' => "File was uploaded to the S3 bucket successfully!", 'objectURI' => S3_BASE_URI . $file_name];
    // } else {
    //     $statusMsg = ['status_code' => 401, 'msg' => $api_error, 'objectURI' => ''];
    // }
    return $statusMsg;

}

function s4_cloud_upload1($fromUserId)
{
    $region = 'ap-south-1';
    $version = 'latest';
    $secret_access_key = '3x/C8lc/NRaVYBIo1JZaVb+P4j5Qqrui9iowq1py';
    $access_key_id = 'AKIAU35OCLBBBZZLUSPE';
    $bucket = 'quiklrnexam';
    $s3 = new S3Client([
        'version' => $version,
        'region' => $region,
        'credentials' => [
            'key' => $access_key_id,
            'secret' => $secret_access_key,
        ]
    ]);
    $gUid = GUID();
    $file_name = $fromUserId . "/" . $gUid . ".qquiz";
    $file_temp_src = "../../../tmp/output.csv";

    try {
        $result = $s3->putObject([
            'Bucket' => $bucket,
            'Key' => $file_name,
            'SourceFile' => $file_temp_src,
        ]);
        $result_arr = $result->toArray();

        if (!empty($result_arr['ObjectURL'])) {
            $s3_file_link = $result_arr['ObjectURL'];
        } else {
            $api_error = 'Upload Failed! S3 Object URL not found.';
        }
    } catch (Aws\S3\Exception\S3Exception $e) {
        $api_error = "Message: " . $e->getMessage();
    }

    if (empty($api_error)) {
        $status = 'success';
        $statusMsg = ['status_code' => 200, 'msg' => "File uploaded successfully!", 'objectURI' => S3_BASE_URI . $file_name];
    } else {
        $statusMsg = ['status_code' => 401, 'msg' => $api_error, 'objectURI' => ''];
    }
    return $statusMsg;
}

function sa4_cloud_upload()
{
    $bucket = 'quiklrnreports';
    $keyname = 'AKIA4ROQEOUP4XZNNHHA';

    $s3 = new S3Client([
        'version' => 'latest',
        'region' => 'ap-south-1'
    ]);

    try {
        // Upload data.
        $result = $s3->putObject([
            'Bucket' => $bucket,
            'Key' => $keyname,
            'Body' => 'Hello, world!',
            'ACL' => 'public-read'
        ]);

        // Print the URL to the object.
        echo $result['ObjectURL'] . PHP_EOL;
    } catch (S3Exception $e) {
        echo $e->getMessage() . PHP_EOL;
    }
}


?>