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

//aws image store
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);
// print_r($postdata);
checkIfNoPhpContentsReceive();

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_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  !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;
$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.');
} else {
    $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);

function getvendor($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $transaction_type_group, $start_date = null, $end_date = null)
{
    $sql_session = "
        SELECT 
            DATE(date) AS transaction_date, 
            vendor_name, 
            amount,
            category_id
        FROM 
            unmarked_transaction 
        WHERE 
            institution_id = ? 
             AND transaction_type_group IN ('expense', 'receipt');
    ";

    // Prepare parameters
    $array_params = [$institution_id];

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

    // Add vendor_name search condition
    if (!empty($search_string)) {
        $sql_session .= " AND vendor_name LIKE ? ";
        $array_params[] = "%" . $search_string . "%"; // Add wildcard for partial matching
    }

    // Add date range filter if start_date and end_date are provided
    if ($start_date !== null && $end_date !== null) {
        $sql_session .= " AND DATE(date) BETWEEN ? AND ? ";
        $array_params[] = $start_date;
        $array_params[] = $end_date;
    }

    // Order by vendor_name and date
    $sql_session .= " ORDER BY vendor_name ASC, date ASC";

    // Execute the query
    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);

    // Fetch results
    $expense_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_data = [];
    foreach ($expense_stats as $row) {
        $vendor = $row['vendor_name'];
        $date = $row['transaction_date'];
        $amount = $row['amount'];
        $category_id = $row['category_id'];

        $fetch_vendor_sql = "SELECT id, group_name FROM unmarked_transaction_type_group WHERE id = ?";

        // Prepare and execute the query
        $stmt = $conn_rjllearning_specific->prepare($fetch_vendor_sql);
        $stmt->execute([$category_id]);

        // Fetch the result
        $vendor_info = $stmt->fetch(PDO::FETCH_ASSOC);

        // Check if vendor info was found
        if ($vendor_info) {
            // Successfully fetched vendor info
            $group_id = $vendor_info['id'];
            $group_name = $vendor_info['group_name'];
        } else {
            $group_id = null;
            $group_name = null;
        }

        // Ensure we are using vendor as the key for $formatted_data
        if (!isset($formatted_data[$vendor])) {
            $formatted_data[$vendor] = [];
        }
        if (!isset($formatted_data[$vendor][$date])) {
            $formatted_data[$vendor][$date] = [
                'date' => $date,
                'amounts' => [],
                'total_expense' => 0
            ];
        }

        // Add the individual amount
        $formatted_data[$vendor][$date]['amounts'][] = $amount;

        // Increment the total for the date
        $formatted_data[$vendor][$date]['total_expense'] += $amount;
    }

    // Prepare final output
    $output = ['data' => []];
    foreach ($formatted_data as $vendor => $dates) {
        $daily_stats = [];
        foreach ($dates as $date => $stats) {
            $daily_stats[] = [
                'transaction_date' => $stats['date'],
                'amounts' => $stats['amounts'],
                'total_expense' => $stats['total_expense']
            ];
        }
        // Instead of $vendor_info, use the group_name for the vendor
        $output['data'][] = [
            'vendor_name' => $vendor, // Use vendor name directly
            'group_name' => $group_name, // If you want the group name in the output
            'daily_stats' => $daily_stats
        ];
    }

    return $output;
}


if ($postdata['function_type'] == "fetch_daily_expense_category_wise_stats") {
    // $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']) && !empty($postdata['branch_id']) ? trim($postdata['branch_id']) : null;
    $transaction_type_group = isset($postdata['transaction_type_group']) ? trim($postdata['transaction_type_group']) : null;
    $search_string = isset($postdata['search_string']) ? trim($postdata['search_string']) : null;
    $start_date = isset($postdata['start_date']) ? trim($postdata['start_date']) : null;
    $end_date = isset($postdata['end_date']) ? trim($postdata['end_date']) : null;


 
        $success['data'] = getvendor($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $transaction_type_group,$start_date, $end_date);
        successreturn($success);
    
}
