<?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 . 'functions/get_branch_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
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 . "user_management/functions/functions.php";

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

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

checkIfNoPhpContentsReceive();

// Validate required fields
$required_fields = [ 'api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}

// Specific DB connection
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;

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

$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

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

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

function getBusStaff($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id,$from_date,$to_date, $limit, $offset)
{
    $sql_count = "SELECT  count(*) as total_rows FROM  other_staff_groups where institution_id =?";
    $array_params = [$institution_id];
    if ($branch_id == 'all') {
            $sql_count .= "";
    } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql_count .= " AND branch_id LIKE ? ";
            $array_params[] = '%' . $branch_id . '%';
    }

    if ($search_string != null) {
            $sql_count .= " AND group_name LIKE ? ";
            $array_params[] = '%' . $search_string . '%'; // Append to $array_params
    }
    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    if ($limit == 'all') {

        $sql_session = "SELECT * FROM  other_staff_groups  where institution_id =? ";
        $array_params = [$institution_id];
        if ($branch_id == 'all') {
            $sql_session .= "";
        } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql_session .= " AND branch_id LIKE ? ";
            $array_params[] = '%' . $branch_id . '%';
        }

        if ($search_string != null) {
            $sql_session .= " AND group_name LIKE ? ";
            $array_params[] = '%' . $search_string . '%'; // Append to $array_params
        }

      $sql_session .=  "order by date_created desc, time_created desc";
        
        
    } else {
        $sql_session = "SELECT * FROM other_staff_groups WHERE institution_id = ?";
        $array_params = [$institution_id];
        
        if ($branch_id == 'all') {
            $sql_session .= "";
        } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql_session .= " AND branch_id LIKE ? ";
            $array_params[] = '%' . $branch_id . '%';
        }

        
        if ($search_string != null) {
            $sql_session .= " AND group_name LIKE ? ";
            $array_params[] = '%' . $search_string . '%'; // Append to $array_params
        }

      $sql_session .= " order by date_created desc, time_created desc ";
      $sql_session .= "LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();
 
   

$array_return = [];

// Loop through each session row to fetch data
foreach ($session_rows as $rows) {
    $group_id = $rows['id'];
    $institution_id = $rows['institution_id'];

    // Fetch all staff details for the given group_id and institution_id
    $sql_staff_details = "SELECT * FROM faculty_info WHERE other_staff_group_id = ? AND institution_id = ?";
    $stmt_staff = $conn_rjllearning_specific->prepare($sql_staff_details);
    $stmt_staff->execute([$group_id, $institution_id]);
    $staff_details_list = $stmt_staff->fetchAll(PDO::FETCH_ASSOC);

    // Reset branch information for each session row
    $branch_info = [];
    $branch_id = $rows['branch_id'];
    
    // Fetch branch information based on branch_id value
    if ($branch_id === 'all') {
        $branch_info[] = array('branch_id' => $branch_id, 'branch_name' => ucwords($branch_id));
    } else {
        // Remove single quotes and split by comma
        $branch_ids = explode(',', str_replace("'", '', $branch_id));
        $placeholders = implode(',', array_fill(0, count($branch_ids), '?'));
        $array_params = array_merge([$institution_id], $branch_ids);

        $sql_branch = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($placeholders)";
        $stmt_branch = $conn_rjllearning_specific->prepare($sql_branch);
        $stmt_branch->execute($array_params);
        $branch_rows = $stmt_branch->fetchAll();

        foreach ($branch_rows as $branch_data) {
            $branch_info[] = array('branch_id' => $branch_data['id'], 'branch_name' => $branch_data['name']);
        }
    }

    // Build $array_return based on presence of staff details
    if ($staff_details_list) {
        foreach ($staff_details_list as $staff_details) {
            $array_return[] = array(
                'staff_id' => $staff_details['id'],
                'group_name' => $rows['group_name'],
                'branch_id' => $branch_info,
                'institution_id' => $institution_id,
                'staff_name' => $staff_details['name'],
                'staff_email' => $staff_details['email'],
                'staff_phone' => $staff_details['mobile'],
            );
        }
    } else {
        // No staff details found
        $array_return[] = array(
            'staff_id' => $rows['id'],
            'group_name' => $rows['group_name'],
            'branch_id' => $branch_info,
            'institution_id' => $institution_id,
            'staff_name' => null,
            'staff_email' => null,
            'staff_phone' => null,
        );
    }
}

// Prepare the final return structure
if (count($session_rows) < 50) {
    return array('total_rows' => $totalrows, 'BusStaff_info' => $array_return, 'maxreach' => 1);
} else {
    return array('total_rows' => $totalrows, 'BusStaff_info' => $array_return, 'maxreach' => 0);
}
}

if ($postdata['function_type'] == "fetch_bus_staff") {
  
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
   
     if(isset($postdata['subject_id']) and !empty($postdata['subject_id']) and trim($postdata['subject_id'])) {
        $subject_id = trim($postdata['subject_id']);
    } else {
        $subject_id = null;
    }
  
 

   
    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }

    if (isset($postdata['section_id']) and !empty($postdata['section_id']) and trim($postdata['section_id'])) {
        $section_id = trim($postdata['section_id']);
    } else {
        $section_id = "all";
    }

    if (isset($postdata['class_id']) and !empty($postdata['class_id']) and trim($postdata['class_id'])) {
        $class_id = trim($postdata['class_id']);
    } else {
        $class_id = "all";
    }
    
     if (isset($postdata['from_date']) and !empty($postdata['from_date'])) {
        $from_date = trim($postdata['from_date']);
    } else {
        $from_date = null;
    }
    if (isset($postdata['to_date']) and !empty($postdata['to_date'])) {
        $to_date = trim($postdata['to_date']);
    } else {
        $to_date = null;
    }
    
    if ($from_date > $to_date) {
    errorreturn('Invalid Date format');
    }
    $limit = $postdata['limit'];

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

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = getBusStaff($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id,$from_date,$to_date, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = getBusStaff($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id,$from_date,$to_date, $limit, null);
        successreturn($success);
    }
}
