<?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;
$name = $jwt_validate->data->name;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;


// $institution_id = trim($postdata['institution_id']);
// $branch_id = trim($postdata['branch_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);

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

$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 get_fuel_expense($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $from_date, $to_date, $limit, $offset)
{
    $sql_count = "SELECT count(*) as total_rows FROM fuel_expense WHERE institution_id = ?";
    $array_params = [$institution_id];
    if ($branch_id != 'all' && $branch_id != null) {
            $sql_count .= " AND branch_id = ?";
            $array_params[] = $branch_id;
    }

    if ($search_string) {
            $sql_count .= " AND bus_id LIKE ?";
            $array_params[] = '%' . $search_string . '%';
    }

    // Add date filtering to the main query if dates are provided
    if ($from_date && $to_date) {
            $sql_count .= " AND date BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetch();
    $totalrows = $result_total['total_rows'];

    if ($limit == 'all') {
        $sql_session = "SELECT * FROM fuel_expense WHERE institution_id = ?";
        $array_params = [$institution_id];

        if ($branch_id != 'all' && $branch_id != null) {
            $sql_session .= " AND branch_id = ?";
            $array_params[] = $branch_id;
        }

        if ($search_string) {
            $sql_session .= " AND bus_id LIKE ?";
            $array_params[] = '%' . $search_string . '%';
        }

        // Add date filtering to the main query if dates are provided
        if ($from_date && $to_date) {
            $sql_session .= " AND date BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }

        $sql_session .= " ORDER BY date_created DESC, time_created DESC";
    } else {
        $sql_session = "SELECT * FROM fuel_expense WHERE institution_id = ?";
        $array_params = [$institution_id];

        if ($branch_id != 'all' && $branch_id != null) {
            $sql_session .= " AND branch_id = ?";
            $array_params[] = $branch_id;
        }

        if ($search_string) {
            $sql_session .= " AND bus_id LIKE ?";
            $array_params[] = '%' . $search_string . '%';
        }

        // Add date filtering to the main query if dates are provided
        if ($from_date && $to_date) {
            $sql_session .= " AND date BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }

        $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(PDO::FETCH_ASSOC);

    $array_return = [];

    // Loop through each session row to fetch data
    foreach ($session_rows as $rows) {
       if ($rows['bus_id'] === "miscellaneous") {
    
         $bus_number = "miscellaneous";
         } else {
    
          $bus_number_query = "SELECT * FROM buses WHERE id = ?";
          $array_params = [$rows['bus_id']];

            $stmt = $conn_rjllearning_specific->prepare($bus_number_query);
            $stmt->execute($array_params);

    // Fetch the result
           $bus_details = $stmt->fetch(PDO::FETCH_ASSOC);
          $bus_number = $bus_details ? $bus_details['bus_number'] : null;
        }

        
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
        $array_return[] = array(
            'fuel_expense_id' => $rows['id'],
            'institution_id' => $rows['institution_id'],
            'branch_id' => $branch_info,
            'bus_id' => $rows['bus_id'],
            'bus_number' => $bus_number,
            'date' => $rows['date'],
            'meter_reading' => $rows['meter_reading'],
            'topup' => $rows['topup'],
            'narration' => $rows['narration'],
            'added_by' => $rows['added_by'],
            'date_created' => $rows['date_created'],
            'time_created' => $rows['time_created']
        );
    }

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

if ($postdata['function_type'] == "fetch_bus_fuel_expense") {
    // $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.");
    }
    // $branch_id = isset($postdata['branch_id']) ? trim($postdata['branch_id']) : null;
    $search_string = isset($postdata['search_string']) ? trim($postdata['search_string']) : null;
    $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 = $postdata['limit'];
    $page = isset($postdata['page']) && is_numeric($postdata['page']) ? (int)$postdata['page'] : 1;

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