<?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) {
    $sql = "SELECT coin_id FROM rr_410_coin WHERE coin_name = '$coin'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['coin_id'];
    } else {
        $insert_sql = "INSERT INTO rr_410_coin (coin_name) VALUES ('$coin')";
        if ($conn->query($insert_sql) === TRUE) {
            return $conn->insert_id;
        }
    }
    return null;
}

function getCoinpairId($coinpair, $conn) {
    $sql = "SELECT coinpair_id FROM rr_410_coinpair WHERE coinpair_name = '$coinpair'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['coinpair_id'];
    } else {
        $insert_sql = "INSERT INTO rr_410_coinpair (coinpair_name) VALUES ('$coinpair')";
        if ($conn->query($insert_sql) === TRUE) {
            return $conn->insert_id;
        }
    }
    return null;
}

function getDirectionId($direction, $conn) {
    $sql = "SELECT direction_id FROM rr_410_direction WHERE direction = '$direction'";
    $result = $conn->query($sql);
    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') {
        // Long position calculation without intermediate rounding
        $percentage = ((100 / $open_price) * $close_price - 100) * $leverage;
    } elseif ($direction === 'short') {
        // Short position calculation without intermediate rounding
        $percentage = ((100 / $open_price) * $close_price - 100) * (-1) * $leverage;
    } else {
        return null;
    }
    
    // Round the final result to two decimal places
    return round($percentage, 2);
}


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

    // Handle file upload (photo) if provided
    $photo_name = null; // Default to null if no photo is uploaded
    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; // Define where to store the uploaded file

        $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
    $account_sql = "SELECT account_id FROM rr_410_accounts WHERE account_name = '$account_name'";
    $account_result = $conn->query($account_sql);

    if ($account_result && $account_result->num_rows > 0) {
        $account_row = $account_result->fetch_assoc();
        $account_id = $account_row['account_id']; // Account ID found

        // 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) {
            // Insert the trade data into rr_410_history_input
            $history_sql = "INSERT INTO rr_410_history_input (coin_id, coinpair_id, direction_id, account_id, open_price, close_price, leverage, close_date, photo, percents) 
                            VALUES ('$coin_id', '$coinpair_id', '$direction_id', '$account_id', '$open_price', '$close_price', '$leverage', '$close_date', ";

            // If the photo is not provided, insert NULL
            if ($photo_name) {
                $history_sql .= "'$photo_name', '$percents')";
            } else {
                $history_sql .= "NULL, '$percents')";
            }

            if ($conn->query($history_sql) === TRUE) {
                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: ' . $conn->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();
?>