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

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

// Check if required fields are present
$required_fields = ['institution_id', '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;

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

// Extract and validate input data
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$date = $postdata['date'];

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

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

// Validate branch
if ($branch_id != "all") {
    $sql_branch = $conn_rjllearning_specific->prepare("SELECT id, name FROM branch WHERE id = ? AND institution_id = ?");
    $sql_branch->execute([$branch_id, $institution_id]);
    $branch = $sql_branch->fetch(PDO::FETCH_ASSOC);
    if (!$branch) {
        errorreturn("Branch does not exist in the specified institution.");
    }
}

$function_type = $postdata['function_type'];
if ($function_type === "datewise_management_stats") {
    try {
        // Array to store results for each branch
        $branch_results = array();

        // If branch is selected
        $sql_branches_query = "SELECT id, name FROM branch WHERE  id = ? AND institution_id = ?";
        $array_params = [$branch_id,$institution_id];
       
        $sql_branches = $conn_rjllearning_specific->prepare($sql_branches_query);
        $sql_branches->execute($array_params);
        $branches = $sql_branches->fetchAll(PDO::FETCH_ASSOC);

        // Loop through each branch
        foreach ($branches as $branch) {
            $branch_id = $branch['id'];
            $branch_name = $branch['name'];

            // Query to get total active students for the current branch
            $sql_total_active_students = "SELECT COUNT(*) AS total_active_students FROM students WHERE institution_id = ? AND branch_id = ?";
            $params = [$institution_id,$branch_id];
            $stmt_active_students = $conn_rjllearning_specific->prepare($sql_total_active_students);
            $stmt_active_students->execute($params);
            $total_active_students = $stmt_active_students->fetchColumn();

            // Query to get total present students for the current branch
           $sql_total_present = "SELECT COUNT(*) AS total_present FROM student_attendance_daywise WHERE institution_id = ? AND value = 'P' AND branch_id = ?";
            $array_params = [$institution_id,$branch_id];

            $stmt_present = $conn_rjllearning_specific->prepare($sql_total_present);
            $stmt_present->execute($array_params);
            $total_present = $stmt_present->fetchColumn();

            // Query to get total marked students for the current branch
           $sql_total_marked_students = "SELECT COUNT(*) AS total_marked_students FROM student_attendance_daywise WHERE institution_id = ? AND value IN ('P', 'H', 'A') AND branch_id = ?";
           $array_params = [$institution_id,$branch_id];
            $stmt_total_marked_students = $conn_rjllearning_specific->prepare($sql_total_marked_students);
            $stmt_total_marked_students->execute($array_params);
            $total_marked_students = $stmt_total_marked_students->fetchColumn();

            // Store results for the current branch
            $branch_results[] = array(
                "branch_id" => $branch_id,
                "branch_name" => $branch_name,
                "total_active_students" => $total_active_students,
                "total_marked_students" => $total_marked_students,
                "total_present" => $total_present
            );
        }

        // Return the branch-wise results
        echo json_encode($branch_results);
    } catch (PDOException $e) {
        errorreturn("Error executing query: " . $e->getMessage());
    }
} else {
    errorreturn("Invalid function type.");
}
?>
