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

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

/*
 * Required Checks
 */
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']);

/*
 * JWT Validation
 */
$jwttoken   = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid       = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$role         = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id      = $jwt_validate->data->branch_id;
$class_id       = $jwt_validate->data->class;
$section_id     = $jwt_validate->data->section;

/*
 * DB Access Validation
 */
$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);

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

/*
 * Pagination + Filters
 */
$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');
}

$limit  = isset($postdata['limit']) ? $postdata['limit'] : 50;
$page   = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
$offset = ($limit != 'all') ? ($page - 1) * $limit : null;

/*
 * Function Handling
 */
if ($postdata['function_type'] == "fetch_speech_submissions") {

    // ---- Count Total Rows ----
    $sql_count = "SELECT COUNT(*) 
              FROM speech_tasks_submission 
              WHERE student_id = ? AND institution_id = ? AND academic_id = ? AND workspace_id = ? AND branch_id = ?";
    $params = [$userid, $institution_id, $academic_id, $workspace_id, $branch_id];
    
    if ($from_date && $to_date) {
        $sql_count .= " AND DATE(submitted_at) BETWEEN ? AND ?";
        $params[] = $from_date;
        $params[] = $to_date;
    }
    
    $stmt = $conn_rjllearning->prepare($sql_count);
    $stmt->execute($params);
    $totalrows = (int)$stmt->fetchColumn();

    // ---- Fetch Submissions ----
    $sql_data = "SELECT * 
                 FROM speech_tasks_submission 
                 WHERE student_id = ? AND institution_id = ? AND academic_id = ? AND workspace_id = ? AND branch_id = ?";
    $params_data = [$userid, $institution_id, $academic_id,$workspace_id,$branch_id];

    if ($from_date && $to_date) {
        $sql_data .= " AND DATE(submitted_at) BETWEEN ? AND ?";
        $params_data[] = $from_date;
        $params_data[] = $to_date;
    }

    $sql_data .= " ORDER BY submitted_at DESC";

    if ($limit != 'all') {
        $sql_data .= " LIMIT " . $offset . ", " . $limit;
    }

    $stmt = $conn_rjllearning->prepare($sql_data);
    $stmt->execute($params_data);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ---- Return Data ----
    $success['data'] = [
        'total_rows' => $totalrows,
        'submissions' => $rows,
        'maxreach' => ($limit != 'all' && count($rows) < $limit) ? 1 : 0
    ];

    successreturn($success);
} else {
    errorreturn("Invalid function type.");
}
