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

//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.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);

// Required fields check
$required_fields = [ 'faculty_id', 'class_id', 'section_id', 'function_type', 'jwt_token'];
$missing_fields = [];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field])) {
        $missing_fields[] = $field;
    }
}
if (!empty($missing_fields)) {
    errorreturn("Missing required parameters: " . implode(", ", $missing_fields));
}

// API Signature
validateApiSignature($postdata['api_signature']);

// JWT validation
$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;
// Dynamic DB access check
$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);
}

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';


$faculty_id     = trim($postdata['faculty_id']);
$subject_id     = isset($postdata['subject_id']) ? trim($postdata['subject_id']) : null;
$from_date      = trim($postdata['from_date']);
$to_date        = trim($postdata['to_date']);
$remarks        = isset($postdata['remarks']) ? trim($postdata['remarks']) : null;

// New fields
$faculty_title       = isset($postdata['faculty_title']) ? trim($postdata['faculty_title']) : null;
$faculty_description = isset($postdata['faculty_description']) ? trim($postdata['faculty_description']) : null;
$student_title       = isset($postdata['student_title']) ? trim($postdata['student_title']) : null;
$student_description = isset($postdata['student_description']) ? trim($postdata['student_description']) : null;

// Convert arrays to JSON safely
$class_ids       = isset($postdata['class_id']) ? trim($postdata['class_id']) : 'all';
// Academic session check
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}
$section_ids = json_encode(array_map('strval', $postdata['section_id']));

// Holiday check
$sql_holiday = "SELECT holiday_date FROM holiday_calendar 
                WHERE institution_id = ? AND (branch_id = ? OR branch_id = 'all') 
                AND holiday_date BETWEEN ? AND ?";
$stmt_holiday = $conn_rjllearning_specific->prepare($sql_holiday);
$stmt_holiday->execute([$institution_id, $branch_id, $from_date, $to_date]);
$holidays = $stmt_holiday->fetchAll(PDO::FETCH_COLUMN);

foreach ($holidays as $holiday) {
    if ($holiday >= $from_date && $holiday <= $to_date) {
        errorreturn("The selected dates fall on a holiday: $holiday.");
    }
}
$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'];
$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.");
}
// CREATE FACULTY PLANNER
if ($postdata['function_type'] === 'create_faculty_planner') {

    // Validate required inputs
    if (empty($branch_id) || empty($faculty_id) || empty($from_date) || empty($to_date) || empty($postdata['class_id']) || empty($postdata['section_id'])) {
        errorreturn("Branch, Faculty, Date Range, Class and Section are mandatory.");
    }

    // Validate branch-class-section relation
    validateBranchClassSection(
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $postdata['class_id'],
        $postdata['section_id'],
        0,0,0,1,0
    );

    // Insert query
    $sql = "INSERT INTO faculty_planner (
                institution_id, branch_id, academic_session, faculty_id,
                faculty_title, faculty_description, student_title, student_description,
                class_id, section_id, subject_id, remarks,
                from_date, to_date, date_created, created_by, last_modified_by, last_modified_at, status
            ) VALUES (
                ?,?,?,?,?, ?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?
            )";

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([
        $institution_id,
        $branch_id,
        $academic_id,
        $faculty_id,
        $faculty_title,
        $faculty_description,
        $student_title,
        $student_description,
        $class_ids,
        $section_ids,
        $subject_id,
       
        $remarks,
        $from_date,
        $to_date,
        date("Y-m-d"),
        $username,
        $username,
        date("Y-m-d"),
        1
    ]);

    successreturn(["successmsg" => "Successfully added faculty planner."]);
}
if ($postdata['function_type'] === 'update_faculty_planner') {

    // Validate required inputs
    if (empty($postdata['planner_id']) ) {
        errorreturn("Planner ID, Branch, Faculty, Date Range, Class and Section are mandatory.");
    }



    // Update query
    $sql = "UPDATE faculty_planner SET
                faculty_title = ?,
                faculty_description = ?,
                student_title = ?,
                student_description = ?,
                class_id = ?,
                section_id = ?,
                subject_id = ?,
                remarks = ?,
                from_date = ?,
                to_date = ?,
                last_modified_by = ?,
                last_modified_at = ?,
                status = ?
            WHERE institution_id = ? 
              AND branch_id = ? 
              AND academic_session = ?
              AND faculty_id = ?
              AND id = ?";   // id = planner_id

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([
        $faculty_title,
        $faculty_description,
        $student_title,
        $student_description,
        $class_ids,
        $section_ids,
        $subject_id,
        $remarks,
        $from_date,
        $to_date,
        $username,
        date("Y-m-d"),
        1,   // active status (can change if needed)
        $institution_id,
        $branch_id,
        $academic_id,
        $faculty_id,
        $postdata['planner_id']
    ]);

    successreturn(["successmsg" => "Successfully updated faculty planner."]);
}

else {
    errorreturn("Invalid function type");
}
?>
