<?php
/**
 * create_investment.php: Handles user investment in plans
 * Part of Ton Sui Mining investment workflow
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require user authentication
requireLogin(true);

require_once 'config.php';
require_once 'db.php';
require_once 'csrf.php';

function respond($success, $message, $data = null) {
    $response = ['success' => $success, 'message' => $message];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);
$plan_id = isset($data['plan_id']) ? intval($data['plan_id']) : 0;
$amount = isset($data['amount']) ? floatval($data['amount']) : 0;

// Validate input
if ($plan_id <= 0) {
    respond(false, 'Invalid investment plan selected.');
}

if ($amount <= 0) {
    respond(false, 'Invalid investment amount. Amount must be greater than zero.');
}

try {
    // Get plan details first
    $planStmt = $pdo->prepare('SELECT * FROM investment_plans WHERE id = ? AND status = "active"');
    $planStmt->execute([$plan_id]);
    $plan = $planStmt->fetch();
    
    if (!$plan) {
        respond(false, 'Selected investment plan not found or is not active.');
    }
    
    // Check if amount is within plan limits
    if ($amount < floatval($plan['min_amount'])) {
        respond(false, 'Investment amount is below the minimum required for this plan: ' . number_format($plan['min_amount'], 2) . '.');
    }
    
    if (!empty($plan['max_amount']) && $amount > floatval($plan['max_amount'])) {
        respond(false, 'Investment amount exceeds the maximum allowed for this plan: ' . number_format($plan['max_amount'], 2) . '.');
    }
    
    // Check if user has sufficient balance and KYC status (support both schema variants)
    $hasKycStatus = false; $hasKycVerified = false;
    try {
        $uc = $pdo->query("SHOW COLUMNS FROM users");
        while ($col = $uc->fetch(PDO::FETCH_ASSOC)) {
            $f = strtolower($col['Field'] ?? '');
            if ($f === 'kycstatus') $hasKycStatus = true;
            if ($f === 'kyc_verified') $hasKycVerified = true;
        }
    } catch (Exception $e) { /* ignore */ }
    $fields = ['balance'];
    if ($hasKycStatus)   { $fields[] = 'kycStatus'; }
    if ($hasKycVerified) { $fields[] = 'kyc_verified'; }
    $sql = 'SELECT ' . implode(', ', $fields) . ' FROM users WHERE id = ?';
    $userStmt = $pdo->prepare($sql);
    $userStmt->execute([isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0]);
    $user = $userStmt->fetch();
    
    if (!$user) {
        respond(false, 'User not found.');
    }
    
    $balance = floatval($user['balance']);
    
    // PRIORITY 1: Check balance FIRST (more important than KYC)
    if ($balance < $amount) {
        respond(false, 'Insufficient balance. Your available balance is ' . number_format($balance, 8) . '. Please deposit funds first.');
    }
    
    // PRIORITY 2: Only check KYC if balance is sufficient
    // Accept either kyc_verified=1 (int) or kycStatus='approved' (string)
    $kycApproved = null;
    if (array_key_exists('kyc_verified', $user)) {
        $kycApproved = intval($user['kyc_verified']) === 1;
    }
    if ($kycApproved !== true && array_key_exists('kycStatus', $user)) {
        $kycApproved = strtolower((string)$user['kycStatus']) === 'approved';
    }
    // Bypass KYC when disabled in config
    if (isset($config['kyc_required']) && $config['kyc_required'] === false) {
        $kycApproved = true;
    }
    if ($kycApproved === null) { $kycApproved = true; }
    if (!$kycApproved) {
        respond(false, 'KYC verification required. Please complete your KYC verification before making investments. Go to Dashboard > KYC.');
    }
    
    // Calculate ROI and end date based on plan parameters
    $roi_amount = ($amount * floatval($plan['roi_percentage'])) / 100;
    $total_return = $amount + $roi_amount;
    $duration_days = intval($plan['duration_days']);
    $start_date = date('Y-m-d H:i:s');
    $end_date = date('Y-m-d H:i:s', strtotime("+{$duration_days} days"));
    
    // Start a transaction to ensure all operations are atomic
    $pdo->beginTransaction();
    
    // Deduct the investment amount from user balance
    $updateBalanceStmt = $pdo->prepare('UPDATE users SET balance = balance - ? WHERE id = ?');
    $updateBalanceStmt->execute([$amount, isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0]);
    
    // Create the investment record
    $investmentStmt = $pdo->prepare('
        INSERT INTO investments 
        (user_id, plan_id, amount, roi, total_return, status, start_date, end_date, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ');
    
    $investmentStmt->execute([
        isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0,
        $plan_id,
        $amount,
        $roi_amount,
        $total_return,
        'active',
        $start_date,
        $end_date
    ]);
    
    $investment_id = $pdo->lastInsertId();
    
    // Create a transaction record for the investment
    $transactionStmt = $pdo->prepare('
        INSERT INTO transactions 
        (user_id, type, amount, status, details, reference, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, NOW())
    ');
    
    $reference = 'INV-' . $investment_id;
    $details = json_encode([
        'plan_id' => $plan_id,
        'plan_name' => $plan['name'],
        'roi_percentage' => $plan['roi_percentage'],
        'duration_days' => $plan['duration_days'],
        'investment_id' => $investment_id
    ]);
    
    $transactionStmt->execute([
        isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0,
        'investment',
        $amount,
        'completed',
        $details,
        $reference
    ]);
    
    // Log the investment
    $logStmt = $pdo->prepare('
        INSERT INTO security_logs 
        (action, user_id, ip_address, user_agent, details, created_at) 
        VALUES (?, ?, ?, ?, ?, NOW())
    ');
    
    $logStmt->execute([
        'investment_created',
        isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0,
        $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        json_encode([
            'plan_id' => $plan_id,
            'plan_name' => $plan['name'],
            'amount' => $amount,
            'roi_amount' => $roi_amount,
            'end_date' => $end_date,
            'investment_id' => $investment_id
        ])
    ]);
    
    // Commit the transaction
    $pdo->commit();
    
    respond(true, 'Investment created successfully. Your investment will mature on ' . date('M d, Y', strtotime($end_date)) . '.', [
        'investment_id' => $investment_id,
        'plan_name' => $plan['name'],
        'amount' => $amount,
        'roi_amount' => $roi_amount,
        'total_return' => $total_return,
        'start_date' => $start_date,
        'end_date' => $end_date
    ]);
    
} catch (Exception $e) {
    // Something went wrong, rollback
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log('Investment error: ' . $e->getMessage());
    respond(false, 'An error occurred while processing your investment. Please try again or contact support.');
}
