<?php

ini_set('display_errors', 1);

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 . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "user_management/functions/functions.php";
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . "admin_api/modules/library_management/library_function.php";
require_once $base_path_to_learning . "admin_api/modules/transportation/routes/routes_functions.php";
require_once $base_path_to_learning . "admin_api/modules/staff/staff_attendance/staff_function.php";


use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

$required_fields = ['institution_id', 'branch_id', 'api_signature', 'user_id', 'function_type', 'jwt_token', 'start_date', 'end_date'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

validateApiSignature($postdata['api_signature']);

// Authenticate and validate the JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$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 to a specific database
$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);

// Retrieve and sanitize POST data
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$user_id = trim($postdata['user_id']);
$start_date = trim($postdata['start_date']);
$end_date = trim($postdata['end_date']);
$function_type = trim($postdata['function_type']);

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

$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
}

// Validate date range
if (!$start_date || !strtotime($start_date) || !$end_date || !strtotime($end_date)) {
    errorreturn("Invalid or missing start/end date.");
}

$start_date = date('Y-m-d', strtotime($start_date));
$end_date = date('Y-m-d', strtotime($end_date));

if (!isUserValid($conn_rjllearning_specific, $user_id)) {
    errorreturn("Invalid user_id.");
}

$start_date_dt = new DateTime($start_date);
$end_date_dt = new DateTime($end_date);
$interval = $start_date_dt->diff($end_date_dt);

if ($interval->days >= 31) {
    $attendance_data = fetchMonthly_Attendance($institution_id, $branch_id, $user_id, $conn_rjllearning_specific, $start_date, $end_date);

    if (empty($attendance_data['date_wise_info'])) {
        errorreturn("No records found for the given user and date range.");
    } else {
        $response = [
                'staff_id' => $user_id,
                'detail' => $attendance_data['date_wise_info'],
                'attendance_summary' => $attendance_data['stats_info']
        ];
        successreturn($response);
    }
} else {
    if ($function_type == "Fetch_staff_attendance") {
        if (!$start_date || !strtotime($start_date) || !$end_date || !strtotime($end_date) || strtotime($end_date) < strtotime($start_date)) {
            errorreturn("Invalid date range. Ensure end date is not earlier than start date.");
        }

        $attendance_data = specificStaffAttendance($institution_id, $branch_id, $user_id, $conn_rjllearning_specific, $start_date, $end_date);

        if (empty($attendance_data['date_wise_info'])) {
            errorreturn("No records found for the given user and date range.");
        } else {
            $response = [
                    'staff_id' => $user_id,
                    'detail' => $attendance_data['date_wise_info'],
                    'attendance_summary' => $attendance_data['attendance_summary']
            ];
            successreturn($response);
        }
    } else {
        errorreturn('Invalid function type.');
    }
}
