<?php

// Display errors for debugging
ini_set('display_errors', 1);

// Include necessary files
require_once '../../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php"; // Database connection
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';


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

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All fields are required.");
}

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

// Decode and validate 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;
$name = $jwt_validate->data->name;
// echo $userid;
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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

// Validate institution_id and branch_id
$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

$response = [];



// here we will check that function type should be visitor_stats else error

function myAttendance($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $from_date, $to_date,$userid) 
{
    // Initialize variables
    $possible_values = ['H', 'P', 'A', 'L'];
    $attendance_summary = array_fill_keys($possible_values, 0);
    $attendance_counts_separate = [];

    try {
        // Get total staff
        $sql_total_staff = "SELECT COUNT(*) AS total_staff FROM faculty_info WHERE institution_id = ? and branch_id = ?";
        $array_params = [$institution_id,$branch_id];
        $stmt = $conn_rjllearning_specific->prepare($sql_total_staff);
        $stmt->execute($array_params);
        $total_students_result = $stmt->fetch();
        $total_staff = $total_students_result['total_staff'];

        // Get attendance summary
        $sql_attendance_summary = "SELECT date, value, COUNT(*) AS attendance_summary 
                                   FROM staff_attendance_daywise 
                                   WHERE institution_id = ?  AND branch_id = ? AND user_id = ?";
        $array_params = [$institution_id,$branch_id,$userid];

        // if ($branch_id != 'all') {
        //     $sql_attendance_summary .= " AND branch_id = ?";
        //     $array_params[] = $branch_id;
        // }

        if ($from_date && $to_date) {
            $sql_attendance_summary .= " AND date BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }

        $sql_attendance_summary .= " GROUP BY date, value";
        $stmt = $conn_rjllearning_specific->prepare($sql_attendance_summary);
        $stmt->execute($array_params);
        $attendance_summary_results = $stmt->fetchAll();

        // Populate attendance_summary and attendance_counts_separate
        foreach ($attendance_summary_results as $row) {
            $date = $row['date'];
            $value = $row['value'];
            $count = $row['attendance_summary'];

            if (isset($attendance_summary[$value])) {
                $attendance_summary[$value] += $count;
            }

            if (!isset($attendance_counts_separate[$date])) {
                $attendance_counts_separate[$date] = array_fill_keys($possible_values, 0);
            }
            $attendance_counts_separate[$date][$value] = $count;
        }

        // Ensure all dates within the range are represented
        if ($from_date) {
            $current_date = strtotime($from_date);
        } else {
            $current_date = strtotime('today');
        }

        if ($to_date) {
            $end_date = strtotime($to_date);
        } else {
            $end_date = strtotime('today');
        }

        while ($current_date <= $end_date) {
            $date = date('Y-m-d', $current_date);
            if (!isset($attendance_counts_separate[$date])) {
                $attendance_counts_separate[$date] = array_fill_keys($possible_values, 0);
            }
            $current_date = strtotime('+1 day', $current_date);
        }

        // Remove dates with no attendance
        $attendance_counts_separate = array_filter($attendance_counts_separate, function($counts) {
            return array_sum($counts) > 0;
        });

        // Calculate total marked days
        $sql_total_marked_days = "SELECT COUNT(DISTINCT date) AS total_marked_days 
                                  FROM staff_attendance_daywise 
                                  WHERE institution_id = ? AND branch_id = ? AND user_id = ?";
        $array_params = [$institution_id,$branch_id,$userid];

        // if ($branch_id != 'all') {
        //     $sql_total_marked_days .= " AND branch_id = ?";
        //     $array_params[] = $branch_id;
        // }

        $sql_total_marked_days .= " AND date BETWEEN ? AND ?";
        $array_params[] = $from_date;
        $array_params[] = $to_date;

        $stmt = $conn_rjllearning_specific->prepare($sql_total_marked_days);
        $stmt->execute($array_params);
        $total_marked_days_result = $stmt->fetch();
        $total_marked_days = $total_marked_days_result['total_marked_days'];

        // Get total marked attendance
        $sql_total_marked_attendance = "SELECT COUNT(*) AS total_marked_attendance 
                                        FROM staff_attendance_daywise 
                                        WHERE institution_id = ? AND branch_id = ? AND user_id = ?";
        $array_params = [$institution_id,$branch_id,$userid];

        // if ($branch_id != 'all') {
        //     $sql_total_marked_attendance .= " AND branch_id = ?";
        //     $array_params[] = $branch_id;
        // }

        // Add date range condition
        if ($from_date != null && $to_date != null) {
            $sql_total_marked_attendance .= " AND date BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }

        $stmt = $conn_rjllearning_specific->prepare($sql_total_marked_attendance);
        $stmt->execute($array_params);
        $total_marked_attendance_result = $stmt->fetch();
        $total_marked_attendance = $total_marked_attendance_result['total_marked_attendance'];

        // Initialize attendance summary
        $total_present = $attendance_summary['P'] ?? 0;
        $total_late = $attendance_summary['L'] ?? 0;
        $total_half_day = $attendance_summary['H'] ?? 0;
        $total_absent = $attendance_summary['A'] ?? 0;

        // Calculate attendance percentages
        $attendance_percentages = [];
        if ($total_marked_attendance > 0) {
            $attendance_percentages['P'] = round(($total_present / $total_marked_attendance) * 100);
            $attendance_percentages['L'] = round(($total_late / $total_marked_attendance) * 100);
            $attendance_percentages['H'] = round(($total_half_day / $total_marked_attendance) * 100);
            $attendance_percentages['A'] = round(($total_absent / $total_marked_attendance) * 100);
        } else {
            $attendance_percentages = array_fill_keys($possible_values, 0);
        }

        // Calculate total and unmarked students
        $total_marked_students = $total_present + $total_late + $total_half_day + $total_absent;
        $unmarked_students = max(0, $total_staff - $total_marked_students);

        // Get total attendance records
        $sql_total_attendance_record = "SELECT COUNT(*) AS total_attendance 
                                        FROM staff_attendance_daywise 
                                        WHERE institution_id = ? AND branch_id = ? AND user_id = ?";
        $array_params = [$institution_id,$branch_id,$userid];

        // if ($branch_id != 'all') {
        //     $sql_total_attendance_record .= " AND branch_id = ?";
        //     $array_params[] = $branch_id;
        // }

        $sql_total_attendance_record .= " AND date BETWEEN ? AND ?";
        $array_params[] = $from_date;
        $array_params[] = $to_date;

        $stmt = $conn_rjllearning_specific->prepare($sql_total_attendance_record);
        $stmt->execute($array_params);
        $total_attendance_record_result = $stmt->fetch();
        $total_attendance_record = $total_attendance_record_result['total_attendance'];

        // Construct response data
        $response_data = [
            'min_date' => $from_date,
            'max_date' => $to_date,
            'marked_dates' => intval($total_marked_students),
            // 'unmarked_dates' => intval($unmarked_students),
            'total_attendance_records' => intval($total_attendance_record),
            'attendance_counts' => $attendance_summary,
            'attendance_counts_separate' => $attendance_counts_separate,
            'attendance_percentages' => $attendance_percentages,
        ];

        // Prepare success response with the response data
        $success['data'] = $response_data;
        successreturn($success);
    } catch (Exception $e) {
        // Handle exception
        errorreturn($e->getMessage());
    }
}

if ($postdata['function_type'] == "my_datewise_attendance_stats") {  
    $institution_id = trim($postdata['institution_id']);
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if (!$check_academic_confirmation) {
        errorreturn("Access denied. Academic session not active.");
    } 

    $branch_id = isset($postdata['branch_id']) ? trim($postdata['branch_id']) : 'all';
    $search_string = isset($postdata['search_string']) ? trim($postdata['search_string']) : null;
    $from_date = isset($postdata['from_date']) ? trim($postdata['from_date']) : null;
    $to_date = isset($postdata['to_date']) ? trim($postdata['to_date']) : null;

    if ($from_date && $to_date && $from_date > $to_date) {
        errorreturn('Invalid Date format');
    }
    
    $success['data'] = myAttendance($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $from_date, $to_date,$userid);
    successreturn($success);
}
?>
