<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// Security check: Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

require_once "../include/db.php";

$userId = intval($_SESSION['user_id']);

// Plan Definitions
$plans = [
    'starter' => ['name' => 'Starter Plan', 'min' => 100, 'max' => 999, 'return' => 1.5, 'duration' => 7],
    'premium' => ['name' => 'Premium Tier', 'min' => 1000, 'max' => 4999, 'return' => 2.5, 'duration' => 14],
    'ultra'   => ['name' => 'Ultra Growth', 'min' => 5000, 'max' => 19999, 'return' => 3.8, 'duration' => 30],
    'vip'     => ['name' => 'VIP Institutional', 'min' => 20000, 'max' => 100000, 'return' => 5.0, 'duration' => 60]
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $planId = $_POST['plan_id'] ?? '';
    $amount = floatval($_POST['amount'] ?? 0);

    if (!isset($plans[$planId])) {
        $_SESSION['error'] = "Invalid investment plan selected.";
        header("Location: ../buy-plan.php");
        exit;
    }

    $selectedPlan = $plans[$planId];

    if ($amount < $selectedPlan['min'] || $amount > $selectedPlan['max']) {
        $_SESSION['error'] = "Amount must be between $" . number_format($selectedPlan['min']) . " and $" . number_format($selectedPlan['max']) . ".";
        header("Location: ../buy-plan.php");
        exit;
    }

    // Check Balance
    $userQuery = mysqli_query($conn, "SELECT balance FROM users WHERE id = $userId LIMIT 1");
    $userData = mysqli_fetch_assoc($userQuery);
    
    if (!$userData || $userData['balance'] < $amount) {
        $_SESSION['error'] = "Insufficient balance. Please deposit funds.";
        header("Location: ../buy-plan.php");
        exit;
    }

    mysqli_begin_transaction($conn);

    try {
        // 1. Deduct Balance
        $updateBalance = mysqli_prepare($conn, "UPDATE users SET balance = balance - ? WHERE id = ?");
        mysqli_stmt_bind_param($updateBalance, "di", $amount, $userId);
        mysqli_stmt_execute($updateBalance);

        // 2. Setup Plan Data
        $durationDays = $selectedPlan['duration'];
        $endDate = date('Y-m-d H:i:s', strtotime("+$durationDays days"));
        $dailyReturn = $selectedPlan['return'];
        $planName = $selectedPlan['name'];
        // last_payout is set to NOW so the cron job waits 24 hours from purchase
        $lastPayout = date('Y-m-d H:i:s'); 

        // 3. Record Investment (Fixed the type string space error here)
        $insertInvest = mysqli_prepare($conn, "INSERT INTO investments (user_id, plan_name, amount, daily_return, duration, status, last_payout, end_at, created_at) VALUES (?, ?, ?, ?, ?, 'active', ?, ?, NOW())");
        
        // Corrected: "isddiss" (7 chars) matches the 7 variables below
        mysqli_stmt_bind_param($insertInvest, "isddiss", $userId, $planName, $amount, $dailyReturn, $durationDays, $lastPayout, $endDate);
        mysqli_stmt_execute($insertInvest);

        mysqli_commit($conn);
        
        $_SESSION['success'] = "Successfully invested $" . number_format($amount, 2) . " in " . $planName . "!";
        header("Location: ../buy-plan.php");
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['error'] = "Transaction failed. Error: " . $e->getMessage();
        header("Location: ../buy-plan.php");
    }
} else {
    header("Location: ../buy-plan.php");
}