<?php
session_start();
require 'db.php'; // hakikisha una include connection yako

if (!isset($_SESSION['user_id'])) {
    die("Please login to invest.");
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $user_id = $_SESSION['user_id'];
    $amount = floatval($_POST['amount']);
    $cycle_days = intval($_POST['cycle_days']);
    $daily_income = floatval($_POST['daily_income']);
    $start_time = date("Y-m-d H:i:s");
    $last_earnings_time = $start_time;
    $status = "active";

    // Check balance
    $stmt = $conn->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($balance);
    $stmt->fetch();
    $stmt->close();

    if ($balance < $amount) {
        die("Insufficient balance.");
    }

    // Deduct amount
    $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
    $stmt->bind_param("di", $amount, $user_id);
    $stmt->execute();
    $stmt->close();

    // Save investment
    $stmt = $conn->prepare("INSERT INTO investments (user_id, amount, start_time, status, daily_percentage, last_earnings_time, daily_earnings, total_earned)
        VALUES (?, ?, ?, ?, 0, ?, ?, 0)");
    $stmt->bind_param("idssdd", $user_id, $amount, $start_time, $status, $last_earnings_time, $daily_income);
    $stmt->execute();
    $stmt->close();

    echo "Investment successful!";
} else {
    echo "Invalid request.";
}
?>
