<?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";
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_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "user_management/functions/functions.php";
require_once $base_path_to_learning . "faculty_api/modules/library_management/library_function.php";
require_once $base_path_to_learning . "functions/common_functions.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();

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) 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);

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$name = $jwt_validate->data->name;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;


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

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], $institution_id);
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);

    $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.");
    }

    // Retrieve the faculty_id from the result
    $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.");
    }

function getBook_info($conn_rjllearning_specific, $book_id)
{
    $sql = "SELECT * FROM library_management WHERE id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$book_id]);
    $result = $stmt->fetchAll();

    // Check if the result is empty
    if (empty($result)) {
        return [];
    }

    return $result;
}

function getbooks_details($conn_rjllearning_specific, $institution_id, $student_id, $branch_id, $book_id, $limit, $offset, $sort, $type_of_request, $check_academic_confirmation, $search_string)
{
    // Initial count query to get the total rows
    $sql = "SELECT COUNT(*) as total_rows 
            FROM book_issues 
            LEFT JOIN library_management ON book_issues.book_id = library_management.id
            WHERE book_issues.institution_id = ? AND book_issues.branch_id = ? AND book_issues.academic_id=?";
    $array_params = [$institution_id,$branch_id, $check_academic_confirmation];

    // if ($branch_id != 'all') {
    //     $sql .= " AND book_issues.branch_id = ?";
    //     $array_params[] = $branch_id;
    // }

    if ($student_id != null) {
        $sql .= " AND book_issues.student_id = ?";
        $array_params[] = $student_id;
    }

    if ($book_id != null) {
        $sql .= " AND book_issues.book_id = ?";
        $array_params[] = $book_id;
    }

    if ($type_of_request == 'only_issued') {
        $sql .= " AND book_issues.date_of_return IS NULL";
    } elseif ($type_of_request == 'only_returned') {
        $sql .= " AND book_issues.date_of_return IS NOT NULL";
    }

    if ($search_string != null) {
        $sql .= " AND (library_management.book_name LIKE ? OR library_management.author LIKE ?)";
        $search_term = '%' . $search_string . '%';
        $array_params[] = $search_term;
        $array_params[] = $search_term;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    // Sort order setup
    $sort_order = '';
    if ($sort == 'issuedesc') {
        $sort_order = 'book_issues.date_of_issue DESC';
    } elseif ($sort == 'issueasc') {
        $sort_order = 'book_issues.date_of_issue ASC';
    } elseif ($sort == 'returndesc') {
        $sort_order = 'book_issues.date_of_return DESC';
    } elseif ($sort == 'returnasc') {
        $sort_order = 'book_issues.date_of_return ASC';
    } else {
        $sort_order = 'book_issues.date_of_issue DESC';
    }

    // Query to fetch book details
    $sql = "SELECT book_issues.*, library_management.book_name, library_management.author 
            FROM book_issues 
            LEFT JOIN library_management ON book_issues.book_id = library_management.id
            WHERE book_issues.institution_id = ? AND book_issues.branch_id = ? AND book_issues.academic_id=?";
    $array_params = [$institution_id, $branch_id, $check_academic_confirmation];

    // if ($branch_id != 'all') {
    //     $sql .= " AND book_issues.branch_id = ?";
    //     $array_params[] = $branch_id;
    // }

    if ($student_id != null) {
        $sql .= " AND book_issues.student_id = ?";
        $array_params[] = $student_id;
    }

    if ($book_id != null) {
        $sql .= " AND book_issues.book_id = ?";
        $array_params[] = $book_id;
    }

    if ($type_of_request == 'only_issued') {
        $sql .= " AND book_issues.date_of_return IS NULL";
    } elseif ($type_of_request == 'only_returned') {
        $sql .= " AND book_issues.date_of_return IS NOT NULL";
    }

    if ($search_string != null) {
        $sql .= " AND (library_management.book_name LIKE ? OR library_management.author LIKE ?)";
        $search_term = '%' . $search_string . '%';
        $array_params[] = $search_term;
        $array_params[] = $search_term;
    }

    // Add sorting and pagination
    $sql .= " ORDER BY " . $sort_order;
    if ($limit != 'all') {
        $sql .= " LIMIT " . $offset . ", " . $limit;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();
   
    $array_return = [];

    foreach ($result as $rows) {
        $student_info = getStudentInfo($conn_rjllearning_specific, $institution_id, $rows['student_id']);
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $student_info['class_id']);

        $array_return[] = array(
            "issue_id" => $rows['id'],
            "student_id" => $student_info['student_id'],
            "student_name" => $student_info['name'],
            "admission_number" => $student_info['admission_number'],
            "branch_id" => $student_info['branch_id'],
            "class_name" => $class_info['class_name'],
            "book_name" => $rows['book_name'],
            'author' => $rows['author'],
            "date_of_issue" => $rows['date_of_issue'],
            "time_of_issue" => $rows['issue_time'],
            "issued_by" => $rows['issued_by'],
            "due_date" => $rows['due_date'],
            "date_of_return" => $rows['date_of_return'],
            "time_of_return" => $rows['return_time'],
            "return_to" => $rows['return_to'],
            "remarks" => $rows['remarks']
        );
    }

    if (count($result) < 50) {
        return array('total_rows' => $totalrows, 'books_detail' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'books_detail' => $array_return, 'maxreach' => 0);
    }
}

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

    if (isset($postdata['sort']) && !empty($postdata['sort']) && trim($postdata['sort'])) {
        $sort = trim($postdata['sort']);
    } else {
        $sort = 'issuedesc';
    }

    $student_id = isset($postdata['student_id']) ? trim($postdata['student_id']) : null;
    $book_id = isset($postdata['book_id']) ? trim($postdata['book_id']) : null;
    $type_of_request = isset($postdata['type_of_request']) ? trim($postdata['type_of_request']) : 'all';
    $search_string = isset($postdata['search_string']) ? trim($postdata['search_string']) : null;
    

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


    $limit = isset($postdata['limit']) ? $postdata['limit'] : '10';
    $page = (isset($postdata['page']) && is_numeric($postdata['page'])) ? (int) $postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
    } else {
        $offset = null;
    }

    $fetch_book_details = getbooks_details($conn_rjllearning_specific, $institution_id, $student_id, $branch_id, $book_id, $limit, $offset, $sort, $type_of_request, $check_academic_confirmation, $search_string);

    if ($fetch_book_details && !empty($fetch_book_details['books_detail'])) {
        successreturn($fetch_book_details);
    } else {
        errorreturn("No book details available.");
    }
} else {
    errorreturn("Invalid Function_type");
}
