<?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/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/registration_functions.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 . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

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

$postdata = json_decode(file_get_contents("php://input"), true);
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;

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["superadmin","admin","principal","teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

if($role == 'principal' or $role == 'teacher'){
    $institution_id = $jwt_validate->data->institution_id;
    $branch_id = $jwt_validate->data->branch_id;
    

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

if($role == 'admin' or $role == 'superadmin'){
      if(!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']))
      {
          errorreturn("institution field is required.");
      }else{
            $institution_id = $postdata['institution_id'];
            if (isset($postdata['branch_id']) && !empty($postdata['branch_id'])) {
                if (is_array($postdata['branch_id'])) {
                    // Multiple branches selected
                    $branch_id = $postdata['branch_id']; // keep as array
                } else {
                    // Single branch
                    $branch_id = trim($postdata['branch_id']);
                }
            } else {
                $branch_id = "all";
            }

      }
}

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

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

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

    // Validate faculty_id array
    if (!isset($postdata['faculty_id']) || !is_array($postdata['faculty_id']) || empty($postdata['faculty_id'])) {
        errorreturn("faculty_id array is required.");
    }

    // Optional branch filter
    $branch_filter = "";
    $params = [$institution_id];
    if (isset($postdata['branch_id']) && is_array($postdata['branch_id']) && !empty($postdata['branch_id'])) {
        $branch_placeholders = implode(',', array_fill(0, count($postdata['branch_id']), '?'));
        $branch_filter = " AND branch_id IN ($branch_placeholders)";
        $params = array_merge($params, $postdata['branch_id']);
    }

    $results = [];

    foreach ($postdata['faculty_id'] as $faculty_id) {

        // Fetch salary records for this faculty (latest first)
        $query = "SELECT id, faculty_id, branch_id, basic_salary ,date_created
                  FROM other_staff_details 
                  WHERE institution_id = ? AND faculty_id = ? $branch_filter
                  ORDER BY date_created DESC";
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute(array_merge([$institution_id, $faculty_id], isset($postdata['branch_id']) ? $postdata['branch_id'] : []));
        $salary_records = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!$salary_records) {
            // Skip if no salary data
            continue;
        }

        // Fetch faculty name
        $faculty_query = "SELECT name FROM faculty_info WHERE id = ?";
        $faculty_stmt = $conn_rjllearning_specific->prepare($faculty_query);
        $faculty_stmt->execute([$faculty_id]);
        $faculty_data = $faculty_stmt->fetch(PDO::FETCH_ASSOC);
        $faculty_name = $faculty_data ? $faculty_data['name'] : null;

        // Prepare current & history
        $current_salary_data = $salary_records[0];
        $current_salary_data['name'] = $faculty_name;
        $current_salary_data['branch_info'] = getBranchInfo($conn_rjllearning_specific, $institution_id, $current_salary_data['branch_id']);

        $old_salary_data = [];
        if (count($salary_records) > 1) {
            foreach (array_slice($salary_records, 1) as $old) {
                $old['name'] = $faculty_name;
                $old['branch_info'] = getBranchInfo($conn_rjllearning_specific, $institution_id, $old['branch_id']);
                $old_salary_data[] = $old;
            }
        }

        // Add to results
        $results[] = [
            "faculty_id" => $faculty_id,
            "current"    => $current_salary_data,
            "history"    => $old_salary_data
        ];
    }

    if (empty($results)) {
        errorreturn("No salary data found for the given faculty IDs.");
    }

    successreturn($results);
}
