<?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 . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/functions.php';
require_once $base_path_to_learning . 'functions/common_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';

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

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

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !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;

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

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

if ($postdata['function_type'] == "fetch_staff_apply_leaves") {
    $institution_id = trim($postdata['institution_id']);
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

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

      if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }
    
    // $subject_leave = isset($postdata['subject_leave']) ? trim($postdata['subject_leave']) : null;
    if (isset($postdata['leave_type']) and !empty($postdata['leave_type'])) {
        $leave_type = trim($postdata['leave_type']);
    } else {
        $leave_type = null;
    }
    // $description = isset($postdata['description']) ? trim($postdata['description']) : null;
      if (isset($postdata['leave_reason']) and !empty($postdata['leave_reason'])) {
        $leave_reason = trim($postdata['leave_reason']);
    } else {
        $leave_reason = null;
    }
    
    // $start_date = isset($postdata['start_date']) ? trim($postdata['start_date']) : null;
    $start_date = !empty($postdata['from_date']) ? trim($postdata['from_date']) : null;
$end_date = !empty($postdata['to_date']) ? trim($postdata['to_date']) : null;


    
    $status = isset($postdata['status']) ? trim($postdata['status']) : null;

    // Validate dates
    if ($start_date != null && $end_date != null && strtotime($start_date) > strtotime($end_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;

        $apply_leaves_data = getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $leave_type, $leave_reason, $start_date, $end_date,$limit, $offset);
    } else {
        $apply_leaves_data = getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id,$leave_type, $leave_reason, $start_date, $end_date, $limit, null);
    }
    successreturn($apply_leaves_data);
}

function getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $leave_type, $leave_reason, $start_date, $end_date,$limit, $offset)
{

    $sql = "SELECT  count(*) as total_rows FROM  staff_apply_leaves  where institution_id =? ";
    $array_params = [$institution_id];
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];


    $sql = "SELECT * FROM staff_apply_leaves WHERE institution_id = ?";
    $array_params = array($institution_id);

    // Append conditions based on filters
    if ($branch_id != null && $branch_id != 'all') {
        $sql .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }


    if ($start_date != null && $end_date != null) {
        $sql .= " AND date_created BETWEEN ? AND ?";
        $array_params[] = $start_date;
        $array_params[] = $end_date;
    }

    if ($search_string != null) {
        $sql .= " AND (leave_type LIKE ? OR leave_reason LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }


    $sql .= " ORDER BY date_created DESC ";

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

    $stmt = $conn_rjllearning_specific->prepare($sql);


    $stmt->execute($array_params);
    $result = $stmt->fetchAll();


    $leave_info = [];

    foreach ($result as $row) {

$student_sql = "SELECT id, name FROM faculty_info WHERE institution_id = ? AND id = ?";

$student_stmt = $conn_rjllearning_specific->prepare($student_sql);
$student_stmt->execute([$institution_id, $row['staff_id']]);

// Fetch a single result as an associative array
$student_result = $student_stmt->fetch(PDO::FETCH_ASSOC);


    if ($student_result) {
        // Access data correctly from the associative array
        $student_id = $student_result['id'];
        $student_name = $student_result['name'];
    } else {
        $student_id = null;
        $student_name = null;
    }

        // Process attachment
    if (!empty($row['attachment']) && is_string($row['attachment'])) {
    $data_attachment = json_decode($row['attachment'], true);
    if (isset($data_attachment['filepath']) && isset($data_attachment['original_name'])) {
        $filePath = $data_attachment['filepath'];
        $originalName = $data_attachment['original_name'];
        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
        $final_array_attachment = array("filepath" => $aws_attachment, "original_name" => $originalName);
    } else {
        $final_array_attachment = null;
    }
} else {
    $final_array_attachment = null;
}




 $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
        // Create the response array
        $leave_info[] = [
            'apply_leave_id' => $row['id'],
            'staff_id' => $student_id,
            'name' => $student_name,
            'branch_info' => $branch,
            'attachment' => $final_array_attachment,
            'leave_type' => $row['leave_type'],
            'leave_reason' => $row['leave_reason'],
            'start_date' => $row['start_date'],
            'end_date' => $row['end_date'],
            'date_created' => $row['date_created'],
            'time_created' => $row['time_created'],
            'status' => $row['status'],
          
        ];
    }



    // Return the array
    // return $array_return;

    if (count($result) < 50) {

        return array('total_rows' => $totalrows, 'leave_info' => $leave_info, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'leave_info' => $leave_info, 'maxreach' => 0);
    }
}
