<?php
ini_set('display_errors', 1);

require_once '../../../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';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.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/task_schedule/task_scheduler_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/activity_mentor/activity_functions.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = $_POST;
// $postdata = json_decode(file_get_contents("php://input"), true);

// Define an array of required fields with their corresponding values
$required_fields = [
    'institution_id',
    'title',
    'description',
    'type',
    'api_signature',
    'function_type',
    'jwt_token'
];

// Iterate over the array and validate each field
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
    }
}

// Optional: Add a check for 'featured_bool' if it needs to be validated specifically
if (isset($postdata['featured_bool']) && !is_numeric($postdata['featured_bool'])) {
    errorreturn('featured_bool must be a numeric value.');
}


validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';


$institution_id = trim($postdata['institution_id']);
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}


$class_id = $postdata['class_id'];
$section_id = $postdata['section_id'];
$student_id = $postdata['student_id'];



$type = trim($postdata['type']);
$allowed_types = ['normal', 'festival'];

if (!in_array($type, $allowed_types)) {
    errorreturn("Invalid type. Allowed values are: normal, festival, important.");
}

$description = trim($postdata['description']);
// $type = trim($postdata['type']);
$title = trim($postdata['title']);
$featured_bool = isset($postdata['featured_bool']) ? trim($postdata['featured_bool']) : 0;

if (isset($postdata['tags']) && is_array($postdata['tags'])) {
    // You can use it directly without json_decode
    $tags = $postdata['tags']; // Directly assign the array

    // If you need to encode it to JSON for some reason
    $tag_encode = json_encode($tags);
} else {
    // Handle the case when tags are not set or not an array
    $tag_encode = json_encode([]); // or whatever default behavior you want
}

$currenttime = time();

$publish_date = (isset($postdata['publish_date']) and !empty($postdata['publish_date'])) ? trim(date('Y-m-d', strtotime($postdata['publish_date']))) : date("Y-m-d");
$publish_time = (isset($postdata['publish_time']) && !empty($postdata['publish_time']))
    ? trim($postdata['publish_time'])
    : date('H:i'); // Use colons for time format

$terminate_date = (isset($postdata['termination_date']) && !empty($postdata['termination_date'])) ? trim(date('Y-m-d', strtotime($postdata['termination_date']))) : null;
$termination_time = (isset($postdata['termination_time']) && !empty($postdata['termination_time'])) ? trim($postdata['termination_time']) : null;

$today_date = date('Y-m-d');
if ($publish_time !== null) {
    if (!CheckValidateTime($publish_time)) {
        errorreturn('Invalid publish time');
    }
}

if ($termination_time !== null) {
    if (!CheckValidateTime($termination_time)) {
        errorreturn('Invalid termination time');
    }
}

compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $publish_date, null, true);

$attachment = (isset($_FILES['attachment']) and !empty($_FILES['attachment'])) ? $_FILES['attachment'] : null;

// Check if 'branch_id' is set and is an array
if (isset($postdata['branch_id']) && is_array($postdata['branch_id'])) {
    $branch_id = $postdata['branch_id']; // Use it directly

    // Check if the first element is 'all'
    if (count($branch_id) === 1 && $branch_id[0] === 'all') {
        // If 'all' is present, no need for further checks
        $json_branch_id = 'all';
    } else {
        // Handle the case when 'all' is not present
        if (count($branch_id) <= 0) {
            errorreturn("Select at least one branch.");
        }

        // Prepare the branch IDs for SQL query
        $imploded_branch_ids = "('" . implode("','", $branch_id) . "')";
        $count_ids = count($branch_id);

        // Prepare the SQL statement
        $sql_codes = $conn_rjllearning_specific->prepare("SELECT count(*) as total FROM branch WHERE id IN $imploded_branch_ids AND status = ?");
        $sql_codes->execute(array('1'));

        // Fetch the total count of branches
        $result_branch = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];

        // Validate that the number of found branches matches the expected count
        if ($result_branch != $count_ids) {
            errorreturn("Branch Not Found.");
        }

        // Encode the valid branch IDs
        $json_branch_id = json_encode($branch_id);
    }
} else {
    errorreturn("Select one branch.");
}


