<?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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;
// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], 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);

// Extract and validate input data
// $institution_id = trim($postdata['institution_id']);
// $branch_id = trim($postdata['branch_id']);
$date = date('Y-m-d', strtotime($postdata['date']));
if (!$date || !strtotime($date)) {
    errorreturn("Invalid or missing date.");
}
$currentDate = date('Y-m-d');
if ($date != $currentDate) {
     // The date is not the current date
    errorreturn("The date is not the current date.");
}

$value = $postdata['value'];

// Check if the attendance values array is empty
if (empty($value)) {
    errorreturn("Invalid values found for attendance.");
} else {
    // Check for any values that are not in the allowed set
    $allowed_values = ['P', 'L', 'H', 'A'];
    if (!in_array($value, $allowed_values)) {
        errorreturn("Invalid values found for attendance.");
    }
}

// Fetch the faculty attendance setting
$sql_setting = "SELECT faculty_attendance_setting FROM institution_global_settings WHERE institution_id = ? AND branch_id = ?";
$stmt_setting = $conn_rjllearning_specific->prepare($sql_setting);
$stmt_setting->execute([$institution_id,$branch_id]);
$setting_result = $stmt_setting->fetch();
// print_r($setting_result);die();
if ($setting_result) {
    $faculty_attendance_setting = json_decode($setting_result['faculty_attendance_setting'], true);

    // Check if self-marking is enabled
    if ($faculty_attendance_setting['self_mark'] == 1) {
        // Self-marking is allowed, so teacher/staff can add their own attendance
        // echo "Self-marking enabled. Attendance can be marked by teacher/staff.";

        // // Further conditions can be added based on biometric or GPS settings
        // if ($faculty_attendance_setting['methods']['biometric'] == 0) {
        //     errorreturn ("Biometric method is disabled for attendance.");
        // }
        // if ($faculty_attendance_setting['methods']['gps'] == 0) {
        //     errorreturn ("GPS method is disabled for attendance.");
        // }
        
    } else {
        // Restrict attendance marking
        errorreturn ("Self-marking disabled. Attendance marking restricted.");
    }
} 
// else {
//     errorreturn("Attendance settings not found for this institution.");
// }
$last_updated_time =  null;
$coordinates = (isset($postdata['coordinates']) and !empty($postdata['coordinates'])) ? ($postdata['coordinates']) : null;
if ($coordinates) {
    $coordinates_json = json_encode($coordinates);
   
} else {
    errorreturn ("No coordinates provided.");
}

if ($postdata['function_type'] == "my_attendance") {
    // echo $userid;
    $sql_check_students = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE institution_id = ? and branch_id = ? AND userid = ? and status = ?");
    $sql_check_students->execute([$institution_id, $branch_id,$userid,1]);
    $result_staff_count = $sql_check_students->fetchAll();
    if (count($result_staff_count) != 1 ) {
        errorreturn("staff not found.");
    }
    
    $faculty_id = $result_staff_count[0]['id'];
    
    // 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 = ? and user_id = ?");
    $sql_check_attendance->execute([$institution_id, $branch_id,$date,$faculty_id]);
    if ($sql_check_attendance->rowCount() >= 1) {
        errorreturn("Staff attendance already exists for this day.");
    }
    
    $stmt = $conn_rjllearning_specific->prepare("INSERT INTO staff_attendance_daywise(institution_id, branch_id,user_id,value,date,coordinates,added_by,time_created,last_updated_time)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)");
    $stmt->execute([$institution_id, $branch_id, $faculty_id, $value, $date,$coordinates_json, $username, time(), $last_updated_time]);
    
    successreturn("Successfully added attendance.");
}

