<?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['investmentId'])) {
        $investment_id = intval($shonupost['investmentId']);

        $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 investment details
            $investment_query = "SELECT ui.*, ip.interest_rate, ip.duration_days
                                FROM user_investments ui
                                JOIN investment_plans ip ON ui.plan_id = ip.id
                                WHERE ui.id = $investment_id AND ui.user_id = $user_id AND ui.status = 1";
            $investment_result = $conn->query($investment_query);

            if ($investment_result->num_rows > 0) {
                $investment = $investment_result->fetch_assoc();

                $invested_at = strtotime($investment['invested_at']);
                $last_claim = $investment['last_claim'] ? strtotime($investment['last_claim']) : $invested_at;
                $now = time();

                // Check if 24 hours have passed since last claim
                if (($now - $last_claim) < 86400) { // 24 hours in seconds
                    $res['code'] = 7;
                    $res['msg'] = 'Cannot claim yet. 24 hours must pass since last claim.';
                    http_response_code(200);
                    echo json_encode($res);
                    exit;
                }

                // Calculate daily interest
                $daily_interest = ($investment['amount'] * $investment['interest_rate'] / 100) / 30; // Assuming 30 days month

                // Check if investment duration is over
                $duration_seconds = $investment['duration_days'] * 86400;
                if (($now - $invested_at) > $duration_seconds) {
                    $res['code'] = 7;
                    $res['msg'] = 'Investment period has ended';
                    http_response_code(200);
                    echo json_encode($res);
                    exit;
                }

                // Update 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();
                $new_balance = $balance_row['motta'] + $daily_interest;

                $conn->query("UPDATE shonu_kaichila SET motta = $new_balance WHERE balakedara = $user_id");

                // Record claim
                $claim_sql = "INSERT INTO investment_claims (investment_id, amount) VALUES ($investment_id, $daily_interest)";
                $conn->query($claim_sql);

                // Update investment last claim and total claimed
                $new_total_claimed = $investment['total_claimed'] + $daily_interest;
                $conn->query("UPDATE user_investments SET last_claim = '$shnunc', total_claimed = $new_total_claimed WHERE id = $investment_id");

                $res['data'] = ['claimed_amount' => $daily_interest, 'new_balance' => $new_balance];
                $res['code'] = 0;
                $res['msg'] = 'Claim successful';
                $res['msgCode'] = 0;
                http_response_code(200);
                echo json_encode($res);
            } else {
                $res['code'] = 7;
                $res['msg'] = 'Investment 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);
}
?>
