<?php
ini_set('display_errors', 1);
date_default_timezone_set('Asia/Kolkata');


function errorreturn($x, $conn = null, $errorstatus = 0)
{
    if ($conn and $conn->inTransaction()) {
        $conn->rollBack();
    }
    $errormsg['status'] = $errorstatus;
    $errormsg['response'] = $x;
    echo json_encode($errormsg, JSON_UNESCAPED_SLASHES);
    die();
}



// function errorreturn($x) {
//     $errormsg['status'] = 0;
//     $errormsg['response'] = $x;
//     echo json_encode($errormsg, JSON_UNESCAPED_SLASHES);
//     die();
// }



function successreturn($x)
{
    $sucessmsg['status'] = 1;
    $sucessmsg['response'] = $x;
    echo json_encode($sucessmsg, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE);
    die();
}


function checkIfIssetAndNotEmpty($x)
{
    if (isset($x) and !empty(trim($x))) {
        return true;
    } else return false;
}

function checkIfNoPhpContentsReceive()
{
    if (!file_get_contents("php://input")) {
        return errorreturn("Empty request");
    } else {
        return true;
    }
}

//checking email validation regex
function CheckEMailIsValidOrNot($x)
{
    if (isset($x) and filter_var($x, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else return false;
}


function removeKeys($data, $fields_to_remove)
{
    foreach ($data as &$d) {
        foreach ($fields_to_remove as $field) {
            unset($d[$field]);
        }
    }
    return $data;
}

function removeKeys2($data)
{
    foreach ($data as &$d) {

        unset($d);
    }
    return $data;
}


function getArrayValues($data)
{
    $result = [];
    foreach ($data as $d) {
        $list = array_values($d);
        $result[] = $list;
    }
    return $result;
}

function getArrayKeys($data)
{
    $keys = array_keys($data);
    // print_r($keys);
    return $keys;
}

function getCorrespondingValue($array, $x)
{
    // echo $array;
    foreach ($array as $key => $value) {
        if ($key === $x) {
            return $value;
        }
    }

    return $x;
}

function getDatesBetween($startDate, $endDate)
{
    $dates = [];

    // Convert the dates to DateTime objects
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);

    // Include the end date in the range
    $end = $end->modify('+1 day');

    // Use a DatePeriod to iterate over the date range
    $interval = new DateInterval('P1D'); // 1-day interval
    $dateRange = new DatePeriod($start, $interval, $end);

    // Loop through each date in the range
    foreach ($dateRange as $date) {
        $dates[] = $date->format('Y-m-d'); // Format the date as 'YYYY-MM-DD'
    }

    return $dates;
}

// function checkFileValidation($fileSize, $fileType, $file_extension, $allowed_file_size, $allowed_file_types, $allowed_file_extensions, $errormsg_for_type = null)
// {

//     if (!in_array($fileType, $allowed_file_types)) {
//         if ($errormsg_for_type == null) {
//             errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
//         } else {
//             errorreturn($errormsg_for_type);
//         }
//     }

//     if (!in_array($file_extension, $allowed_file_extensions)) {
//         errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
//     }

//     // provide max file size in MB.
//     if ($fileSize > ($allowed_file_size * 1024 * 1024)) {
//         errorreturn("Please upload a valid image  with a size less than $allowed_file_size MB");
//     }
// }

function checkFileValidation($fileSize, $fileType, $file_extension, $allowed_file_size, $allowed_file_types, $allowed_file_extensions, $errormsg_for_type = null)
{

    // if (!in_array($fileType, $allowed_file_types) ) {
    //     if ($errormsg_for_type == null) {
    //         errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
    //     } else {
    //         errorreturn($errormsg_for_type);
    //     }
    // }
    if (!in_array($fileType, $allowed_file_types) && $fileType != 'application/octet-stream') {
        errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
    } else {
        // Handle the case where the MIME type is application/octet-stream
        if ($fileType == 'application/octet-stream') {
            if (!in_array($file_extension, $allowed_file_extensions)) {
                errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
            }
        }
    }

    if (!in_array($file_extension, $allowed_file_extensions)) {
        errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
    }

    // provide max file size in MB.
    if ($fileSize > ($allowed_file_size * 1024 * 1024)) {
        errorreturn("Please upload a valid image  with a size less than $allowed_file_size MB");
    }
}


// Function to sanitize input curl api students data
function sanitizeInput($input)
{
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

function delete_Activity($activity_id, $conn_rjllearning_specific, $s3_learning_bucket, $bucket_name, $institution_id)
{
    try {
        // Step 1: Fetch the attachment file path associated with the activity
        $getFilePathQuery = "SELECT attachment FROM activity_mentor WHERE id = ? AND institution_id = ? ";
        $stmt = $conn_rjllearning_specific->prepare($getFilePathQuery);
        $stmt->execute([$activity_id, $institution_id]);

        // Fetch the row
        $attachmentRow = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$attachmentRow) {
            return ['status' => 'error', 'message' => 'No activity found with the provided ID.'];
        }

        // Decode the attachment field
        $attachmentData = json_decode($attachmentRow['attachment'], true);
        if (!$attachmentData || !isset($attachmentData['filepath'])) {
            return ['status' => 'error', 'message' => 'Invalid or empty attachment data.'];
        }

        $file_path = $attachmentData['filepath'];

        // Step 2: Delete the file from S3 using the awsS3UserUploadDelete function
        try {
            awsS3UserUploadDelete($s3_learning_bucket, $bucket_name, $conn_rjllearning_specific, $institution_id, $file_path, null, false);
        } catch (Exception $e) {
            // Log the error but continue with the activity deletion
            error_log('Error deleting file from S3: ' . $e->getMessage());
        }

        // Step 3: Delete the activity from the database
        $deleteActivityQuery = "DELETE FROM activity_mentor WHERE id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($deleteActivityQuery);
        $stmt->execute([$activity_id, $institution_id]);

        return ['status' => 'success', 'message' => 'Activity and attachment deleted successfully.'];
    } catch (Exception $e) {
        // Catch any unexpected errors
        return ['status' => 'error', 'message' => 'Error deleting activity: ' . $e->getMessage()];
    }
}

function delete_Assignment($assignment_id, $conn_rjllearning_specific, $s3_learning_bucket, $bucket_name, $institution_id)
{
    try {
        // Step 1: Fetch all attachment file paths associated with the assignment from the assignment_questions table
        $getFilePathsQuery = "SELECT question_attachment FROM assignment_questions WHERE assignment_id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($getFilePathsQuery);
        $stmt->execute([$assignment_id, $institution_id]);

        // Fetch all rows (for multiple attachments)
        $attachments = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Step 2: Loop through each attachment and delete from S3 if the attachment exists
        foreach ($attachments as $attachment) {
            $question_attachment = json_decode($attachment['question_attachment'], true);

            if ($question_attachment && isset($question_attachment['filepath'])) {
                $file_path = $question_attachment['filepath'];
                try {
                    // Use awsS3UserUploadDelete to delete the attachment from S3
                    awsS3UserUploadDelete($s3_learning_bucket, $bucket_name, $conn_rjllearning_specific, $institution_id, $file_path, null, false);
                    echo "File deleted from S3: $file_path\n"; // Optional: Debug message
                } catch (Exception $e) {
                    // Log the error if the file can't be deleted from S3
                    error_log('Error deleting file from S3: ' . $e->getMessage());
                }
            }
        }

        // Step 3: Delete rows from the assignment_questions table related to the assignment
        $deleteQuestionsQuery = "DELETE FROM assignment_questions WHERE assignment_id = ? AND institution_id = ? ";
        $stmt = $conn_rjllearning_specific->prepare($deleteQuestionsQuery);
        $stmt->execute([$assignment_id, $institution_id]);

        // Step 4: Delete the assignment itself from the assignments table
        $deleteAssignmentQuery = "DELETE FROM assignments WHERE id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($deleteAssignmentQuery);
        $stmt->execute([$assignment_id, $institution_id]);

        // Step 5: Delete related rows from the assignment_submission table
        $deleteSubmissionsQuery = "DELETE FROM assignment_submission WHERE assignment_id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($deleteSubmissionsQuery);
        $stmt->execute([$assignment_id, $institution_id]);

        return ['status' => 'success', 'message' => 'Assignment, related data, and all attachments deleted successfully.'];
    } catch (Exception $e) {
        return ['status' => 'error', 'message' => 'Error deleting assignment: ' . $e->getMessage()];
    }
}

function delete_Lesson($lesson_id, $conn_rjllearning_specific, $s3_learning_bucket, $bucket_name, $institution_id)
{
    try {
        // Step 1: Fetch the lesson and associated attachments
        $getLessonQuery = "SELECT audio_attachment, primary_attachment, cover_image 
                           FROM lessons 
                           WHERE id = ? AND institution_id = ? ";
        $stmt = $conn_rjllearning_specific->prepare($getLessonQuery);
        $stmt->execute([$lesson_id, $institution_id]);

        $lessonRow = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$lessonRow) {
            return ['status' => 'error', 'message' => 'No lesson found with the provided ID.'];
        }

        // Decode JSON fields if not null
        $audio_attachment = !empty($lessonRow['audio_attachment']) ? json_decode($lessonRow['audio_attachment'], true) : null;
        $primary_attachment = !empty($lessonRow['primary_attachment']) ? json_decode($lessonRow['primary_attachment'], true) : null;
        $cover_image = !empty($lessonRow['cover_image']) ? json_decode($lessonRow['cover_image'], true) : null;

        // Step 2: Delete attachments from S3
        try {
            if ($audio_attachment && isset($audio_attachment['filepath'])) {
                awsS3UserUploadDelete($s3_learning_bucket, $bucket_name, $conn_rjllearning_specific, $institution_id, $audio_attachment['filepath'], null, false);
            }

            if ($primary_attachment && isset($primary_attachment['filepath'])) {
                awsS3UserUploadDelete($s3_learning_bucket, $bucket_name, $conn_rjllearning_specific, $institution_id, $primary_attachment['filepath'], null, false);
            }

            if ($cover_image && isset($cover_image['filepath'])) {
                awsS3UserUploadDelete($s3_learning_bucket, $bucket_name, $conn_rjllearning_specific, $institution_id, $cover_image['filepath'], null, false);
            }
        } catch (Exception $e) {
            // Log any issues with S3 deletion but proceed with lesson deletion
            error_log('Error deleting file from S3: ' . $e->getMessage());
        }

        // Step 3: Delete the lesson from the database
        $deleteLessonQuery = "DELETE FROM lessons WHERE id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($deleteLessonQuery);
        $stmt->execute([$lesson_id, $institution_id]);

        if ($stmt->rowCount() > 0) {
            return ['status' => 'success', 'message' => 'Lesson and associated attachments deleted successfully.'];
        } else {
            return ['status' => 'error', 'message' => 'Failed to delete lesson.'];
        }
    } catch (Exception $e) {
        // Catch any unexpected errors
        error_log('Error in delete_Lesson: ' . $e->getMessage());
        return ['status' => 'error', 'message' => 'Error deleting lesson: ' . $e->getMessage()];
    }
}

