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

require_once '../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
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';

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

// $postdata = json_decode(file_get_contents("php://input"), true);
$postdata = $_POST;
// checkIfNoPhpContentsReceive();
// print_r($postdata);die();
if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or
    !isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id']) or
    !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['message']) or !checkIfIssetAndNotEmpty($postdata['message']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

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']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$branch_id = trim($postdata['branch_id']);
$title = ucwords(strtolower(trim($postdata['title'])));
$message = trim($postdata['message']);
$attachment = (isset($_FILES['attachment']) and !empty($_FILES['attachment'])) ? $_FILES['attachment'] : null;
$date_now = date('Y-m-d');
$time_now = time();


$currenttime = time();

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

validateBranchClassSection($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $support_branch_all = 1, $checkClass = 0, $support_class_all = 0, $checkSection = 0,  $support_section_all = 1);

$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, null, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied");
}

$function_type = $postdata['function_type'];

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

    $res = $conn_rjllearning_specific->prepare("SELECT id FROM announcement WHERE institution_id = ? AND academic_id = ? AND branch_id = ? AND class_id = ?  AND section_id = ? AND title = ? and date_created = ?");
    $res->execute(array($institution_id, $academic_id, $branch_id, $class_id, $section_id, $title, $date_now));
    $result1 = $res->fetchAll();

    if (count($result1) >= 1) {
        errorreturn("This announcement already exists. ");
    }


    if ($attachment == null) {
        $attachment = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay =  date('d');
        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/announcement/" . $currentYear . "/" . $currentMonth . "/";
        $file_name = $_FILES['attachment']['name'];
        $fileTmpName = $_FILES['attachment']["tmp_name"];
        $fileSize = $_FILES['attachment']["size"];
        $fileType = $_FILES['attachment']["type"];
        $fileError = $_FILES['attachment']["error"];
        $file_extension = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ]; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    try {

        $sql = "INSERT INTO announcement(institution_id,academic_id,branch_id,class_id,section_id,title,message,attachment,date_created,time_created,added_by,status)
         VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);

        $stmt->execute(array($institution_id, $academic_id, $branch_id, $class_id, $section_id, $title, $message, null, $date_now, $time_now, $username, '1'));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }

    $announcement_id = $conn_rjllearning_specific->lastInsertId();

    if ($attachment !=  null) {
        $image_name = "announcement_" . $announcement_id . "." . $file_extension; // Define the image name dynamically
        $announcement_path = $directoryPathMain . $image_name; // Create the full path for the logo
        awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $announcement_path, $multiple_files_bool = false, $multiple_file_index = 0);
        $attachment_image = json_encode(array("filepath" => $announcement_path, "original_name" => $file_name));
        $sql_logo = "UPDATE announcement SET attachment = ? WHERE id= ?";
        $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $announcement_id));
    }

    
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'announcement', $announcement_id,  $date_now, $time_now, 1, $process_type = 'create');
    

    successreturn(array('id' => $announcement_id, 'successmsg' => "Announcement Added Successfully."));
} else if ($postdata['function_type'] == "alter_announcement") {

    if (!isset($postdata['announcement_id']) or !checkIfIssetAndNotEmpty($postdata['announcement_id'])) {
        errorreturn('Error in updating the announcement.');
    } else {
        $id = $postdata['announcement_id'];
    }
    $remove_bool = (isset($postdata['remove_bool']) and !empty($postdata['remove_bool'])) ? trim($postdata['remove_bool']) : 0;
    $res = $conn_rjllearning_specific->prepare("SELECT attachment FROM announcement WHERE id = ? and institution_id=? ");
    $res->execute(array($id, $institution_id));
    $result1 = $res->fetchAll();
    if (count($result1) != 1) {
        errorreturn("Announcement not exists. ");
    }

    if (count($result1) == 1) {
        $existing_attachment = $result1[0]['attachment'];
        if ($existing_attachment !=  null) {
            $data_attachment = json_decode($existing_attachment, true);
            $filePath = $data_attachment['filepath'];
        }
    }

    $res = $conn_rjllearning_specific->prepare("SELECT attachment FROM announcement WHERE id != ? and institution_id = ? and class_id = ? and section_id = ? and   date_created = ? and (title = ? or message = ?) ");
    $res->execute(array($id, $institution_id, $class_id, $section_id, $date_now, $title, $message));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("This announcement already exits. Kindly check title or message");
    }

    if ($remove_bool == 1 and $attachment !=  null) {
        if ($existing_attachment === null) {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');
            $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/announcement/" . $currentYear . "/" . $currentMonth . "/";
        } else {
            $directoryPathMain = substr($filePath, 0, strrpos($filePath, '/') + 1);
        }
        $file_name = $_FILES['attachment']['name'];
        $fileTmpName = $_FILES['attachment']["tmp_name"];
        $fileSize = $_FILES['attachment']["size"];
        $fileType = $_FILES['attachment']["type"];
        $fileError = $_FILES['attachment']["error"];
        $file_extension = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ]; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    $sql_users = "UPDATE announcement SET class_id =?,section_id = ?,title= ?,message=? WHERE id=? and institution_id=?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($class_id, $section_id, $title, $message, $id, $institution_id));

    if ($remove_bool == 1 and $existing_attachment != null) {
        $sql_image = $conn_rjllearning_specific->prepare("SELECT attachment FROM  announcement  where id = ? and institution_id = ?");
        $sql_image->execute(array($id, $institution_id));
        $result_image = $sql_image->fetchAll();
        if (count($result_image) == 1) {
            $existing_attachment = $result_image[0]['attachment'];
            $data_attachment = json_decode($existing_attachment, true);
            $filePath = $data_attachment['filepath'];
            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
            $sql = "UPDATE announcement SET attachment = ? WHERE id = ? and institution_id= ?";
            $conn_rjllearning_specific->prepare($sql)->execute(array(null, $id, $institution_id));
        }
    }

    if ($attachment !=  null) {
        $image_name = "announcement_" . $id . "." . $file_extension; // Define the image name dynamically
        $announcement_path = $directoryPathMain . $image_name; // Create the full path for the logo
        awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $announcement_path, $multiple_files_bool = false, $multiple_file_index = 0);
        $attachment_image = json_encode(array("filepath" => $announcement_path, "original_name" => $file_name));
        $sql_logo = "UPDATE announcement SET attachment = ? WHERE id= ?";
        $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $id));
    }


    
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'announcement', $id,  $date_now, $time_now, 1, $process_type = 'alter');
    

    successreturn("Announcement Updated Successfully");
}
