<?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';

//aws image store
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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/payroll/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";
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

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);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_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);
}
$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.");
}

// // Retrieve the faculty_id from the result
$faculty_id = $result_faculty['id'];

function get_faculty_planner($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $from_date, $to_date, $limit, $offset)
{
    global $function_type ;
    global $conn_rjllearning;
    global $userid;
        $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, $subject_id, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }

    $sql_count = "SELECT  count(*) as total_rows FROM faculty_planner where institution_id =? ";
    $array_params = [$institution_id];

    if ($branch_id == 'all') {
        $sql_count .= "";
    } else if ($branch_id !=  null  && $branch_id != 'all') {
        $sql_count .= " AND branch_id = ? ";
        $array_params[] = $branch_id;
    }

        $sql_append_data = facultyFilterQueryAppend($sql_count, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning, 1, 1, 1, 1, true);
    $sql_count = $sql_append_data['sql']; // Get the modified SQL
    $array_params = $sql_append_data['array_params'];


    if ($search_string != null) {
        $sql_count .= " AND remarks LIKE ? ";
        $array_params[] = '%' . $search_string . '%'; // Append to $array_params
    }

    if ($from_date != null && $to_date != null) {
        $sql_count .= " AND date_created BETWEEN ? AND ?";
        $array_params[] = $from_date;
        $array_params[] = $to_date;
    }
    
    // print_r($array_params);

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

    if ($limit == 'all') {

        $sql_session = "SELECT * FROM faculty_planner where institution_id = ? and branch_id =?";
        $array_params = [$institution_id,$branch_id];

      

    $sql_append_data = facultyFilterQueryAppend($sql_session, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning, 1, 1, 1, 1, true);
    $sql_session = $sql_append_data['sql']; // Get the modified SQL
    $array_params = $sql_append_data['array_params'];


        if ($search_string != null) {
            $sql_session .= " AND remarks LIKE ? ";
            $array_params[] = '%' . $search_string . '%'; // Append to $array_params
        }

        // Add date range condition
        if ($from_date != null && $to_date != null) {
            $sql_session .= " AND date_created BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }

        $sql_session .=  " order by date_created desc ";
        // print_r($sql_session);
    } else {
         $sql_session = "SELECT * FROM faculty_planner where institution_id = ? and branch_id =?";
        $array_params = [$institution_id,$branch_id];

    $sql_append_data = facultyFilterQueryAppend($sql_session, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning, 1, 1, 1, 1, true);
    $sql_session = $sql_append_data['sql']; // Get the modified SQL
    $array_params = $sql_append_data['array_params'];


        if ($search_string != null) {
            $sql_session .= " AND remarks LIKE ? ";
            $array_params[] = '%' . $search_string . '%'; // Append to $array_params
        }

        // Add date range condition
        if ($from_date != null && $to_date != null) {
            $sql_session .= " AND date_created BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }
        $sql_session .= " order by date_created desc ";
        $sql_session .= " LIMIT " . $offset . " , " . $limit . "";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();


    $array_return = [];

    foreach ($session_rows as $rows) {

        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

        // =========================
        // Handle section_id (JSON)
        // =========================
             $section = [];
        $section_id = $rows['section_id'];
        $section_ids_array = json_decode($section_id, true);

        if ($section_id == 'all' || (is_array($section_ids_array) && in_array('all', $section_ids_array))) {
            $section[] = ['section_id' => 'all', 'section_name' => 'All Sections'];
        } elseif (!empty($section_ids_array) && is_array($section_ids_array)) {
            $imploded_section_ids = implode(',', array_map('intval', $section_ids_array));
            $sql_section = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($imploded_section_ids)";
            $stmt_section = $conn_rjllearning_specific->prepare($sql_section);
            $stmt_section->execute([$institution_id]);
            $section_rows = $stmt_section->fetchAll();

            foreach ($section_rows as $section_data) {
                $section[] = ['section_id' => $section_data['id'], 'section_name' => $section_data['section_name']];
            }
        }

        // --------------------
        // Resolve Class IDs
        // --------------------
          if ($rows['class_id'] == 'all' ) {
            $class_info = array('class_id' => 'all', 'class_name' => 'All Classes');
        } else {
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']); 
        }

        $faculty_info = getFacultyInfo($conn_rjllearning_specific, $institution_id, $rows['faculty_id']);
        $subject_info = $rows['subject_id'] == 'all'
            ? ['subject_id' => 'all', 'subject_name' => 'All']
            : getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);


        $array_return[] = [
            'planner_id' => $rows['id'],
            'institution_id' => $rows['institution_id'],
            'branch' => $branch_info,
            'faculty' => $faculty_info,
            'academic_session' => $rows['academic_session'],
            'faculty_title' => $rows['faculty_title'],
            'faculty_description' => $rows['faculty_description'],
            'student_title' => $rows['student_title'],
            'student_description' => $rows['student_description'],
            'from_date' => $rows['from_date'],
            'to_date' => $rows['to_date'],
            'class_info' => $class_info,
            'section_info' => $section,
            'subject_info' => $subject_info,
            
            'remarks' => $rows['remarks'],
            'date_created' => $rows['date_created'],
            'created_by' => $rows['created_by'],
            'last_modified_by' => $rows['last_modified_by'],
            'last_modified_at' => $rows['last_modified_at'],
            'status' => $rows['status']
        ];
    }


    if (count($session_rows) < 50) {

        return array('total_rows' => $totalrows, 'faculty_planner_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'faculty_planner_info' => $array_return, 'maxreach' => 0);
    }
}

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

    $class_id = isset($postdata['class_id']) && checkIfIssetAndNotEmpty($postdata['class_id']) ? ($postdata['class_id']) : 'all';
    $section_id = isset($postdata['section_id']) && checkIfIssetAndNotEmpty($postdata['section_id']) ? ($postdata['section_id']) : 'all';
    $subject_id = isset($postdata['subject_id']) && checkIfIssetAndNotEmpty($postdata['subject_id']) ? ($postdata['subject_id']) : 'all';
    
    $from_date = isset($postdata['from_date']) && !empty($postdata['from_date']) ? trim($postdata['from_date']) : date('Y-m-d');
    $to_date = isset($postdata['to_date']) && !empty($postdata['to_date']) ? trim($postdata['to_date']) : $from_date;
    
    if ($from_date > $to_date) {
        errorreturn('Invalid Date format');
    }

    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = get_faculty_planner($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, 
        $section_id, $from_date, $to_date, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = get_faculty_planner($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, 
        $section_id, $from_date, $to_date, $limit, null);
        successreturn($success);
    }
}
