<?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 . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["teacher"], 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';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning,$conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

// $institution_id = trim($postdata['institution_id']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_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');

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


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

$sql_section = $conn_rjllearning->prepare("SELECT * FROM  users WHERE username= ? ");
$sql_section->execute(array($username));
$result_section = $sql_section->fetchAll();
if (count($result_section) < 1) {
    errorreturn("Teacher not exists.");
}
$function_type = trim($postdata['function_type']);

$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));
// Fetch a single row instead of all
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);
// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}


if ($postdata['function_type'] == "create_announcement") {
    
    $faculty_id = $result_faculty['id'];
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, null, $conn_rjllearning);
    if($check_faculty_status == false){
        errorreturn("Access denied: You do not have the required permissions.");
    }
    $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 = ? ");
    $res->execute(array($institution_id, $academic_id, $branch_id, $class_id, $section_id, $title));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("This announcement already exists. ");
    }

    if ($attachment != null) {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay =  date('d');

        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id.  "/" . $branch_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(), $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(), 1, $process_type = 'create');
    
    successreturn(array('id' => $announcement_id, 'successmsg' => "Successfully announcement  added."));
} 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=? AND branch_id = ?");
    $res->execute(array($id, $institution_id,$branch_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 branch_id = ? AND class_id = ? AND  (title= ? OR message = ?) ");
    // $res->execute(array($id, $institution_id,$branch_id, $class_id, $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.  "/" . $branch_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=? AND branch_id = ?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($class_id, $section_id, $title, $message, $id, $institution_id,$branch_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(), 1, $process_type = 'alter');
    successreturn("Updated announcement Successfully");
}
