<?php

$GLOBALS['globals_branch_names_already_fetched'] = [];
$GLOBALS['globals_branch_ids_already_fetched'] = [];


function getBranchId($conn, $institution_id, $branch_name) {
    $branch_name_key = strtolower(trim($branch_name));

    // Check cache
    if (in_array($branch_name_key, $GLOBALS['globals_branch_names_already_fetched'])) {
        return $GLOBALS['globals_branch_ids_already_fetched'][
            array_search($branch_name_key, $GLOBALS['globals_branch_names_already_fetched'])
        ];
    }

    // Fetch from DB
    $stmt = $conn->prepare("SELECT id FROM branch WHERE name = ? AND institution_id = ?");
    $stmt->execute([$branch_name, $institution_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        errorreturn("Branch not found: '$branch_name'");
    }

    // Store in global cache
    $GLOBALS['globals_branch_names_already_fetched'][] = $branch_name_key;
    $GLOBALS['globals_branch_ids_already_fetched'][] = $result['id'];

    return $result['id'];
}




function copyImageFromAnotherBucketAndUpdate(
    $conn_rjllearning_specific,
    $s3_learning_bucket,
    $learning_bucketName,
    $profilephoto,
    $workspace_id,
    $institution_id,
    $student_id,
    $sourceBucket
) {
    $currentYear = date('Y');
    $currentMonth = date('m');
    $fileName = basename($profilephoto);

    // File parts
    $fileInfo = pathinfo($fileName);
    $fileBaseName = $fileInfo['filename'];
    $fileExtension = isset($fileInfo['extension']) ? '.' . $fileInfo['extension'] : '';

    // Destination keys for both tables
   $destinationKeyStudents = "user_uploads/{$workspace_id}/{$institution_id}/students/{$currentYear}/{$currentMonth}/{$student_id}/Students_Image_{$student_id}{$fileExtension}";

    $destinationKeyAdmission = "user_uploads/{$workspace_id}/{$institution_id}/student_admission/{$currentYear}/{$currentMonth}/{$student_id}/AdmissionImage_" . $student_id . $fileExtension;

    try {
        
        $copySource = "{$sourceBucket}/Profiles/{$profilephoto}";
        // Copy to students key
        $s3_learning_bucket->copyObject([
            'Bucket'     => $learning_bucketName,
            'Key'        => $destinationKeyStudents,
            'CopySource' => $copySource,
        ]);

        // Copy to student_admission key
        $s3_learning_bucket->copyObject([
            'Bucket'     => $learning_bucketName,
            'Key'        => $destinationKeyAdmission,
            'CopySource' => $copySource,
        ]);

        // Prepare JSON attachments
        $attachmentStudents = json_encode([
            'filepath' => $destinationKeyStudents,
            'original_name' => basename($destinationKeyStudents)
        ]);

        $attachmentAdmission = json_encode([
            'filepath' => $destinationKeyAdmission,
            'original_name' => basename($destinationKeyAdmission)
        ]);

        // Update students table
        $sql1 = "UPDATE students SET student_profile_image = ? WHERE id = ?";
        $conn_rjllearning_specific->prepare($sql1)->execute([$attachmentStudents, $student_id]);

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

        return true;

    } catch (Aws\Exception\AwsException $e) {
        return [
            'status' => false,
            'message' => 'AWS S3 Error: ' . $e->getAwsErrorMessage()
        ];
    } catch (PDOException $e) {
        return [
            'status' => false,
            'message' => 'Database Error: ' . $e->getMessage()
        ];
    } catch (Exception $e) {
        return [
            'status' => false,
            'message' => 'Unexpected Error: ' . $e->getMessage()
        ];
    }
}
