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

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);
header('vary: Origin');

date_default_timezone_set("Asia/Kolkata");
$shnunc = date("Y-m-d H:i:s");
$res = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $shnunc,
];

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

if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    if (isset($shonupost['planId']) && isset($shonupost['amount'])) {
        $plan_id = intval($shonupost['planId']);
        $amount = floatval($shonupost['amount']);

        $bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
        $author = $bearer[1];
        $is_jwt_valid = is_jwt_valid($author);
        $data_auth = json_decode($is_jwt_valid, 1);

        if($data_auth['status'] === 'Success') {
            $user_id = $data_auth['payload']['id'];

            // Get plan details
            $plan_query = "SELECT * FROM investment_plans WHERE id = $plan_id AND status = 1";
            $plan_result = $conn->query($plan_query);

            if ($plan_result->num_rows > 0) {
                $plan = $plan_result->fetch_assoc();

                // Validate amount
                if ($amount < $plan['min_amount'] || $amount > $plan['max_amount']) {
                    $res['code'] = 7;
                    $res['msg'] = 'Investment amount must be between ' . $plan['min_amount'] . ' and ' . $plan['max_amount'];
                    http_response_code(200);
                    echo json_encode($res);
                    exit;
                }

                // Check user balance
                $balance_query = "SELECT motta FROM shonu_kaichila WHERE balakedara = $user_id";
                $balance_result = $conn->query($balance_query);
                $balance_row = $balance_result->fetch_assoc();
                $current_balance = $balance_row['motta'];

                if ($current_balance < $amount) {
                    $res['code'] = 7;
                    $res['msg'] = 'Insufficient balance';
                    http_response_code(200);
                    echo json_encode($res);
                    exit;
                }

                // Deduct balance
                $new_balance = $current_balance - $amount;
                $conn->query("UPDATE shonu_kaichila SET motta = $new_balance WHERE balakedara = $user_id");

                // Insert investment
                $insert_sql = "INSERT INTO user_investments (user_id, plan_id, amount) VALUES ($user_id, $plan_id, $amount)";
                if ($conn->query($insert_sql)) {
                    $res['data'] = ['new_balance' => $new_balance];
                    $res['code'] = 0;
                    $res['msg'] = 'Investment successful';
                    $res['msgCode'] = 0;
                    http_response_code(200);
                    echo json_encode($res);
                } else {
                    $res['code'] = 7;
                    $res['msg'] = 'Investment failed';
                    http_response_code(200);
                    echo json_encode($res);
                }
            } else {
                $res['code'] = 7;
                $res['msg'] = 'Plan not found';
                http_response_code(200);
                echo json_encode($res);
            }
        } else {
            $res['code'] = 4;
            $res['msg'] = 'No operation permission';
            $res['msgCode'] = 2;
            http_response_code(401);
            echo json_encode($res);
        }
    } else {
        $res['code'] = 9;
        $res['msg'] = 'Missing parameters';
        unset($res['msgCode']);
        unset($res['serviceNowTime']);
        http_response_code(200);
        echo json_encode($res);
    }
} else {
    http_response_code(405);
    echo json_encode($res);
}
?>
