<?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 . 'functions/common_functions.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_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/payroll/functions.php';

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

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

function get_specific_student_planner($conn_rjllearning_specific, $institution_id, $planner_id)
{
    $sql = "SELECT * FROM student_planner WHERE institution_id = ? AND id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $planner_id]);
    $row = $stmt->fetch();
    
    if (!$row) {
        errorreturn("No data available");
    }
    
    if ($row['branch_id'] == 'all' ) {
            $branch_info = array('branch_id' => 'all', 'branch_name' => 'All branches');
        } else {
            $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
        }
        
        
        if ($row['student_id'] == 'all') {
            $student_info = array('student_id' => 'all', 'student_name' => 'All students');
        } else {
            $student_id = $row['student_id'];
            $institution_id = $row['institution_id'];
        
            // Prepare SQL
            $query = "SELECT id AS student_id, name AS student_name 
                      FROM students 
                      WHERE id = :student_id 
                      AND institution_id = :institution_id 
                      LIMIT 1";
        
            $stmt = $conn_rjllearning_specific->prepare($query); // assuming $pdo_rjllearning_specific is your PDO connection
            $stmt->execute([
                ':student_id' => $student_id,
                ':institution_id' => $institution_id
            ]);
        
            $student = $stmt->fetch(PDO::FETCH_ASSOC);
        
            if ($student) {
                $student_info = array(
                    'student_id' => $student['student_id'],
                    'student_name' => $student['student_name']
                );
            } else {
                $student_info = array(
                    'student_id' => $student_id,
                    'student_name' => 'Unknown Student'
                );
            }
        }

        
        
        // Class Info
        if ($row['class_id'] == 'all' ) {
            $class_info = array('class_id' => 'all', 'class_name' => 'All Classes');
        } else {
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $row['class_id']); 
        }
        
        // Section Info
        if ($row['section_id'] == 'all') {
            $section_info = array('section_id' => 'all', 'section_name' => 'All Sections');
        } else {
            $section_info = getSection($conn_rjllearning_specific, $institution_id, $row['section_id']);
        }
        
        if ($row['faculty_id'] == 'all' ) {
            $faculty_info = array('faculty_id' => 'all', 'name' => 'All Faculty');
        } else {
            $faculty_info = getFacultyInfo($conn_rjllearning_specific, $institution_id, $row['faculty_id']);
        }
        
        $subject_info = $row['subject_id'] == 'all' ? array('subject_id' => 'all', 'name' => ucwords('all')) : 
        getSubject($conn_rjllearning_specific, $institution_id, $row['subject_id']);

    
    return array(
        'student_planner_id' => $row['id'],
        'institution_id' => $row['institution_id'],
        'academic_session' => $row['academic_session'],
        'branch' => $branch_info,
        'faculty' => $faculty_info,
        'subject_info' => $subject_info,
        'class_info' => $class_info, 
        'section_info' => $section_info,
        "student_info" =>$student_info,
        'from_date' => $row['from_date'],
        'to_date' => $row['to_date'],
        'schedule_details' => json_decode($row['schedule_details'], true),
        'remarks' => $row['remarks'],
        'date_created' => $row['date_created'],
        'created_by' => $row['created_by'],
        'last_modified_by' => $row['last_modified_by'],
        'last_modified_at' => $row['last_modified_at'],
        'status' => $row['status']
    );
}

if ($postdata['function_type'] == "fetch_specific_student_planner") {
    $institution_id = $postdata['institution_id'];
    $planner_id = $postdata['student_planner_id'];
    
    $success['data'] = get_specific_student_planner($conn_rjllearning_specific, $institution_id, $planner_id);
    successreturn($success);
}
