<?php
/**
 * delete_investment.php: Deletes an investment (for testing purposes only)
 * This endpoint should be restricted to test environments only
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/delete_investment_errors.log');

// 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';

header('Content-Type: application/json');
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, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

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

// Log the request for debugging
error_log("Delete investment request received: " . print_r([
    'method' => $_SERVER['REQUEST_METHOD'],
    'post' => $_POST,
    'get' => $_GET,
    'input' => file_get_contents('php://input')
], true));

try {
    require_once 'config.php';
    require_once 'db.php';
    
    // Only allow this endpoint in test environment
    // Temporarily allow in all environments for testing
    if (defined('ENVIRONMENT') && ENVIRONMENT === 'production') {
        throw new Exception('This endpoint is not available in production');
    }

    // Get the raw POST data
    $input = file_get_contents('php://input');
    $data = [];
    if (!empty($input)) {
        if (strpos($input, '{') === 0) {
            // JSON input
            $data = json_decode($input, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception('Invalid JSON input: ' . json_last_error_msg());
            }
        } else {
            // Form data
            parse_str($input, $data);
        }
    }

    // Merge with POST/GET data
    $data = array_merge($data, $_POST, $_GET);
    
    // Log the parsed data for debugging
    error_log("Parsed request data: " . print_r($data, true));

    // Get investment_id from data
    $investmentId = isset($data['investment_id']) ? intval($data['investment_id']) : 0;

    if (empty($investmentId)) {
        throw new Exception('Investment ID is required');
    }

    // Log the database connection status
    error_log("Database connection status: " . ($pdo ? 'Connected' : 'Not connected'));
    
    // Begin transaction
    $pdo->beginTransaction();
    
    try {
        // First, delete related transactions (if any)
        $stmt = $pdo->prepare("DELETE FROM transactions WHERE reference = :reference OR details LIKE :details");
        $reference = 'investment_' . $investmentId;
        $details = '%"investment_id":' . $investmentId . '%';
        $stmt->bindParam(':reference', $reference, PDO::PARAM_STR);
        $stmt->bindParam(':details', $details, PDO::PARAM_STR);
        $deletedTransactions = $stmt->execute();
        
        error_log("Deleted transactions: " . $stmt->rowCount());
        
        // Then delete the investment
        $stmt = $pdo->prepare("DELETE FROM investments WHERE id = :id");
        $stmt->bindParam(':id', $investmentId, PDO::PARAM_INT);
        $stmt->execute();
        $deleted = $stmt->rowCount() > 0;
        
        if ($deleted) {
            $pdo->commit();
            $response = [
                'success' => true,
                'message' => 'Investment deleted successfully',
                'investment_id' => $investmentId,
                'deleted_transactions' => $deletedTransactions ? $stmt->rowCount() : 0
            ];
            error_log("Success: " . print_r($response, true));
            echo json_encode($response);
        } else {
            $pdo->rollBack();
            http_response_code(404);
            $response = [
                'success' => false,
                'message' => 'Investment not found or already deleted',
                'investment_id' => $investmentId
            ];
            error_log("Not found: " . print_r($response, true));
            echo json_encode($response);
        }
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log("PDO Error in transaction: " . $e->getMessage());
        throw $e;
    }
} catch (Exception $e) {
    error_log("Error in delete_investment.php: " . $e->getMessage() . "\n" . $e->getTraceAsString());
    
    http_response_code(500);
    $errorResponse = [
        'success' => false,
        'message' => 'Error: ' . $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => ENVIRONMENT === 'test' ? $e->getTraceAsString() : null
    ];
    
    echo json_encode($errorResponse);
}