// Handle class_id
if (isset($postdata['class_id']) && is_array($postdata['class_id'])) {
    $class_id = $postdata['class_id']; // Use it directly

    if (count($class_id) === 1 && $class_id[0] === 'all') {
        // If 'all' is present, no need for further checks
        $json_class_id = 'all';
    } else {
        // Handle the case when 'all' is not present
        if (count($class_id) <= 0) {
            errorreturn("Select at least one class.");
        }

        // Prepare the class IDs for SQL query
        $imploded_class_ids = "('" . implode("','", $class_id) . "')";
        $count_ids = count($class_id);

        // Prepare the SQL statement
        $sql_codes = $conn_rjllearning_specific->prepare("SELECT count(*) as total FROM class_info WHERE id IN $imploded_class_ids AND status = ?");
        $sql_codes->execute(array('1'));

        // Fetch the total count of classes
        $result_class = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];

        // Validate that the number of found classes matches the expected count
        if ($result_class != $count_ids) {
            errorreturn("Class Not Found.");
        }

        // Encode the valid class IDs
        $json_class_id = json_encode($class_id);
    }
} else {
    errorreturn("Select at least one class.");
}

// Handle section_id
if (isset($postdata['section_id']) && is_array($postdata['section_id'])) {
    $section_id = $postdata['section_id']; // Use it directly

    if (count($section_id) === 1 && $section_id[0] === 'all') {
        // If 'all' is present, no need for further checks
        $json_section_id = 'all';
    } else {
        // Handle the case when 'all' is not present
        if (count($section_id) <= 0) {
            errorreturn("Select at least one section.");
        }

        // Prepare the section IDs for SQL query
        $imploded_section_ids = "('" . implode("','", $section_id) . "')";
        $count_ids = count($section_id);

        // Prepare the SQL statement
        $sql_codes = $conn_rjllearning_specific->prepare("SELECT count(*) as total FROM section_info WHERE id IN $imploded_section_ids AND status = ?");
        $sql_codes->execute(array('1'));

        // Fetch the total count of sections
        $result_section = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];

        // Validate that the number of found sections matches the expected count
        if ($result_section != $count_ids) {
            errorreturn("Section Not Found.");
        }

        // Encode the valid section IDs
        $json_section_id = json_encode($section_id);
    }
} else {
    errorreturn("Select at least one section.");
}

// Check if student_id is set and decode it
if (isset($postdata['student_id']) && !empty($postdata['student_id'])) {
    $student_id = $postdata['student_id']; // Use it directly

    // Check if "all" is selected
    if (is_array($student_id) && count($student_id) === 1 && $student_id[0] === 'all') {
        // If 'all' is present, no further checks are required
        $json_student_id = 'all';
    } else {
        // Ensure $student_id is a valid array with at least one element
        if (!is_array($student_id) || count($student_id) === 0) {
            errorreturn("Select at least one student.");
        }

        // Prepare the student IDs for the SQL query
        $imploded_student_ids = "('" . implode("','", array_map('intval', $student_id)) . "')";
        $count_ids = count($student_id);

        // Check if all provided students are valid and active
        $sql_codes = $conn_rjllearning_specific->prepare(
            "SELECT COUNT(*) AS total FROM students WHERE user_id IN $imploded_student_ids AND status = ?"
        );
        $sql_codes->execute(['1']);

        // Fetch the total count of valid students
        $result_student = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];

        // Ensure the number of valid students matches the input count
        if ($result_student != $count_ids) {
            errorreturn("One or more students are not found or inactive.");
        }

        // Encode the valid student IDs to JSON
        $json_student_id = json_encode($student_id);
    }
} else {
    errorreturn("Student ID is required.");
}

