<?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';

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

// print_r($postdata);
// die();
// Check if required fields are present
$required_fields = ['institution_id', 'class_id', 'section_id', 'branch_id', 'api_signature', 'function_type', 'jwt_token', 'min_date', 'max_date'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
    }
}

// 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;

// Validate user access
$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);

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

// Extract and validate input data
$institution_id = trim($postdata['institution_id']);
$class_id = trim($postdata['class_id']);
$branch_id = trim($postdata['branch_id']);
$section_id = trim($postdata['section_id']);
$min_date = $postdata['min_date'];
$max_date = $postdata['max_date'];

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

$attendance_academic_session = compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $min_date, $max_date);


// Validate class
if ($class_id != "all") {
    $sql_class = $conn_rjllearning_specific->prepare("SELECT * FROM class_info WHERE id = ? AND institution_id = ?");
    $sql_class->execute([$class_id, $institution_id]);
    if ($sql_class->rowCount() < 1) {
        errorreturn("Class info does not exist.");
    }
}

// Validate section
if ($section_id != "all") {
    $sql_section = $conn_rjllearning_specific->prepare("SELECT * FROM section_info WHERE id = ? AND institution_id = ?");
    $sql_section->execute([$section_id, $institution_id]);
    if ($sql_section->rowCount() < 1) {
        errorreturn("Section info does not exist.");
    }
}

// Validate branch
if ($branch_id != "all") {
    $sql_branch = $conn_rjllearning_specific->prepare("SELECT * FROM branch WHERE id = ? AND institution_id = ?");
    $sql_branch->execute([$branch_id, $institution_id]);
    if ($sql_branch->rowCount() < 1) {
        errorreturn("branch info does not exist.");
    }
}

