<?php

// Set up error reporting
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';
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_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/modules/library_management/library_function.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";


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


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

$postdata = $_POST;

// print_r($postdata);die();
$required_fields = ['book_name', 'api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}

validateApiSignature($postdata['api_signature']);

// Authenticate user and get user details
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$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;

// Validate user access to specific database
$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);
}
// Include necessary function files
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);

$class_id = isset($postdata['class_id']) ? trim($postdata['class_id']) : null;
$subject_id = isset($postdata['subject_id']) ? trim($postdata['subject_id']) : null;
$book_name = ucwords(trim($postdata['book_name']));
$author = ucwords(trim($postdata['author']));
$genre = ucfirst(trim($postdata['genre']));
$date_of_purchase = trim($postdata['date_of_purchase']);
$bill = (isset($_FILES['bill']) and !empty($_FILES['bill'])) ? $_FILES['bill'] : null;
$bill_reference = trim($postdata['bill_reference']);
$book_reference = trim($postdata['book_reference']);
$opening_quantity = intval(trim($postdata['opening_quantity']));
$year_of_publication = trim($postdata['year_of_publication']);
$price = floatval(trim($postdata['price']));
$language = ucfirst(trim($postdata['language']));
$publisher = ucwords(trim($postdata['publisher']));

$barcode=trim($postdata['barcode']);

$date_added = date('Y-m-d');
$status = 1;
$date_created = date('Y-m-d');
$time_created = time();

// Define valid genres
$genres = [
    'Literature & Fiction',
    'Biography & Memoir',
    'Science & Technology',
    'History',
    'Non-Fiction',
    'Study Material'  // Ensure the case matches exactly
];

// Normalize the genre input
$genre = ucwords(trim($postdata['genre']));

// Validate genre
if (!in_array($genre, $genres)) {
    errorreturn("Invalid genre specified.");
}

// Validate class_id and subject_id if genre is 'Study Material'
if ($genre == 'Study Material') {
    if (!$class_id || !$subject_id) {
        errorreturn("Both class_id and subject_id are required for 'Study Material' genre.");
    }

    // Validate subject_id for the given class_id
    $subjectValidForClass = validateSubjectForClass($conn_rjllearning_specific, $class_id, $subject_id);
    if (!$subjectValidForClass) {
        errorreturn("Invalid class_id and subject_id combination.");
    }
} else {
    // If genre is not 'Study Material', set class_id and subject_id to null
    $class_id = null;
    $subject_id = null;
}


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

$function_type = trim($postdata['function_type']);

// Check if the faculty exists
$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));
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

$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, null, null, null, $conn_rjllearning);
if($check_faculty_status == false){
        errorreturn("Access denied: You do not have the required permissions.");
}
if ($postdata['function_type'] == 'create_library') {

   $libraryId = addLibraryRecord(
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $class_id,
        $subject_id,
        $barcode,
        $book_name,
        $author,
        $genre,
        $date_of_purchase,
        $bill,
        $bill_reference,
        $book_reference,
        $opening_quantity,
        $year_of_publication,
        $price,
        $language,
        $publisher,
        $username,
        $date_added,
        $time_created,
        $status,
        $workspace_id
    );
    
    // if ($bill !=  null) {
    //     $image_name = "library_" . $libraryId . "." . $GLOBALS['file_extension']; // Define the image name dynamically
    //     $bill_path = $GLOBALS['directoryPathMain'] . $image_name; // Create the full path for the logo
    //     awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $bill, $bill_path, $multiple_files_bool = false, $multiple_file_index = 0);
    //     $attachment_image = json_encode(array("filepath" => $bill_path, "original_name" => $_FILES['bill']['name']));
    //     $sql_logo = "UPDATE library_management SET bill = ? WHERE id= ?";
    //     $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $libraryId));
    // }
    
    if ($bill != null) {
        $file_extension = strtolower(pathinfo($bill['name'], PATHINFO_EXTENSION));

        // Define $directoryPathMain
        $currentYear = date('Y');
        $currentMonth = date('n');
        $currentDay = date('d');
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/" . $branch_id . "/library_management/" . $currentYear . "/" . $currentMonth . "/";

        // Create the directory if it doesn't exist
        if (!file_exists($GLOBALS['base_path_to_learning'] . $directoryPathMain)) {
            mkdir($GLOBALS['base_path_to_learning'] . $directoryPathMain, 0777, true);
        }

        $image_name = "library_" . $libraryId . "." . $file_extension; // Define the image name dynamically
        $bill_path = $directoryPathMain . $image_name; // Create the full path for the bill
        awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $bill, $bill_path, $multiple_files_bool = false, $multiple_file_index = 0);
        $attachment_image = json_encode(array("filepath" => $bill_path, "original_name" => $_FILES['bill']['name']));
        $sql_logo = "UPDATE library_management SET bill = ? WHERE id= ?";
        $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $libraryId));
    }

    successreturn(['id' => $libraryId, 'successmsg' => "Successfully added books."]);
} else if ($postdata['function_type'] == 'alter_library') {

    updateLibraryRecord($conn_rjllearning_specific, $institution_id, $postdata, $branch_id, $class_id, $subject_id, $book_name, $author, $genre, $date_of_purchase, $bill, $bill_reference, $book_reference, $opening_quantity, $year_of_publication, $price, $language, $publisher, $username, $date_added, $time_created, $status, $workspace_id);
    
    successreturn("Library record updated successfully.");
} else if ($postdata['function_type'] == 'delete_library') {
    if (isset($postdata['library_management_id'])) {
        $library_management_id = trim($postdata['library_management_id']);
        $success['data'] = deletelibraryDetails($conn_rjllearning_specific, $institution_id, $library_management_id);
        successreturn($success);
    } else {
        errorreturn("Library management ID not provided.");
    }
}
