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



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

$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)) {
    erroreturn("Missing required parameters: " . implode(", ", $missing_fields));
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$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;
$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';
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);

// Prepare data for insertion

$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;
$schedule_details = is_array($postdata['schedule_details']) ? json_encode($postdata['schedule_details']) : null;
$student_id = trim($postdata['student_id']);

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

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

if ($postdata['function_type'] === 'create_student_planner') {

    $class_ids   = isset($postdata['class_id']) && is_array($postdata['class_id']) ? $postdata['class_id'] : [];
    $section_ids = isset($postdata['section_id']) && is_array($postdata['section_id']) ? $postdata['section_id'] : [];

    if (empty($class_ids) || empty($section_ids)) {
        errorreturn("Class ID and Section ID must be arrays and cannot be empty.");
    }

    // Validate class/section IDs
    validateBranchClassSection(
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $class_ids,
        $section_ids,
        0, 0, 0, 1, 0
    );

    $sql = "INSERT INTO student_planner (
                institution_id, branch_id, academic_session, student_id, faculty_id,
                class_id, section_id, subject_id, schedule_details, remarks,
                from_date, to_date, date_created, created_by, last_modified_by,
                last_modified_at, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn_rjllearning_specific->prepare($sql);

    foreach ($class_ids as $class_id) {
        foreach ($section_ids as $section_id) {
            $stmt->execute([
                $institution_id,
                $branch_id,
                $academic_id,
                $student_id,
                $faculty_id,
                $class_id,
                $section_id,
                $subject_id,
                $schedule_details,
                $remarks,
                $from_date,
                $to_date,
                date("Y-m-d H:i:s"),
                $username,
                $username,
                date("Y-m-d H:i:s"),
                1
            ]);
        }
    }

    successreturn(["successmsg" => "Successfully added student planner."]);

} elseif ($postdata['function_type'] === 'update_student_planner') {

    $planner_id = isset($postdata['student_planner_id']) ? trim($postdata['student_planner_id']) : null;
    if (!$planner_id) {
        errorreturn("Missing planner_id for update.");
    }

    $class_id = trim($postdata['class_id']);
    $section_id = trim($postdata['section_id']);

    $sql = "UPDATE student_planner 
            SET institution_id = ?, 
                branch_id = ?, 
                faculty_id = ?, 
                class_id = ?, 
                section_id = ?, 
                subject_id = ?, 
                schedule_details = ?, 
                remarks = ?, 
                from_date = ?, 
                to_date = ?, 
                last_modified_at = NOW(), 
                last_modified_by = ? 
            WHERE id = ?";

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([
        $institution_id,
        $branch_id,
        $faculty_id,
        $class_id,
        $section_id,
        $subject_id,
        $schedule_details,
        $remarks,
        $from_date,
        $to_date,
        $username,
        $planner_id
    ]);

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

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