if ($postdata['function_type'] == "create_activity_mentor") {

    $res = $conn_rjllearning_specific->prepare("SELECT id FROM activity_mentor WHERE institution_id =?   AND title=? ");
    $res->execute(array($institution_id, $title));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("activity already exists.");
    }

    if ($publish_date !== null) {
        if ($publish_date < $today_date) {
            // Publish date is less than today's date, show an error
            errorreturn("Publish date cannot be less than today's date.");
        }

        if ($terminate_date !== null && $publish_date > $terminate_date) {
            // Publish date is after termination date
            errorreturn('Publish date cannot be after termination date.');
        }
    }

    if ($publish_time !== null) {
        if ($publish_date !== null) {
            $publish_datetime = $publish_date . ' ' . $publish_time;
        } else {
            $publish_datetime = $publish_time;
        }

        if ($terminate_date !== null) {
            if ($termination_time !== null) {
                $termination_datetime = $terminate_date . ' ' . $termination_time;
            } else {
                $termination_datetime = $terminate_date . ' 23:59:59'; // Assume end of day if no time is provided
            }

            if ($publish_datetime > $termination_datetime) {
                // Publish datetime is after termination datetime
                errorreturn('Publish datetime cannot be after termination datetime.');
            }
        }
    }

    // Check if 'attachment' field is set and has files
    if (!isset($_FILES['attachment']) || !is_array($_FILES['attachment']['name']) || empty($_FILES['attachment']['name'])) {
        $attachmentsArray = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/activity/" . $currentYear . "/" . $currentMonth . "/";

        // Initialize an array to store attachment details
        $attachmentsArray = [];

        // Loop through each file in the 'attachment' field and validate before inserting
        foreach ($_FILES['attachment']['name'] as $key => $file_name) {
            if (!empty($file_name)) { // Ensure file name is not empty
                // Get file details
                $fileTmpName = $_FILES['attachment']["tmp_name"][$key];
                $fileSize = $_FILES['attachment']["size"][$key];
                $fileType = $_FILES['attachment']["type"][$key];
                $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                // Define allowed file types and extensions for images, videos, audio, and documents
                $allowedTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                    'image/heic', // Images
                    'video/mp4',
                    'video/avi',
                    'video/mkv',
                    'video/mov',
                    'video/webm', // Videos
                    'audio/mpeg',
                    'audio/wav',
                    'audio/aac',
                    'audio/flac',
                    'audio/ogg'
                ];

                $allowed_extensions = [
                    'jpg',
                    'jpeg',
                    'png',
                    'gif',
                    'heic', // Image extensions
                    'mp4',
                    'avi',
                    'mkv',
                    'mov',
                    'webm',  // Video extensions
                    'mp3',
                    'wav',
                    'aac',
                    'flac',
                    'ogg'  // Audio extensions
                ];

                $maxFileSize = 500 * 1024 * 1024; // 500MB maximum file size

                // Validate file type, size, and extension
                checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
            }
        }
    }

    // **STEP 2: Insert activity into the database without attachment**
    try {
        $sql = "INSERT INTO activity_mentor (
                institution_id, branch_id, class_id, section_id, student_id, type, tags, title, description, attachment, 
                featured_bool, publish_date, publish_time, termination_date, termination_time, created_by, last_modified_by, date_created, time_created, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $json_student_id = isset($json_student_id) ? $json_student_id : null;
        $stmt->execute([
            $institution_id,
            $json_branch_id,
            $json_class_id,
            $json_section_id,
            $json_student_id,
            $type,
            $tag_encode,
            $title,
            $description,
            null, // Initially NULL
            $featured_bool,
            $publish_date,
            $publish_time,
            $terminate_date,
            $termination_time,
            $username,
            null,
            date('Y-m-d'),
            time(),
            1
        ]);

        $id = $conn_rjllearning_specific->lastInsertId(); // Get inserted ID

        // **STEP 3: Upload files and collect file paths**
        if ($attachmentsArray !== null) {
            foreach ($_FILES['attachment']['name'] as $key => $file_name) {
                if (!empty($file_name)) {
                    // Get file details
                    $fileTmpName = $_FILES['attachment']["tmp_name"][$key];
                    $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                    // Construct file name using ID instead of uniqid()
                    $newFileName = time() . "_" . $id . "_" . $key . "." . $file_extension;
                    $filePath = $directoryPathMain . $newFileName;

                    // Upload file to S3 or local storage
                    try {
                        $s3_learning_bucket->putObject([
                            'Bucket' => $learning_bucketName,
                            'Key' => $filePath,
                            'SourceFile' => $fileTmpName,
                        ]);
                    } catch (Exception $e) {
                        errorreturn($e->getMessage());
                    }

                    // Store attachment details
                    $attachmentsArray[] = ["filepath" => $filePath, "original_name" => $file_name];
                }
            }

            // Convert attachments to JSON
            $attachmentJson = json_encode($attachmentsArray);

            // **STEP 4: Update the attachment field**
            $updateSql = "UPDATE activity_mentor SET attachment = ? WHERE id = ?";
            $updateStmt = $conn_rjllearning_specific->prepare($updateSql);
            $updateStmt->execute([$attachmentJson, $id]);
        }

        // **Send notification after successful insertion**
        sendActivityMentorNotification($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $json_student_id, $title, $workspace_id, $web_app_title);
        successreturn(['id' => $id, 'successmsg' => "Activity successfully added."]);
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
    }
} else if ($postdata['function_type'] == "alter_activity_mentor") {

    if (!isset($postdata['activity_mentor_id']) or !checkIfIssetAndNotEmpty($postdata['activity_mentor_id'])) {
        errorreturn('Error in updating the activity.');
    } else {
        $id = $postdata['activity_mentor_id'];
    }

    // Fetch existing attachment
    $stmt = $conn_rjllearning_specific->prepare("SELECT attachment FROM activity_mentor WHERE id = ? AND institution_id = ?");
    $stmt->execute([$id, $institution_id]);
    $existing_attachment_json = $stmt->fetchColumn();
    $existing_attachments = $existing_attachment_json ? json_decode($existing_attachment_json, true) : [];

    if (isset($postdata['delete_attachment']) && is_array($postdata['delete_attachment'])) {
        foreach ($postdata['delete_attachment'] as $attachmentUrl) {
            // Parse URL to extract the S3 key path
            $urlParts = parse_url($attachmentUrl);
            $filePathToDelete = ltrim($urlParts['path'], '/');

            // Remove query parameters if present
            if (strpos($filePathToDelete, '?') !== false) {
                $filePathToDelete = substr($filePathToDelete, 0, strpos($filePathToDelete, '?'));
            }

            // Delete from S3
            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePathToDelete, null, null);

            // Remove from existing attachments array
            $existing_attachments = array_filter($existing_attachments, function ($attachment) use ($filePathToDelete) {
                return $attachment['filepath'] === $filePathToDelete ? false : true;
            });
        }
    }

    // Process new file uploads if file_attached array is provided
    $new_attachments = [];
    if (isset($_FILES['file_attached']) && is_array($_FILES['file_attached']['name']) && !empty($_FILES['file_attached']['name'][0])) {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/activity/" . $currentYear . "/" . $currentMonth . "/";

        foreach ($_FILES['file_attached']['name'] as $key => $file_name) {
            if (!empty($file_name)) {
                // Get file details
                $fileTmpName = $_FILES['file_attached']["tmp_name"][$key];
                $fileSize = $_FILES['file_attached']["size"][$key];
                $fileType = $_FILES['file_attached']["type"][$key];
                $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                // Allowed types
                $allowedTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                    'image/heic',
                    'video/mp4',
                    'video/avi',
                    'video/mkv',
                    'video/mov',
                    'video/webm',
                    'audio/mpeg',
                    'audio/wav',
                    'audio/aac',
                    'audio/flac',
                    'audio/ogg'
                ];
                $allowed_extensions = [
                    'jpg',
                    'jpeg',
                    'png',
                    'gif',
                    'heic',
                    'mp4',
                    'avi',
                    'mkv',
                    'mov',
                    'webm',
                    'mp3',
                    'wav',
                    'aac',
                    'flac',
                    'ogg'
                ];
                $maxFileSize = 500 * 1024 * 1024;

                // Validate file
                checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

                // Generate file name
                $newFileName = time() . "_" . $id . "_" . $key . "." . $file_extension;
                $filePath = $directoryPathMain . $newFileName;

                // Upload file to S3
                try {
                    $s3_learning_bucket->putObject([
                        'Bucket' => $learning_bucketName,
                        'Key' => $filePath,
                        'SourceFile' => $fileTmpName,
                    ]);
                } catch (Exception $e) {
                    errorreturn($e->getMessage());
                }

                // Store new attachment details
                $new_attachments[] = ["filepath" => $filePath, "original_name" => $file_name];
            }
        }
    }

    // Merge remaining existing attachments with new attachments
    $final_attachments = array_merge($existing_attachments, $new_attachments);
    $final_attachments_json = !empty($final_attachments) ? json_encode($final_attachments) : null;

    // Update activity data including attachments
    $sql_update = "UPDATE activity_mentor SET
        branch_id = ?, 
        class_id = ?, 
        section_id = ?, 
        student_id = ?, 
        publish_date = ?, 
        publish_time = ?, 
        termination_date = ?, 
        termination_time = ?, 
        description = ?, 
        type = ?, 
        tags = ?, 
        title = ?, 
        featured_bool = ?, 
        attachment = ?,
        last_modified_by = ?
    WHERE id = ? AND institution_id = ?";

    $conn_rjllearning_specific->prepare($sql_update)->execute([
        $json_branch_id,
        $json_class_id,
        $json_section_id,
        $json_student_id,
        $publish_date,
        $publish_time,
        $terminate_date,
        $termination_time,
        $description,
        $type,
        $tag_encode,
        $title,
        $featured_bool,
        $final_attachments_json,
        $username,
        $id,
        $institution_id
    ]);

    // Handle Scheduler
    if ($currenttime == strtotime($publish_time)) {
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'activity', $id, $publish_date, (time() + 120), 1, 'alter');
    } else {
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'activity', $id, $publish_date, strtotime($publish_time), 1, 'alter');
    }

    successreturn("Updated activity successfully.");

    // file_attached
    // delete_attachment(key)
}
