<?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 = ['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;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], 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';
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);

// $branch_id = trim($postdata['branch_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'];
}


$function_type = $postdata['function_type'];

if ($function_type == "staff_datewise_attendance") {

    //this will staff_details
    $user_ids = array_column($attendance_info, 'user_id');
    // Check if no student IDs are provided
    if (empty($user_ids)) {
        errorreturn("No staff 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("', '", $user_ids);
    $last_updated_time =  null;
    
    $sql_check_students = $conn_rjllearning_specific->prepare("SELECT COUNT(*) as total_staff FROM faculty_info WHERE institution_id = ? and branch_id = ? AND id IN ('$imploded_array')");
    $sql_check_students->execute([$institution_id, $branch_id]);
    $result_staff_count = $sql_check_students->fetchAll();
    // print_r($result_staff_count);die();
    if (count($result_staff_count) != 1 or $result_staff_count[0]['total_staff'] != count($user_ids)) {
        errorreturn("Some staff IDs not found in staff detail.");
    }
    
    // Check if attendance data for today already exists
    $sql_check_attendance = $conn_rjllearning_specific->prepare("SELECT * FROM  staff_attendance_daywise WHERE institution_id = ? AND branch_id = ?  AND date = ?");
    $sql_check_attendance->execute([$institution_id, $branch_id,$date]);
    if ($sql_check_attendance->rowCount() >= 1) {
        // delete here
        $sql_delete_existing_attendance = $conn_rjllearning_specific->prepare("DELETE FROM  staff_attendance_daywise WHERE institution_id = ? AND branch_id = ? and date = ?");
        $sql_delete_existing_attendance->execute([$institution_id, $branch_id, $date]);
    }

    $stmt = $conn_rjllearning_specific->prepare("INSERT INTO staff_attendance_daywise(institution_id, branch_id,user_id,value,date,added_by,time_created,last_updated_time)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    foreach ($attendance_info as $attendance) {
        $user_id = $attendance['user_id'];
        $value = $attendance['value'];
        $stmt->execute([$institution_id, $branch_id, $user_id, $value, $date, $username, time(), $last_updated_time]);
    }
    successreturn("Successfully added attendance.");
} else {
    errorreturn('Access deniied.');
}
