<?php

// Display errors for debugging
ini_set('display_errors', 1);

// Include necessary files
require_once '../../../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php"; // Database connection
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_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 . "faculty_api/modules/transportation/vehicle_expense/expense_stats/functions.php";

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

checkIfNoPhpContentsReceive();

if (
    
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All fields are required.");
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Decode and validate JWT token
$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;

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

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

// Validate institution_id and branch_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.");
} 

$response = [];

$function_type = $postdata['function_type'];

if ($function_type === "transaction_stats") {
    $min_date = isset($postdata['min_date']) ? $postdata['min_date'] : null;
    $max_date = isset($postdata['max_date']) ? $postdata['max_date'] : null;

    // Validate dates
    if (!$min_date || !$max_date || !strtotime($min_date) || !strtotime($max_date) || $min_date > $max_date) {
        errorreturn("Both min_date and max_date are required and must be valid.");
    }

    // If min_date and max_date are equal, handle the special case
    if ($min_date == $max_date) {
        // Initialize result structure
        $result = [
            'vendor_info' => [],
            'group_info' => []
        ];

        // SQL query to get transaction data with category details
        $sql_session = "
            SELECT 
                DATE(date) AS transaction_date, 
                vendor_name, 
                amount,
                category_id, 
                transaction_type_group
            FROM 
                unmarked_transaction 
            WHERE 
                institution_id = ? AND branch_id = ? AND date BETWEEN ? AND ? 
            ORDER BY 
                transaction_date ASC, vendor_name ASC;
        ";

        // Prepare and execute SQL query
        $stmt = $conn_rjllearning_specific->prepare($sql_session);
        $stmt->execute([$institution_id, $branch_id, $min_date, $max_date]);

        // Fetch all transactions
        $transactions = $stmt->fetchAll();

        // Process each transaction
        foreach ($transactions as $transaction) {
            $transaction_date = $transaction['transaction_date'];
            $vendor_name = $transaction['vendor_name'];
            $amount = $transaction['amount'];
            $transaction_type_group = $transaction['transaction_type_group'];
            $category_id = $transaction['category_id'];

            // Fetch vendor info based on category_id
            $fetch_vendor_sql = "SELECT id, group_name FROM unmarked_transaction_type_group WHERE id = ?";
            $stmt = $conn_rjllearning_specific->prepare($fetch_vendor_sql);
            $stmt->execute([$category_id]);
            $vendor_info = $stmt->fetch(PDO::FETCH_ASSOC);

            // Default values if vendor info is not found
            $group_name = $vendor_info ? $vendor_info['group_name'] : 'Unknown Group';

            // Handle vendor_info by date
            if (!isset($result['vendor_info'][$transaction_date])) {
                $result['vendor_info'][$transaction_date] = [
                    'label' => $transaction_date,
                    'expense_vendor_info' => [],
                    'receipt_vendor_info' => []
                ];
            }

            // Populate vendor_info based on transaction type group
            if ($transaction_type_group == 'expense') {
                // Sum up amounts for the same vendor_name
                if (isset($result['vendor_info'][$transaction_date]['expense_vendor_info'][$vendor_name])) {
                    $result['vendor_info'][$transaction_date]['expense_vendor_info'][$vendor_name] += $amount;
                } else {
                    $result['vendor_info'][$transaction_date]['expense_vendor_info'][$vendor_name] = $amount;
                }
            } elseif ($transaction_type_group == 'receipt') {
                // Sum up amounts for the same vendor_name
                if (isset($result['vendor_info'][$transaction_date]['receipt_vendor_info'][$vendor_name])) {
                    $result['vendor_info'][$transaction_date]['receipt_vendor_info'][$vendor_name] += $amount;
                } else {
                    $result['vendor_info'][$transaction_date]['receipt_vendor_info'][$vendor_name] = $amount;
                }
            }

            // Handle group_info by date
            if (!isset($result['group_info'][$transaction_date])) {
                $result['group_info'][$transaction_date] = [
                    'label' => $transaction_date,
                    'expense_vendor_info' => [],
                    'receipt_vendor_info' => []
                ];
            }

            // Populate group_info based on transaction type group
            if ($transaction_type_group == 'expense') {
                // Sum up amounts for the same group_name
                if (isset($result['group_info'][$transaction_date]['expense_vendor_info'][$group_name])) {
                    $result['group_info'][$transaction_date]['expense_vendor_info'][$group_name] += $amount;
                } else {
                    $result['group_info'][$transaction_date]['expense_vendor_info'][$group_name] = $amount;
                }
            } elseif ($transaction_type_group == 'receipt') {
                // Sum up amounts for the same group_name
                if (isset($result['group_info'][$transaction_date]['receipt_vendor_info'][$group_name])) {
                    $result['group_info'][$transaction_date]['receipt_vendor_info'][$group_name] += $amount;
                } else {
                    $result['group_info'][$transaction_date]['receipt_vendor_info'][$group_name] = $amount;
                }
            }
        }

        // Prepare final vendor_info for response
        $final_vendor_info = [];
        foreach ($result['vendor_info'] as $date => $info) {
            $final_vendor_info[] = [
                'label' => $info['label'],
                'expense_vendor_info' => array_map(function($vendor_name, $amount) {
                    return ['vendor_name' => $vendor_name, 'amount' => $amount];
                }, array_keys($info['expense_vendor_info']), $info['expense_vendor_info']),
                'receipt_vendor_info' => array_map(function($vendor_name, $amount) {
                    return ['vendor_name' => $vendor_name, 'amount' => $amount];
                }, array_keys($info['receipt_vendor_info']), $info['receipt_vendor_info'])
            ];
        }

        // Prepare final group_info for response
        $final_group_info = [];
        foreach ($result['group_info'] as $date => $info) {
            $final_group_info[] = [
                'label' => $info['label'],
                'expense_vendor_info' => array_map(function($group_name, $amount) {
                    return ['vendor_name' => $group_name, 'amount' => $amount];
                }, array_keys($info['expense_vendor_info']), $info['expense_vendor_info']),
                'receipt_vendor_info' => array_map(function($group_name, $amount) {
                    return ['vendor_name' => $group_name, 'amount' => $amount];
                }, array_keys($info['receipt_vendor_info']), $info['receipt_vendor_info'])
            ];
        }

        // Final result structure to return
        successreturn([
            'date_wise_info' => [
                'vendor_info' => $final_vendor_info,
                'group_info' => $final_group_info
            ]
        ]);
    } else {
        // Calculate the date difference
        $date1 = new DateTime($min_date);
        $date2 = new DateTime($max_date);
        $interval = $date1->diff($date2);

        if ($interval->days <= 7) {
            // Call the dateWise_transactions function for a range of days
            $response = dateWise_transactions(
                $institution_id,
                $branch_id,
                $conn_rjllearning_specific,
                $min_date,
                $max_date
            );
        } else if ($interval->days <= 31) {
            // fetchWeeklyVisitors function
            $response = weekWise_transactions(
                $institution_id,
                $branch_id,
                $conn_rjllearning_specific,
                $min_date,
                $max_date
            );
        } else {
            $response = monthWise_transactions(
                $institution_id,
                $branch_id,
                $conn_rjllearning_specific, 
                $min_date,
                $max_date
            );
        }

        successreturn($response);
    }
} else {
    errorreturn("Invalid function_type");
}
