<?php
require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/staff/staff_details/staff_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/import/left_student_import/function.php';
require_once $base_path_to_learning . 'functions/cache_student_academic_function.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_add_alter_student_ledgers_finware.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning . 'admin_api/modules/student_registration/functions/functions.php';

use Aws\Exception\AwsException;
?>

<!DOCTYPE html>
<html>
<head>
    <title>Test S3 Image Copy</title>
</head>
<body>
    <h2>Copy Image from Source Bucket to Destination</h2>
    <form method="POST">
        <label>Source Bucket:</label> <input type="text" name="sourceBucket" value="live-gvis" required><br><br>
        <label>Image Path in Source (e.g. Profiles/0469.jpg):</label> <input type="text" name="profilephoto" required><br><br>
        <label>Workspace ID:</label> <input type="text" name="workspace_id" value="1" required><br><br>
        <label>Institution ID:</label> <input type="text" name="institution_id" value="1" required><br><br>
        <label>Student ID:</label> <input type="text" name="student_id" value="469" required><br><br>
        <input type="submit" name="submit" value="Copy Image">
    </form>

<?php
if (isset($_POST['submit'])) {
    $sourceBucket = trim($_POST['sourceBucket']);
    $profilephoto = trim($_POST['profilephoto']);
    $workspace_id = intval($_POST['workspace_id']);
    $institution_id = intval($_POST['institution_id']);
    $student_id = intval($_POST['student_id']);
    $learning_bucketName = 'rjlbilldesk-development';
    
    $specific_db_name = validateUserAccess($conn_rjllearning, "30", "superadmin", $workspace_id, ["superadmin", "admin", "principal", "teacher"], null);
    if (!$specific_db_name) {
        errorreturn('Access denied.');
    }
   $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);


    $currentYear = date('Y');
    $currentMonth = date('m');
    $fileName = basename($profilephoto);

    $fileInfo = pathinfo($fileName);
    $fileBaseName = $fileInfo['filename'];
    $fileExtension = isset($fileInfo['extension']) ? '.' . $fileInfo['extension'] : '';
    $newFileName = $fileBaseName . "_Image_" . $student_id . $fileExtension;

    $destinationKey = "user_uploads/{$workspace_id}/{$institution_id}/students/{$currentYear}/{$currentMonth}/{$student_id}/{$newFileName}";

    try {
        $copySource = "{$sourceBucket}/Profiles/{$profilephoto}";
        
        
        

        $result = $s3_learning_bucket->copyObject([
            'Bucket'     => $learning_bucketName,
            'Key'        => $destinationKey,
            'CopySource' => $copySource,
        ]);

        // Store path in student_admission table
        $attachmentAdmission = json_encode([
            'filepath' => $destinationKey,
            'original_name' => basename($destinationKey)
        ]);

        $sql2 = "UPDATE student_admission SET profile_image = ? WHERE student_id = ?";
        $stmt2 = $conn_rjllearning_specific->prepare($sql2);
        $stmt2->execute([$attachmentAdmission, $student_id]);

        echo "<p style='color: green;'>✅ File copied successfully to: <strong>$destinationKey</strong></p>";
    } catch (AwsException $e) {
        $errorMessage = "AWS S3 Error: " . $e->getAwsErrorMessage();
        file_put_contents('s3_copy_error.log', date('Y-m-d H:i:s') . " - " . $errorMessage . PHP_EOL, FILE_APPEND);
        echo "<p style='color: red;'>❌ $errorMessage</p>";
    } catch (Exception $e) {
        $errorMessage = "General Error: " . $e->getMessage();
        file_put_contents('s3_copy_error.log', date('Y-m-d H:i:s') . " - " . $errorMessage . PHP_EOL, FILE_APPEND);
        echo "<p style='color: red;'>❌ $errorMessage</p>";
    }
}
?>
</body>
</html>
