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

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

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

$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_faculty_planner($conn_rjllearning_specific, $institution_id, $planner_id)
{
    $sql = "SELECT * FROM faculty_planner WHERE institution_id = ? AND id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $planner_id]);
    $rows = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$rows) {
        errorreturn("Faculty Planner not found");
    }

    // ---- Branch Info ----
    $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

    // ---- Section Info ----
    $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']];
        }
    }

  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 & Subject Info ----
    $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']);

    // ---- Return formatted data ----
    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 ($postdata['function_type'] == "fetch_specific_faculty_planner") {
    if (!isset($postdata['planner_id']) || !checkIfIssetAndNotEmpty($postdata['planner_id'])) {
        errorreturn("planner_id is required");
    }

    $institution_id = $postdata['institution_id'];
    $planner_id = $postdata['planner_id'];

    $success['data'] = get_specific_faculty_planner($conn_rjllearning_specific, $institution_id, $planner_id);
    successreturn($success);
}
