<?php
ini_set('display_errors', 1);

require_once '../../../resources/base_path_include.php';


require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
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 . 'admin_api/modules/dashboard/dashboard_functions.php';

require_once $base_path_to_learning_resources . 'lib/student_birthdays/function.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/item/functions.php';

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

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

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

$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;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

// $institution_id = isset($postdata['institution_id']) && checkIfIssetAndNotEmpty($postdata['institution_id']) ? trim($postdata['institution_id']) : 'all';
// $branch_id = isset($postdata['branch_id']) && checkIfIssetAndNotEmpty($postdata['branch_id']) ? trim($postdata['branch_id']) : 'all';

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['principal'],null);

if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

function fetchUnmarkedAttendanceClasses($conn_rjllearning_specific, $institution_id, $branch_id, $date = null) {
    try {
        $date = $date ?: date('Y-m-d');
        $unmarkedClasses = [];

        //get all active class-section combinations with student counts
        $activeClassesQuery = "SELECT s.class_id, s.section_id, COUNT(s.id) as student_count
                              FROM students s
                              WHERE s.can_activate = 1 
                              AND s.date_admission <= ? 
                              AND (s.date_left IS NULL OR s.date_left >= ?) AND s.institution_id = ? AND s.branch_id = ?";

        $params = [$date, $date, $institution_id, $branch_id];

        $activeClassesQuery .= " GROUP BY s.class_id, s.section_id";

        $activeStmt = $conn_rjllearning_specific->prepare($activeClassesQuery);
        $activeStmt->execute($params);
        $activeClasses = $activeStmt->fetchAll(PDO::FETCH_ASSOC);

        //get class-sections with attendance marked (any value)
        $markedQuery = "SELECT DISTINCT class_id, section_id 
                        FROM student_attendance_daywise 
                        WHERE date = ? AND institution_id = ? AND branch_id = ?";
        $markedParams = [$date, $institution_id, $branch_id];

        $markedStmt = $conn_rjllearning_specific->prepare($markedQuery);
        $markedStmt->execute($markedParams);
        $markedClasses = $markedStmt->fetchAll(PDO::FETCH_ASSOC);

        //find unmarked classes
        foreach ($activeClasses as $class) {
            $isMarked = false;
            
            //check if this class-section exists in marked_classes
            foreach ($markedClasses as $marked) {
                if ($marked['class_id'] == $class['class_id'] && 
                    $marked['section_id'] == $class['section_id']) {
                    $isMarked = true;
                    break;
                }
            }

            //only include if has students AND not marked
            if ($class['student_count'] > 0 && !$isMarked) {
                $classInfo = getClass($conn_rjllearning_specific, $institution_id, $class['class_id'], true);
                $sectionInfo = getSection($conn_rjllearning_specific, $institution_id, $class['section_id'], true);

                if ($classInfo && $sectionInfo && !isset($classInfo['error'])) {
                    $unmarkedClasses[] = [
                        'class' => $classInfo,
                        'section' => $sectionInfo,
                        'active_students' => $class['student_count']
                    ];
                }
            }
        }

        return [
            'data' => $unmarkedClasses,
            'count' => count($unmarkedClasses)
        ];

    } catch (PDOException $e) {
        error_log("Attendance check failed: " . $e->getMessage());
        return [
            'success' => false,
            'message' => "Database error",
            'error' => $e->getMessage()
        ];
    }
}


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

    if (isset($postdata['from_date']) and !empty($postdata['from_date'])) {
        $from_date = trim($postdata['from_date']);
    } else {
        // $from_date = null;
        $from_date = date('Y-m-d');
    }
    
    if (isset($postdata['to_date']) and !empty($postdata['to_date'])) {
        $to_date = trim($postdata['to_date']);
    } else {
        $to_date = date('Y-m-d');
    }

    if ($from_date > $to_date) {
        errorreturn('Invalid Date format');
    }
    
    $Attendance_stats = fetchUnmarkedAttendanceClasses($conn_rjllearning_specific, $institution_id, $branch_id, $to_date);

    $result = [
        'Attendance_stats' => $Attendance_stats
    ];

    successreturn($result);
}
