<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection
include('connection.php');

// Helper function definitions
function getCoinId($coin, $conn) {
    $stmt = $conn->prepare("SELECT coin_id FROM rr_410_coin WHERE coin_name = ?");
    $stmt->bind_param('s', $coin);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['coin_id'];
    } else {
        $stmt = $conn->prepare("INSERT INTO rr_410_coin (coin_name) VALUES (?)");
        $stmt->bind_param('s', $coin);
        if ($stmt->execute()) {
            return $conn->insert_id;
        }
    }
    return null;
}

function getCoinpairId($coinpair, $conn) {
    $stmt = $conn->prepare("SELECT coinpair_id FROM rr_410_coinpair WHERE coinpair_name = ?");
    $stmt->bind_param('s', $coinpair);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['coinpair_id'];
    } else {
        $stmt = $conn->prepare("INSERT INTO rr_410_coinpair (coinpair_name) VALUES (?)");
        $stmt->bind_param('s', $coinpair);
        if ($stmt->execute()) {
            return $conn->insert_id;
        }
    }
    return null;
}

function getDirectionId($direction, $conn) {
    $stmt = $conn->prepare("SELECT direction_id FROM rr_410_direction WHERE direction = ?");
    $stmt->bind_param('s', $direction);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['direction_id'];
    }
    return null;
}

// Function to calculate percentage gain/loss
function calculatePercents($direction, $open_price, $close_price, $leverage) {
    if ($direction === 'long') {
        $percentage = ((100 / $open_price) * $close_price - 100) * $leverage;
    } elseif ($direction === 'short') {
        $percentage = ((100 / $open_price) * $close_price - 100) * (-1) * $leverage;
    } else {
        return null;
    }
    
    return round($percentage, 2);
}

// Check if POST variables are set
if (isset($_POST['coin'], $_POST['coinpair'], $_POST['direction'], $_POST['account_name'], $_POST['open_price'], $_POST['close_price'], $_POST['leverage'], $_POST['close_date'], $_POST['profile_id'])) {
    $coin = $_POST['coin'];
    $coinpair = $_POST['coinpair'];
    $direction = $_POST['direction'];
    $account_name = $_POST['account_name'];
    $open_price = $_POST['open_price'];
    $close_price = $_POST['close_price'];
    $leverage = $_POST['leverage'];
    $close_date = $_POST['close_date'];
    $profile_id = $_POST['profile_id'];
    
    // Calculate percentage gain/loss
    $percents = calculatePercents($direction, $open_price, $close_price, $leverage);

    // Handle file upload (photo) if provided
    $photo_name = null;
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $photo_tmp = $_FILES['photo']['tmp_name'];
        $photo_name = basename($_FILES['photo']['name']);
        $photo_path = '../photo/' . $photo_name;

        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        $fileType = mime_content_type($photo_tmp);

        if (in_array($fileType, $allowedTypes)) {
            if (!move_uploaded_file($photo_tmp, $photo_path)) {
                echo json_encode(['success' => false, 'message' => 'Failed to upload photo']);
                exit;
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid file type']);
            exit;
        }
    }

    // Get the account_id from the account_name and profile_id
    $stmt = $conn->prepare("SELECT account_id FROM rr_410_accounts WHERE account_name = ? AND profile_id = ?");
    $stmt->bind_param("si", $account_name, $profile_id);
    $stmt->execute();
    $account_result = $stmt->get_result();
    
    if ($account_result && $account_result->num_rows > 0) {
        $account_row = $account_result->fetch_assoc();
        $account_id = $account_row['account_id'];

        // Get Coin, Coinpair, and Direction IDs
        $coin_id = getCoinId($coin, $conn);
        $coinpair_id = getCoinpairId($coinpair, $conn);
        $direction_id = getDirectionId($direction, $conn);

        if ($coin_id && $coinpair_id && $direction_id) {
            $stmt = $conn->prepare("INSERT INTO rr_410_history_input (coin_id, coinpair_id, direction_id, account_id, open_price, close_price, leverage, close_date, photo, percents) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param('iiiiiddsss', $coin_id, $coinpair_id, $direction_id, $account_id, $open_price, $close_price, $leverage, $close_date, $photo_name, $percents);
            
            if ($stmt->execute()) {
                echo json_encode([
                    'success' => true,
                    'coin_id' => $coin_id,
                    'coinpair_id' => $coinpair_id,
                    'direction_id' => $direction_id,
                    'account_id' => $account_id,
                    'percents' => $percents
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to insert trade data: ' . $stmt->error]);
            }
        } else {
            echo json_encode([
                'success' => false, 
                'message' => 'Invalid coin, coinpair, or direction IDs', 
                'coin_id' => $coin_id, 
                'coinpair_id' => $coinpair_id, 
                'direction_id' => $direction_id, 
                'account_id' => $account_id
            ]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Account not found']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
}

$conn->close();
?>
