<?php
include "../../conn.php";
include "../../functions2.php";

header('Content-Type: application/json');

$shonusign = $_POST['signature'] ?? '';

if ($shonusign == $signature) {
    $bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
    $author = $bearer[1];
    $is_jwt_valid = is_jwt_valid($author);
    $data_auth = json_decode($is_jwt_valid, true);

    if ($data_auth['status'] === 'Success') {
        $user_token = mysqli_real_escape_string($conn, $author); // Use JWT token
        $query1 = "SELECT id FROM shonu_subjects WHERE akshinak = '$user_token' LIMIT 1";
        $result1 = mysqli_query($conn, $query1);
        $user_data = mysqli_fetch_assoc($result1);

        if (!$user_data) {
            echo json_encode(["code" => 1, "msg" => "User not found"]);
            exit();
        }
        $user_id = mysqli_real_escape_string($conn, $user_data['id']); // Consistent user_id

        // Step 1: Fetch total amount transferred to safe box
        $safe_query = "SELECT SUM(amount) as safeAmount FROM safe_box WHERE user_id = '$user_id'";
        $safe_result = mysqli_query($conn, $safe_query);
        if (!$safe_result) {
            echo json_encode(["code" => 1, "msg" => "Query failed: " . mysqli_error($conn)]);
            exit();
        }
        $safeAmount = mysqli_fetch_assoc($safe_result)['safeAmount'] ?? 0;

        // Step 2: Define daily interest rate
        $dayShareRate = 0.005; // 0.5% as per your system (adjust to 0.06000 if 6% is intended)

        // Step 3: Calculate daily income (safeEarnings)
        $safeEarnings = $safeAmount * $dayShareRate;

        // Step 4: Calculate amount available to withdraw from safe box (balance)
        $balance = $safeAmount + $safeEarnings; // Total withdrawable from safe box

        // Response
        $response = [
            "data" => [
                "balance" => $balance, // Amount available to withdraw from safe box
                "transferredAmount" => $safeAmount, // Amount transferred to safe box
                "dayShareRate" => $dayShareRate, // Daily interest rate
                "safeEarnings" => $safeEarnings // Daily income from safe box
            ],
            "code" => 0,
            "msg" => "Succeed",
            "msgCode" => 0,
            "serviceNowTime" => date("Y-m-d H:i:s")
        ];
        echo json_encode($response);
    } else {
        echo json_encode(["code" => 1, "msg" => "Unauthorized"]);
    }
} else {
    echo json_encode(["code" => 1, "msg" => "Invalid signature"]);
}

mysqli_close($conn);
?>