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

//validation 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';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

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

// checkIfNoPhpContentsReceive();

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    // !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !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 !isset($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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

// $branch_id = $postdata['branch_id'];
// $institution_id = $postdata['institution_id'];


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

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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 institution_id and branch_id
$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
} 

$function_type = trim($postdata['function_type']);

function get_vendor_details($conn_rjllearning_specific, $institution_id, $branch_id, $limit, $offset)
{
   $params = [$institution_id];
    $branch_condition = "";
    
    if ($branch_id != 'all' && $branch_id != null) {
        $branch_condition = " AND ut.branch_id = ?";
        $params[] = $branch_id;
    }
    
    // Count vendors (non-students)
    $sql_vendor_count = "SELECT COUNT(DISTINCT ut.vendor_name) as vendor_count FROM unmarked_transaction ut
                         LEFT JOIN students s ON ut.vendor_name = s.name WHERE ut.institution_id = ? AND s.id IS NULL AND 
                         ut.vendor_name NOT REGEXP '^[0-9]+$'" . $branch_condition;
    $stmt = $conn_rjllearning_specific->prepare($sql_vendor_count);
    $stmt->execute($params);
    $vendor_count = $stmt->fetch()['vendor_count'];
    
    // Count students (reusing same params)
    $sql_student_count = "SELECT COUNT(DISTINCT ut.vendor_name) as student_count FROM unmarked_transaction ut
    JOIN students s ON ut.vendor_name = s.name WHERE ut.institution_id = ? AND ut.vendor_name NOT REGEXP '^[0-9]+$'" . $branch_condition;
    $stmt = $conn_rjllearning_specific->prepare($sql_student_count);
    $stmt->execute($params);
    $student_count = $stmt->fetch()['student_count'];
    
    $total_rows = $vendor_count + $student_count;


    // ===== 2. Fetch Data with Pagination =====
    $query_params = [$institution_id];
    if ($branch_id != 'all' && $branch_id != null) {
        $query_params[] = $branch_id;
        // Need to add them again for the second part of UNION
        $query_params[] = $institution_id;
        $query_params[] = $branch_id;
    } else {
        $query_params[] = $institution_id;
    }

    $sql = "(SELECT DISTINCT ut.vendor_name, 'vendor' as type 
            FROM unmarked_transaction ut
            LEFT JOIN students s ON ut.vendor_name = s.name
            WHERE ut.institution_id = ? 
            AND s.id IS NULL AND ut.vendor_name NOT REGEXP '^[0-9]+$'" . $branch_condition . ")
            
            UNION ALL
            
            (SELECT DISTINCT ut.vendor_name, 'student' as type 
            FROM unmarked_transaction ut
            JOIN students s ON ut.vendor_name = s.name
            WHERE ut.institution_id = ? AND ut.vendor_name NOT REGEXP '^[0-9]+$'" . $branch_condition . ")";

    // Add pagination if not 'all'
    if ($limit != 'all') {
        $sql .= " LIMIT ?, ?";
        $query_params[] = (int)$offset;
        $query_params[] = (int)$limit;
    }
    
    // print_r($sql);

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($query_params);
    $combined_results = $stmt->fetchAll();

    // ===== 3. Format Results =====
    $formatted_results = array_map(function ($row) {
        return [
            'name' => $row['vendor_name'],
            'type' => $row['type']
        ];
    }, $combined_results);

    return [
        'total_rows' => $total_rows,
        'vendor_info' => $formatted_results,
        'vendor_count' => $vendor_count,
        'student_count' => $student_count,
        'maxreach' => ($limit != 'all' && count($combined_results) < $limit) ? 1 : 0
    ];
}

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

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

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = get_vendor_details($conn_rjllearning_specific, $institution_id, $branch_id, $limit, $offset);
        
    } else {
        $success['data'] = get_vendor_details($conn_rjllearning_specific, $institution_id, $branch_id, $limit, null);
    }
    
    successreturn($success);
}