if ($postdata['function_type'] === "datewise_attendance_stats") {

    // active academic session
    // directly class section students from students
    // not active academic session
    // fetch student id, class, id , section id from cache

    // Get total students
    if ($min_date == date("Y-m-d")) {
        $sql_total_students = "SELECT COUNT(*) AS total_students FROM students WHERE institution_id = ?  and (date_left IS NULL or date_left > ?)  and can_activate = 1";
        $array_params = [$institution_id, $min_date];

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

        if ($class_id != 'all') {
            $sql_total_students .= " AND class_id = ?";
            $array_params[] = $class_id;
        }

        if ($section_id != 'all') {
            $sql_total_students .= " AND section_id = ?";
            $array_params[] = $section_id;
        }
      

        $stmt = $conn_rjllearning_specific->prepare($sql_total_students);
        $stmt->execute($array_params);
        $total_students_result = $stmt->fetch();
        $total_students = $total_students_result['total_students'];
    } else {
        $sql_total_students = "SELECT count(*) as total_students from cache_academic_students_data where institution_id = ?   and student_id IN (SELECT id FROM students WHERE institution_id = ? and date_admission <= ?   AND can_activate = 1 and (date_left IS NULL or date_left > ?))";
        $array_params = [$institution_id, $institution_id, $min_date, $min_date];

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

        if ($class_id != 'all') {
            $sql_total_students .= " AND class_id = ?";
            $array_params[] = $class_id;
        }

        if ($section_id != 'all') {
            $sql_total_students .= " AND section_id = ?";
            $array_params[] = $section_id;
        }


        $stmt = $conn_rjllearning_specific->prepare($sql_total_students);
        $stmt->execute($array_params);
        $total_students_result = $stmt->fetch();
        $total_students = $total_students_result['total_students'];
    }

    // Get attendance summary
    $possible_values = ['H', 'P', 'A', 'L'];

    // Query to get attendance summary
    $sql_attendance_summary = "SELECT date, value, COUNT(*) AS attendance_summary 
                               FROM student_attendance_daywise 
                               WHERE institution_id = ? and academic_id =?";
    $array_params = [$institution_id, $academic_id];

    // Append conditions for branch, class, and section if they are not 'all'
    if ($branch_id != 'all') {
        $sql_attendance_summary .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

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

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

    // Append date condition based on whether min_date and max_date are the same
    if ($min_date === $max_date) {
        $sql_attendance_summary .= " AND date = ?";
        $array_params[] = $min_date;
    } else {
        $sql_attendance_summary .= " AND date BETWEEN ? AND ?";
        $array_params[] = $min_date;
        $array_params[] = $max_date;
    }

    $sql_attendance_summary .= " GROUP BY date, value";

    // Prepare and execute the query
    $stmt = $conn_rjllearning_specific->prepare($sql_attendance_summary);
    $stmt->execute($array_params);
    $attendance_summary_results = $stmt->fetchAll();

    // Initialize arrays to store attendance summary
    $attendance_summary = [];
    $attendance_counts_separate = [];

    // Initialize attendance_summary with zero counts for all possible values
    $attendance_summary = array_fill_keys($possible_values, 0);

    // Iterate through the results to populate attendance_summary and attendance_counts_separate
    foreach ($attendance_summary_results as $row) {
        // Extract data from the row
        $date = $row['date'];
        $value = $row['value'];
        $count = $row['attendance_summary'];

        // Populate attendance_summary with counts for each value
        if (isset($attendance_summary[$value])) {
            $attendance_summary[$value] += $count;
        }

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

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

    // Ensure that all dates within the range are represented
    $current_date = strtotime($min_date);
    $end_date = strtotime($max_date);

    while ($current_date <= $end_date) {
        $date = date('Y-m-d', $current_date);
        if (!isset($attendance_counts_separate[$date])) {
            // Initialize with all possible values set to 0 for dates not present in the attendance data
            $attendance_counts_separate[$date] = array_fill_keys($possible_values, 0);
        }
        $current_date = strtotime('+1 day', $current_date);
    }

    // Remove dates where no attendance was marked
    $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 student_attendance_daywise WHERE institution_id = ? and academic_id=?";
    $array_params = [$institution_id, $academic_id];

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

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

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

    $sql_total_marked_days .= " AND date BETWEEN ? AND ?";
    $array_params[] = $min_date;
    $array_params[] = $max_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 student_attendance_daywise WHERE institution_id = ? and  academic_id=?";
    $array_params = [$institution_id, $academic_id];

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

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

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

    $sql_total_marked_attendance .= " AND date BETWEEN ? AND ?";
    $array_params[] = $min_date;
    $array_params[] = $max_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 variables for total present, late, holiday, and absent
    $total_present = isset($attendance_summary['P']) ? $attendance_summary['P'] : 0;
    $total_late = isset($attendance_summary['L']) ? $attendance_summary['L'] : 0;
    $total_half_day = isset($attendance_summary['H']) ? $attendance_summary['H'] : 0;
    $total_absent = isset($attendance_summary['A']) ? $attendance_summary['A'] : 0;

    // Calculate percentages if total marked attendance is not zero
    $attendance_percentages = [];
    if ($total_marked_attendance != 0) {
            $attendance_percentages['P'] = $total_present;
            $attendance_percentages['L'] = $total_late;
            $attendance_percentages['H'] = $total_half_day;
            $attendance_percentages['A'] = $total_absent;
    } else {
        $attendance_percentages['P'] = 0;
        $attendance_percentages['L'] = 0;
        $attendance_percentages['H'] = 0;
        $attendance_percentages['A'] = 0;
    }

    // if ($total_marked_days != 0) {
    //     $average_presents = round($total_present / $total_marked_days, 2);
    //     $average_absent = round($total_absent / $total_marked_days, 2);
    //     $average_half_day = round($total_half_day / $total_marked_days, 2);
    //     $average_leave = round($total_late / $total_marked_days, 2);
    // } else {
    //     $average_presents = 0;
    //     $average_absent = 0;
    //     $average_half_day = 0;
    //     $average_leave = 0;
    // }

    // $average_presents = number_format($average_presents, 2);
    // $average_absent = number_format($average_absent, 2);
    // $average_half_day = number_format($average_half_day, 2);
    // $average_leave = number_format($average_leave, 2);

    // Calculate marked students
    $total_marked_students = $total_present + $total_late + $total_half_day + $total_absent;
    
    // Calculate unmarked students
    $unmarked_students = ($total_students * $total_marked_days) >= ($total_marked_students) ? (($total_students * $total_marked_days) - ($total_present + $total_late + $total_half_day + $total_absent)) : 0;
    if($total_marked_days <= 0) {
        $unmarked_students_percentage = 0;
    } else {
        $unmarked_students_percentage = round(($unmarked_students / ($total_students * $total_marked_days)) * 100);
    }


    // Get total attendance record
    $sql_total_attendance_record = "SELECT COUNT(*) AS total_attendance FROM student_attendance_daywise WHERE institution_id = ? and academic_id=?";
    $array_params = [$institution_id, $academic_id];

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

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

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

    $sql_total_attendance_record .= " AND date BETWEEN ? AND ?";
    $array_params[] = $min_date;
    $array_params[] = $max_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'];

    // $branch_info = [];
    // if ($branch_id = 'all') {
    //     $sql_branch_info = "SELECT name FROM branch WHERE id = ? AND institution_id = ?";
    //     $stmt = $conn_rjllearning_specific->prepare($sql_branch_info);
    //     $stmt->execute([$branch_id, $institution_id]);
    //     $branch_info = $stmt->fetch(PDO::FETCH_ASSOC);
    // }

    // Construct response data
    $response_data = [
        'min_date' => $min_date,
        'max_date' => $max_date,
        'marked_students' => intval($total_marked_students),
        'unmarked_students' => intval($unmarked_students),
        'unmarked_students_percentage' => $unmarked_students_percentage,
        'total_marked_days' => intval($total_marked_days),
        'total_students' => intval($total_students),
        'total_attendance_records' => intval($total_attendance_record),
        'attendance_counts' => $attendance_summary,
        'attendance_counts_separate' => $attendance_counts_separate,
        'attendance_percentages' => $attendance_percentages,
        // 'branch_info' => $branch_info,
        // 'average_attendance' => [
        //     'P' => $average_presents,
        //     'A' => $average_absent,
        //     'H' => $average_half_day,
        //     'L' => $average_leave,
        // ],
    ];

    // // Convert any nested arrays to objects
    // foreach ($response_data as &$value) {
    //     if (is_array($value)) {
    //         // Wrap the associative array inside an array
    //         $value = [$value];
    //     }
    // }
    // Wrap attendance counts arrays inside another array
    $response_data['attendance_counts'] = [$response_data['attendance_counts']];
    $response_data['attendance_counts_separate'] = [$response_data['attendance_counts_separate']];

    // Prepare success response with the response data
    $success['data'] = $response_data;
    successreturn($success);
}
