<?php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/investment_plans.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success'=>false,'message'=>'Method not allowed.']); exit; }
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false,'message'=>'Please sign in to invest.']); exit; }

$userId = (int) $_SESSION['user_id'];
$planKey = trim((string) ($_POST['plan'] ?? ''));
$amount = filter_var($_POST['amount'] ?? null, FILTER_VALIDATE_FLOAT);
$plans = investment_plans();
if (!isset($plans[$planKey]) || $amount === false || $amount <= 0) { http_response_code(422); echo json_encode(['success'=>false,'message'=>'Choose a plan and enter a valid investment amount.']); exit; }

$plan = $plans[$planKey]; $amount = round((float) $amount, 2);
if ($amount < $plan['minimum']) { http_response_code(422); echo json_encode(['success'=>false,'message'=>'The minimum for '.$plan['name'].' is £'.number_format($plan['minimum'],2).'.']); exit; }

$returnAmount = round($amount * $plan['rate'] / 100 * $plan['months'], 2);
$maturityAmount = round($amount + $returnAmount, 2);
$planName = (string) $plan['name'];
$planRate = (float) $plan['rate'];
$now = (new DateTimeImmutable('now'))->format('Y-m-d H:i:s');
$end = (new DateTimeImmutable('now'))->modify('+'.$plan['months'].' months')->format('Y-m-d H:i:s');

try {
    $conn->begin_transaction();
    $user = $conn->prepare('SELECT account_balance FROM users WHERE id=? FOR UPDATE');
    $user->bind_param('i', $userId); $user->execute();
    $balance = (float) ($user->get_result()->fetch_assoc()['account_balance'] ?? -1); $user->close();
    if ($balance < $amount) { $conn->rollback(); http_response_code(422); echo json_encode(['success'=>false,'message'=>'Your available balance is insufficient for this investment.']); exit; }
    $newBalance = $balance - $amount;
    $update = $conn->prepare('UPDATE users SET account_balance=? WHERE id=?'); $update->bind_param('di', $newBalance, $userId); $update->execute(); $update->close();
    $insert = $conn->prepare("INSERT INTO investments (user_id,package_name,amount,roi_percent,expected_return,start_date,end_date,status) VALUES (?,?,?,?,?,?,?,'active')");
    $insert->bind_param('isddsss', $userId, $planName, $amount, $planRate, $maturityAmount, $now, $end); $insert->execute(); $investmentId = $conn->insert_id; $insert->close();
    $monthlyPayment = round($amount * $plan['rate'] / 100, 2);
    $scheduledTotal = 0.00;
    $payment = $conn->prepare("INSERT INTO investment_return_payments (investment_id,user_id,period_number,rate_percent,amount,due_date) VALUES (?,?,?,?,?,?)");
    for ($period = 1; $period <= $plan['months']; $period++) {
        $paymentAmount = $period === $plan['months'] ? round($returnAmount - $scheduledTotal, 2) : $monthlyPayment;
        $dueDate = (new DateTimeImmutable($now))->modify('+'.$period.' months')->format('Y-m-d H:i:s');
        $payment->bind_param('iiidds', $investmentId, $userId, $period, $planRate, $paymentAmount, $dueDate);
        $payment->execute(); $scheduledTotal += $paymentAmount;
    }
    $payment->close();
    $reference = 'INV-'.$investmentId.'-'.date('YmdHis');
    $ledger = $conn->prepare("INSERT INTO transactions (user_id,reference,transaction_type,direction,amount,status,description,source_table,source_id) VALUES (?,?,'investment','debit',?,'completed',?,'investments',?)");
    $ledgerDescription = 'Investment allocation: '.$plan['name'];
    $ledger->bind_param('isdsi', $userId, $reference, $amount, $ledgerDescription, $investmentId); $ledger->execute(); $ledger->close();
    $description = 'Investment created: '.$plan['name'].' — £'.number_format($amount,2).'. '.$plan['rate'].'% return payment is scheduled each month, subject to plan terms.';
    $log = $conn->prepare("INSERT INTO activity_logs (user_id,actor,action_type,description,created_at) VALUES (?,'user','investment',?,?)"); $log->bind_param('iss', $userId, $description, $now); $log->execute(); $log->close();
    $conn->commit();
    echo json_encode(['success'=>true,'message'=>'Investment created successfully.','investment'=>['id'=>$investmentId,'maturity_date'=>$end,'principal'=>$amount,'projected_maturity_amount'=>$maturityAmount,'projected_return'=>$returnAmount]]);
} catch (Throwable $e) { $conn->rollback(); http_response_code(500); echo json_encode(['success'=>false,'message'=>'We could not create the investment. Please try again.']); }
