<?php
ini_set('display_errors', 1);

// Include required files
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_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

// DB access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';


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

// Check if required fields are present
$required_fields = ['institution_id', 'class_id', 'section_id', 'branch_id', 'api_signature', 'function_type', 'jwt_token', 'date'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

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

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract data from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

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

// Extract and validate input data
$institution_id = trim($postdata['institution_id']);
$class_id = trim($postdata['class_id']);
$branch_id = trim($postdata['branch_id']);
$section_id = trim($postdata['section_id']);


$date = trim($postdata['date']);
if (!$date || !strtotime($date)) {
    errorreturn("Invalid or missing date.");
}
$date = date('Y-m-d', strtotime($date));

if (!isset($postdata['attendance_info']) or empty($postdata['attendance_info']) or !is_array($postdata['attendance_info'])) {
    errorreturn("Please fill the attendance data.");
} else {
    $attendance_info = $postdata['attendance_info'];
}

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

// Validate class
$sql_class = $conn_rjllearning_specific->prepare("SELECT * FROM class_info WHERE id = ? AND institution_id = ?");
$sql_class->execute([$class_id, $institution_id]);
if ($sql_class->rowCount() < 1) {
    errorreturn("Class info does not exist.");
}

// Validate section
$sql_section = $conn_rjllearning_specific->prepare("SELECT * FROM section_info WHERE id = ? AND institution_id = ?");
$sql_section->execute([$section_id, $institution_id]);
if ($sql_section->rowCount() < 1) {
    errorreturn("Section info does not exist.");
}

// Check branch class subject
$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, null, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied.");
}

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

    // the date we are trying to add / update should be of active academic session
    compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $date, null, true);

    $student_ids = array_column($attendance_info, 'student_id');
    // Check if no student IDs are provided
    if (empty($student_ids)) {
        errorreturn("No student IDs provided.");
    }

    $values_attendance = array_column($attendance_info, 'value');
    if (empty($values_attendance)) {
        // error
        errorreturn("Invalid values found for attendance.");
    } else {
        if (count(array_diff($values_attendance, ['P', 'L', 'H', 'A'])) > 0) {
            errorreturn("Invalid values found for attendance.");
        }
    }


    $imploded_array = implode("', '", $student_ids);

    // checking the existence of student ids without class and section as it might be changed
    $sql_check_students = $conn_rjllearning_specific->prepare("SELECT COUNT(*) as total_students FROM students WHERE institution_id = ? and branch_id = ? and date_admission <= ? and (date_left IS NULL or date_left >= ?) AND id IN ('$imploded_array')");
    $sql_check_students->execute([$institution_id, $branch_id, $date, $date]);
    $result_student_count = $sql_check_students->fetchAll();
    // print_r($student_ids);die();

    if (count($result_student_count) != 1 or $result_student_count[0]['total_students'] != count($student_ids)) {
        errorreturn("Some student IDs not found in students info.");
    }


    // Check if attendance data for today already exists
    // data needs to be deleted for each student id received
    $sql_delete_existing_attendance = $conn_rjllearning_specific->prepare("DELETE FROM student_attendance_daywise WHERE institution_id = ? AND branch_id = ? AND student_id IN ('" . $imploded_array . "')  and date = ?");
    $sql_delete_existing_attendance->execute([$institution_id, $branch_id, $date]);



    $stmt = $conn_rjllearning_specific->prepare("INSERT INTO student_attendance_daywise (institution_id, branch_id, class_id, section_id, student_id, academic_id, value, date, added_by, time_created, last_updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    foreach ($attendance_info as $attendance) {
        $student_id = $attendance['student_id'];
        $value = $attendance['value'];

        $stmt->execute([$institution_id, $branch_id, $class_id, $section_id, $student_id, $academic_id, $value, $date, $username, time(), $username]);
    }

    successreturn("Successfully added attendance.");
} else {
    errorreturn('Access deniied.');
}
