<?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';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
$postdata = json_decode(file_get_contents("php://input"), true);
// $postdata = $_POST;
checkIfNoPhpContentsReceive();
// print_r($postdata);die();
if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or
    !isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id']) or
    !isset($postdata['subject_id']) or !checkIfIssetAndNotEmpty($postdata['subject_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);
//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,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
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);

$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$subject_id = trim($postdata['subject_id']);
$date = trim(date('Y-m-d', strtotime($postdata['date'])));
$last_updated_by =  null;
$last_updated_time =  null;

//value (P/A/H/L)

$module_code = 'subjectwise_attendance';
// $user_privilege = usersCheckPrivilege($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $incharge_id, $role, $module_code, $subject_id = null);
// if ($user_privilege == false) {

//     errorreturn("Access Denied.");
// }

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



$sql_class = $conn_rjllearning_specific->prepare("SELECT * FROM  class_info WHERE id = ? AND institution_id = ? AND branch_id LIKE  ?");
$sql_class->execute(array($class_id, $institution_id, '%' . $branch_id . '%'));
$result_class = $sql_class->fetchAll();
if (count($result_class) < 1) {
    errorreturn("Class info not exists.");
}
$sql_section = $conn_rjllearning_specific->prepare("SELECT * FROM  section_info WHERE id = ? AND institution_id = ? AND branch_id LIKE  ?");
$sql_section->execute(array($section_id, $institution_id, '%' . $branch_id . '%'));
$result_section = $sql_section->fetchAll();
if (count($result_section) < 1) {
    errorreturn("Section info not exists.");
}

$check_branch_class_subject = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, $subject_id, $institution_id);
if(!$check_branch_class_subject){
    errorreturn("Access denied");
}

$sql_section = $conn_rjllearning->prepare("SELECT * FROM  users WHERE username= ? ");
$sql_section->execute(array($username));
$result_section = $sql_section->fetchAll();
if (count($result_section) < 1) {
    errorreturn("Teacher not exists.");
}

if ($postdata['function_type'] == "subjectwise_attendance") {
    $attendance_info = $postdata['attendance_info'];
    if(!is_array($attendance_info)){
    errorreturn("required attendance info.");
    }

    // Check if $attendance_info is not an array
    // if (!is_array($attendance_info)) {
    //     errorreturn("Attendance info is not in array format.");
    // }

    // Check if attendance data for today already exists
    $sql_check_attendance = $conn_rjllearning_specific->prepare("SELECT * FROM student_attendance_subjectwise WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ? AND added_by = ? AND date = ?");
    $sql_check_attendance->execute(array($institution_id, $branch_id, $class_id, $section_id, $username, $date));
    $result_check_attendance = $sql_check_attendance->fetchAll();

    if (count($result_check_attendance) >= 1) {
        errorreturn("Attendance data for today already exists.");
    }
    // print_r($attendance_info);
    foreach ($attendance_info as $temp) {

        $student_id = $temp['student_id'];
        $value = $temp['value'];
        if (!in_array($value, ['P', 'A', 'H', 'L'])) {
            errorreturn("Invalid attendance value. Values should be 'P', 'A', 'H', or 'L'.");
        }
        //check student id

        // Extract student_ids from attendance_info
        $student_ids = array_column($attendance_info, 'student_id');
        
        // Count the number of student_ids
        $count_student_rec = count($student_ids);
        
        // Prepare IN clause for SQL query
        $implode_student_rec = "('" . implode("','", $student_ids) . "')";
        
        // Execute SQL query to count the number of matching student_ids in companies_info
        $res = $conn_rjllearning_specific->prepare("SELECT count(*) as total_students FROM students WHERE institution_id = ? AND id IN $implode_student_rec AND branch_id = ?");
        $res->execute(array($institution_id,$branch_id));
        $student_count = $res->fetchAll()[0]['total_students'];
        
        // Check if all student_ids are found
        if ($student_count != $count_student_rec) {
            errorreturn("Some student IDs not found in students info.");
        }

        $sql = "INSERT INTO  student_attendance_subjectwise(institution_id,branch_id,class_id,section_id,student_id,subject_id,academic_id,value,date,added_by,last_updated_by,time_created,last_updated_time)
          VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array($institution_id, $branch_id, $class_id, $section_id, $student_id,$subject_id, $academic_id, $value, $date, $username, $username, time(), $last_updated_time));
    }
    $id = $conn_rjllearning_specific->lastInsertId();
    successreturn(array('id' => $id, 'successmsg' => "Successfully timetable added."));
} else if ($postdata['function_type'] == "alter_subjectwise_attendance") {

    if (!isset($postdata['attendance']) or !checkIfIssetAndNotEmpty($postdata['attendance']) or
        !isset($postdata['student_id']) or !checkIfIssetAndNotEmpty($postdata['student_id']) or !isset($postdata['value']) or !checkIfIssetAndNotEmpty($postdata['value'])
    ) {
        errorreturn('Error in updating the daywise attendance.');
    } else {
        $id = $postdata['attendance'];
        $value = $postdata['value'];
        $student_id = $postdata['student_id'];
    }

    if (!in_array($value, ['P', 'A', 'H', 'L'])) {
        errorreturn("Invalid attendance value. Values should be 'P', 'A', 'H', or 'L'.");
    }

    $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id FROM student_attendance_subjectwise WHERE id != ? AND institution_id=? AND branch_id =?  AND class_id=? AND section_id= ? AND added_by=? and student_id = ?");
    $res->execute(array($id, $institution_id, $branch_id, $class_id, $section_id, $username, $student_id));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Daywise attendance already exists in this student.");
    }

    $sql_users = "UPDATE student_attendance_subjectwise SET value =?,last_updated_by= ?,last_updated_time= ? WHERE id = ? AND institution_id=? AND branch_id =?  AND  class_id=? AND section_id= ? AND student_id = ?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($value, $username, time(), $id, $institution_id, $branch_id, $class_id, $section_id, $student_id));
    successreturn("Updated timetable Successfully");
}
