<?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';
require_once $base_path_to_learning . 'functions/common_functions.php';

//db access function
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';

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

$postdata = $_POST;

if (
    !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);
}

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

    if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or
    !isset($postdata['subject_name']) or !checkIfIssetAndNotEmpty($postdata['subject_name']) or 
    !isset($postdata['type']) or !checkIfIssetAndNotEmpty($postdata['type'])) {
        errorreturn("All * fields are required.");
    }

    $institution_id = trim($postdata['institution_id']);
    $class_id = trim($postdata['class_id']);
    $subject_name = ucwords(strtolower(trim($postdata['subject_name'])));
    $type = trim($postdata['type']);
    // $icon = (isset($_FILES['icon']) and !empty($_FILES['icon'])) ? $_FILES['icon'] : null;

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

    //check class id exists or not
    $sql_class = "SELECT * from class_info where id = ? AND institution_id = ?";
    $stmt_class =  $conn_rjllearning_specific->prepare($sql_class);
    $stmt_class->execute(array($class_id, $institution_id));
    $result_class = $stmt_class->fetchAll();
    if (count($result_class) != 1) {
        errorreturn('Class does not exist in the specified institution.');
    }

    if (!checkOnlyCharcterNumericwithSpace($subject_name)) { // for english chars + numbers only

        errorreturn('Invalid Subject name');
    }

    $res = $conn_rjllearning_specific->prepare("SELECT *  FROM  subject_info WHERE institution_id = ? AND class_id = ? AND subject_name = ?");
    $res->execute(array($institution_id, $class_id, $subject_name));
    $result = $res->fetchAll();
    if (count($result) >= 1) {
        errorreturn("Subject Name already exist in this class");
    }

    // if ($icon == null) {
    //     $icon = null;
    // } else {
    //     $currentYear = date('Y');
    //     $currentMonth = date('n');
    //     $currentDay =  date('d');

    //     $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id . "/subject_attachments/" . $currentYear . "/" . $currentMonth . "/";

    //     if (!file_exists($GLOBALS['base_path_to_learning'] . $directoryPathMain)) {
    //         mkdir($GLOBALS['base_path_to_learning'] . $directoryPathMain, 0777, true);
    //     }
    //      $file_name = $_FILES['icon']['name'];
    //     $fileTmpName = $_FILES['icon']["tmp_name"];
    //     $fileSize = $_FILES['icon']["size"];
    //     $fileType = $_FILES['icon']["type"];
    //     $fileError = $_FILES['icon']["error"];
    //     $file_extension = strtolower(pathinfo($_FILES['icon']['name'], PATHINFO_EXTENSION));
    //     $size = filesize($fileTmpName);
    //     // Check if it's a valid image
    //     $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
    //     $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg'];
    //     $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

    //     checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    //     $image_name = $subject_name . "-" . date('d-m-Y') . "." . $file_extension;
    //     $icon = $directoryPathMain . $image_name;

    //     //move_uploaded_file($fileTmpName, $GLOBALS['base_path_to_learning'] . $icon);
    //     try {
    //         $s3_learning_bucket->putObject([
    //             'Bucket' => $learning_bucketName,
    //             'Key' => $icon,
    //             'SourceFile' => $fileTmpName,

    //         ]);
    //     } catch (Exception $e) {
    //         errorreturn($e->getMessage());
    //     }
    //     $icon = json_encode(array("filepath" => $icon, "original_name" => $file_name));
    // }

    try {

        $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id FROM class_info WHERE institution_id = ? and id= ?");
        $res->execute(array($institution_id, $class_id));
        $result1 = $res->fetchAll();

        if (count($result1) == 1) {
            $sql = "INSERT INTO subject_info(institution_id,class_id,type,subject_name,status)VALUES(?,?,?,?,?)";
            $stmt =  $conn_rjllearning_specific->prepare($sql);

            $stmt->execute(array($institution_id, $class_id, $type, $subject_name, '1'));
        } else {
            errorreturn("Class is not found.");
        }
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }

    $id = $conn_rjllearning_specific->lastInsertId();
    successreturn(array('subject_id' => $id, 'successmsg' => "Successfully subject added."));
} else if ($postdata['function_type'] == "alter_subject") {

    if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or !isset($postdata['subject_name']) or !checkIfIssetAndNotEmpty($postdata['subject_name']) or !isset($postdata['type']) or !checkIfIssetAndNotEmpty($postdata['type'])) {
        errorreturn("All * fields are required.");
    }


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

    $institution_id = trim($postdata['institution_id']);
    $class_id = trim($postdata['class_id']);
    $subject_name = ucwords(trim($postdata['subject_name']));
    $type = trim($postdata['type']);
    // $icon = (isset($_FILES['icon']) and !empty($_FILES['icon'])) ? $_FILES['icon'] : null;
    $remove_bool = (isset($postdata['remove_bool']) and !empty($postdata['remove_bool'])) ? trim($postdata['remove_bool']) : 0; //if 

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

    // $res = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM homework WHERE institution_id = ? AND subject_id = ?");
    // $res->execute(array($institution_id, $id));
    // $result1 = $res->fetchAll();

    // if (count($result1) >= 1) {
    //     errorreturn("Access denied. A homework exists for this subject, so it cannot be updated.");
    // }



    // $res = $conn_rjllearning_specific->prepare("SELECT icon FROM subject_info WHERE id = ? and institution_id=?");
    // $res->execute(array($id, $institution_id));
    // $result1 = $res->fetchAll();
    // if (count($result1) != 1) {
    //     errorreturn("Subject not found.");
    // } else {
    //     $existing_icon = $result1[0]['icon'];
    // }

    $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id FROM subject_info WHERE id != ? and institution_id=? and subject_name =? AND class_id = ?");
    $res->execute(array($id, $institution_id, $subject_name, $class_id));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("The subject already exists");
    }


    // if ($icon == null) {
    //     if ($remove_bool == 1 and $existing_icon != null) {
    //         $sql_image = $conn_rjllearning_specific->prepare("SELECT icon FROM  subject_info  where id = ? and institution_id = ?");
    //         $sql_image->execute(array($id, $institution_id));
    //         $result_image = $sql_image->fetchAll();
    //         if (count($result_image) == 1) {

    //             $existing_icon = $result_image[0]['icon'];
    //             awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $existing_icon, null, null);
    //              $sql = "UPDATE subject_info SET icon = ? WHERE id = ? and institution_id= ?";
    //              $conn_rjllearning_specific->prepare($sql)->execute(array(null, $id, $institution_id));
    //         }

    //     }
    // } 

    // if($remove_bool == 1 and $icon != null){

    //     if ($existing_icon === null) {

    //         $currentYear = date('Y');
    //         $currentMonth = date('n');
    //         $currentDay =  date('d');

    //         $directoryPathMain =  "user_uploads/" . $workspace_id .  "/" . $institution_id . "/subject_attachments/" . $currentYear . "/" . $currentMonth . "/";

    //         if (!file_exists($GLOBALS['base_path_to_learning'] . $directoryPathMain)) {
    //             mkdir($GLOBALS['base_path_to_learning'] . $directoryPathMain, 0777, true);
    //         }
    //     } else {

    //         $directoryPathMain = substr($existing_icon, 0, strrpos($existing_icon, '/') + 1);
    //     }
    //      $file_name = $_FILES['icon']['name'];
    //     $fileTmpName = $_FILES['icon']["tmp_name"];
    //     $fileSize = $_FILES['icon']["size"];
    //     $fileType = $_FILES['icon']["type"];
    //     $fileError = $_FILES['icon']["error"];
    //     $file_extension = strtolower(pathinfo($_FILES['icon']['name'], PATHINFO_EXTENSION));
    //     $size = filesize($fileTmpName);
    //     // Check if it's a valid image
    //     $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
    //     $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg'];
    //     $maxFileSize = 2; // Maximum file size (2MB)

    //     checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    //     $image_name = $subject_name . "-" . date('d-m-Y') . "." . $file_extension;
    //     $icon = $directoryPathMain . $image_name;

    //     //move_uploaded_file($fileTmpName, $GLOBALS['base_path_to_learning'] . $icon);
    //     try {
    //         $s3_learning_bucket->putObject([
    //             'Bucket' => $learning_bucketName,
    //             'Key' => $icon,
    //             'SourceFile' => $fileTmpName,

    //         ]);
    //     } catch (Exception $e) {
    //         errorreturn($e->getMessage());
    //     }
    //     $icon = json_encode(array("filepath" => $icon, "original_name" => $file_name));
    //     $sql_users = "UPDATE subject_info SET icon =? WHERE id=? and institution_id=?";
    //     $conn_rjllearning_specific->prepare($sql_users)->execute(array( $icon, $id, $institution_id));
    // }

    //apply_leaves,assignments,homework,lessons,lesson_categories,library_management,question_bank_info,test,timetable
    // Check for existing homework
    
    if($role == 'teacher' or $role ==  'principal'){
    $sql_homework = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM homework WHERE institution_id = ? AND subject_id = ?");
    $sql_homework->execute(array($institution_id, $id));
    $result_homework = $sql_homework->fetchAll();
    if (count($result_homework) >= 1) {
        errorreturn("Access denied. A homework exists for this subject, so it cannot be deleted.");
    }

    // Check for existing timetable
    $sql_timetable = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM timetable WHERE institution_id = ? AND subject_id = ?");
    $sql_timetable->execute(array($institution_id, $id));
    $result_timetable = $sql_timetable->fetchAll();
    if (count($result_timetable) >= 1) {
        errorreturn("Access denied. A timetable exists for this subject, so it cannot be deleted.");
    }

    // Check for existing assignments
    $sql_assignments = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM assignments WHERE institution_id = ? AND subject_id = ?");
    $sql_assignments->execute(array($institution_id, $id));
    $result_assignments = $sql_assignments->fetchAll();
    if (count($result_assignments) >= 1) {
        errorreturn("Access denied. An assignment exists for this subject, so it cannot be deleted.");
    }

    // Check for existing apply leaves
    $sql_apply_leaves = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM apply_leaves WHERE institution_id = ? AND subject_id = ?");
    $sql_apply_leaves->execute(array($institution_id, $id));
    $result_apply_leaves = $sql_apply_leaves->fetchAll();
    if (count($result_apply_leaves) >= 1) {
        errorreturn("Access denied. An apply leave exists for this subject, so it cannot be deleted.");
    }

    // Check for existing lessons
    $sql_lessons = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM lessons WHERE institution_id = ? AND subject_id = ?");
    $sql_lessons->execute(array($institution_id, $id));
    $result_lessons = $sql_lessons->fetchAll();
    if (count($result_lessons) >= 1) {
        errorreturn("Access denied. A lesson exists for this subject, so it cannot be deleted.");
    }

    // Check for existing lesson categories
    $sql_lesson_categories = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM lesson_categories WHERE institution_id = ? AND subject_id = ?");
    $sql_lesson_categories->execute(array($institution_id, $id));
    $result_lesson_categories = $sql_lesson_categories->fetchAll();
    if (count($result_lesson_categories) >= 1) {
        errorreturn("Access denied. A lesson category exists for this subject, so it cannot be deleted.");
    }

    // Check for existing library management
    $sql_library_management = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM library_management WHERE institution_id = ? AND subject_id = ?");
    $sql_library_management->execute(array($institution_id, $id));
    $result_library_management = $sql_library_management->fetchAll();
    if (count($result_library_management) >= 1) {
        errorreturn("Access denied. A library management entry exists for this subject, so it cannot be deleted.");
    }
    }

    $sql_users = "UPDATE subject_info SET class_id =? ,type= ?,subject_name=? WHERE id=? and institution_id=?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($class_id, $type, $subject_name, $id, $institution_id));
    successreturn("deleted class Successfully");
} else if ($postdata['function_type'] == "subject_status") {


    if (!isset($postdata['subject_id']) or !checkIfIssetAndNotEmpty($postdata['subject_id'])) {
        errorreturn('Error in updating the subject.');
    } else {
        $id = $postdata['subject_id'];
    }
    $institution_id = trim($postdata['institution_id']);
    $check_acdademic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_acdademic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    $res = $conn_rjllearning_specific->prepare("SELECT status FROM subject_info WHERE id = ? and institution_id=? and branch_id =?");
    $res->execute(array($id, $institution_id, $branch_id));
    $result1 = $res->fetchAll();
    $status = $result1[0]['status'];
    //echo $lock_status;die();

    if ($status == '1') {
        $status = '0';
        $sql = "UPDATE subject_info SET status=?  WHERE id = ? and institution_id=? and branch_id =?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($status, $id, $institution_id, $branch_id));
    } else if ($status == '0') {
        $status = '1';
        $sql = "UPDATE subject_info SET status=?  WHERE id = ? and institution_id=? and branch_id =?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($status, $id, $institution_id, $branch_id));
    }
    successreturn("Subject Status Updated Successfully");
} else if ($postdata['function_type'] == "unlock_subject") {

    if (!isset($postdata['subject_id']) or !checkIfIssetAndNotEmpty($postdata['subject_id'])) {
        errorreturn('Error in updating the subject.');
    } else {
        $id = $postdata['subject_id'];
    }
    $institution_id = trim($postdata['institution_id']);
    $check_acdademic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_acdademic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    //  $lock_status = $postdata['lock_status'];
    $res = $conn->prepare("SELECT id,lock_status FROM subject_info WHERE id = ? and institution_id =?");
    $res->execute(array($id, $institution_id));
    $result1 = $res->fetch();
    $lockstatus = $result1['lock_status'];
    //echo $lock_status;die();

    if ($lockstatus == '1') {
        $lock_status = '0';
        $sql = "UPDATE subject_info SET lock_status=?  WHERE id=?  and institution_id= ?";
        $conn->prepare($sql)->execute(array($lock_status, $id, $institution_id));
    } else if ($lockstatus == '0') {
        $lock_status = '1';
        $sql = "UPDATE subject_info SET lock_status=?  WHERE id = ?  and institution_id =?";
        $conn->prepare($sql)->execute(array($lock_status, $id, $institution_id));
    }
    successreturn("Subject status updated Successfully");
}
