<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
$db = getDB();

// Helper function if get_option doesn't exist
if (!function_exists('get_option')) {
    function get_option(string $key, $default = '') {
        global $db;
        if (isset($db)) {
            $stmt = $db->prepare("SELECT option_value FROM options WHERE option_key = ? LIMIT 1");
            if ($stmt) {
                $stmt->bind_param("s", $key);
                $stmt->execute();
                $result = $stmt->get_result();
                $row = $result->fetch_assoc();
                $stmt->close();
                if ($row) return $row['option_value'];
            }
        }
        return $default;
    }
}

// Helper function if setFlash doesn't exist
if (!function_exists('setFlash')) {
    function setFlash(string $message, string $type = 'info') {
        $_SESSION['flash'] = ['message' => $message, 'type' => $type];
    }
}

// Validate input
$coinId = (int)($_POST['coin_id'] ?? 0);
$fiatAmount = (float)($_POST['fiat_amount'] ?? 0);
$cryptoAmount = (float)($_POST['crypto_amount'] ?? 0);
$fiatRate = (float)($_POST['fiat_rate'] ?? 0);
$walletAddress = trim($_POST['wallet_address'] ?? '');

// DEBUG: Log what we received
error_log("Deposit submission: coinId=$coinId, fiatAmount=$fiatAmount, cryptoAmount=$cryptoAmount, rate=$fiatRate");

// Validation
if ($coinId <= 0) {
    setFlash('Invalid wallet selected', 'danger');
    header('Location: crypto-deposit.php');
    exit;
}

if ($fiatAmount <= 0) {
    setFlash('Please enter a valid deposit amount greater than 0', 'danger');
    header('Location: crypto-deposit.php');
    exit;
}

if ($cryptoAmount <= 0) {
    setFlash('Could not calculate crypto amount. Please try again.', 'danger');
    header('Location: crypto-deposit.php');
    exit;
}

// Get wallet info
$stmt = $db->prepare("SELECT * FROM crypto_wallets WHERE id = ? AND is_active = 1");
$stmt->bind_param("i", $coinId);
$stmt->execute();
$result = $stmt->get_result();
$wallet = $result->fetch_assoc();
$stmt->close();

if (!$wallet) {
    setFlash('Invalid wallet selected', 'danger');
    header('Location: crypto-deposit.php');
    exit;
}

// Check minimum deposit
$minDeposit = (float)($wallet['min_deposit'] ?? 0);
if ($minDeposit > 0 && $fiatAmount < $minDeposit) {
    setFlash('Minimum deposit is $' . number_format($minDeposit, 2), 'danger');
    header('Location: crypto-deposit.php');
    exit;
}

// Generate unique reference
$reference = 'CRP-' . strtoupper(substr($wallet['coin_symbol'], 0, 3)) . '-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));

// Insert into crypto_deposits table
$stmt = $db->prepare("
    INSERT INTO crypto_deposits (
        user_id, wallet_id, fiat_amount, crypto_amount, rate_used, 
        wallet_address, reference, status, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
");
$stmt->bind_param("iiddsss", 
    $user['id'], $coinId, $fiatAmount, $cryptoAmount, $fiatRate,
    $walletAddress, $reference
);
$stmt->execute();
$depositId = $stmt->insert_id;
$stmt->close();

// Also create a transaction record
$description = 'Crypto deposit: ' . number_format($cryptoAmount, 8) . ' ' . $wallet['coin_symbol'] . ' @ $' . number_format($fiatRate, 2);

$stmt = $db->prepare("
    INSERT INTO transactions (
        user_id, transaction_type, amount, description, 
        reference_number, status, created_at
    ) VALUES (?, 'credit', ?, ?, ?, 'pending', NOW())
");
$stmt->bind_param("idss", $user['id'], $fiatAmount, $description, $reference);
$stmt->execute();
$stmt->close();

// Get admin email - with multiple fallbacks
$adminEmail = '';
try {
    if (function_exists('get_option')) {
        $adminEmail = get_option('admin_notify_email', '');
    }
} catch (Exception $e) {
    $adminEmail = '';
}

// If no admin email in options, try to get from users table
if (empty($adminEmail)) {
    // Check what columns exist in users table first
    $columnsResult = $db->query("SHOW COLUMNS FROM users");
    $userColumns = [];
    if ($columnsResult) {
        while ($col = $columnsResult->fetch_assoc()) {
            $userColumns[] = $col['Field'];
        }
    }
    
    // Build query based on available columns
    $whereConditions = [];
    if (in_array('role', $userColumns)) {
        $whereConditions[] = "role = 'admin'";
    }
    if (in_array('is_admin', $userColumns)) {
        $whereConditions[] = "is_admin = 1";
    }
    if (in_array('user_type', $userColumns)) {
        $whereConditions[] = "user_type = 'admin'";
    }
    if (in_array('type', $userColumns)) {
        $whereConditions[] = "type = 'admin'";
    }
    
    if (!empty($whereConditions)) {
        $query = "SELECT email FROM users WHERE " . implode(' OR ', $whereConditions) . " LIMIT 1";
        $adminResult = $db->query($query);
        if ($adminResult && $adminResult->num_rows > 0) {
            $adminRow = $adminResult->fetch_assoc();
            $adminEmail = $adminRow['email'] ?? '';
        }
    }
}

// Default fallback email
if (empty($adminEmail)) {
    $adminEmail = 'admin@' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
}

// Send admin notification using sendMail() from functions.php
if (!empty($adminEmail) && filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
    $subject = '🔔 New Crypto Deposit Request - ' . $reference;
    
    $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
            <h2 style='color: #dc2626;'>New Crypto Deposit Request</h2>
            <table style='width: 100%; border-collapse: collapse;'>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>User:</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee;'>" . htmlspecialchars($user['name'] ?? 'Unknown') . " (" . htmlspecialchars($user['email'] ?? '') . ")</td></tr>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>Reference:</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee;'><code>" . htmlspecialchars($reference) . "</code></td></tr>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>Coin:</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee;'>" . htmlspecialchars($wallet['coin_name']) . " (" . htmlspecialchars($wallet['coin_symbol']) . ")</td></tr>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>Network:</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee;'>" . htmlspecialchars($wallet['network'] ?? 'Mainnet') . "</td></tr>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>Amount (USD):</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee; color: #059669; font-weight: bold;'>$" . number_format($fiatAmount, 2) . "</td></tr>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>Crypto Amount:</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee;'><code>" . number_format($cryptoAmount, 8) . " " . htmlspecialchars($wallet['coin_symbol']) . "</code></td></tr>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>Rate Used:</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee;'>$" . number_format($fiatRate, 2) . " per " . htmlspecialchars($wallet['coin_symbol']) . "</td></tr>
                <tr><td style='padding: 8px; border-bottom: 1px solid #eee;'><strong>Wallet Address:</strong></td><td style='padding: 8px; border-bottom: 1px solid #eee;'><code>" . htmlspecialchars($walletAddress) . "</code></td></tr>
                <tr><td style='padding: 8px;'><strong>Status:</strong></td><td style='padding: 8px;'><span style='background: #fef3c7; color: #92400e; padding: 4px 12px; border-radius: 50px; font-size: 12px; font-weight: bold;'>PENDING</span></td></tr>
            </table>
            <p style='margin-top: 20px; font-size: 12px; color: #666;'>Time: " . date('Y-m-d H:i:s') . "</p>
        </div>
    ";
    
    sendMail($adminEmail, $subject, $body, $adminEmail);
}

// Send user notification using sendMail() from functions.php
$userEmail = $user['email'] ?? '';
if (!empty($userEmail) && filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
    $userSubject = '✅ Deposit Request Received - ' . $reference;
    $userBody = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
            <h2 style='color: #059669;'>Your Deposit Request Has Been Received</h2>
            <p>Hi " . htmlspecialchars($user['name'] ?? 'User') . ",</p>
            <p>We've received your crypto deposit request. Please send the exact amount shown below:</p>
            
            <div style='background: #f0fdf4; border: 2px solid #059669; border-radius: 12px; padding: 24px; margin: 20px 0; text-align: center;'>
                <div style='font-size: 14px; color: #666; margin-bottom: 8px;'>SEND EXACTLY</div>
                <div style='font-size: 32px; font-weight: 800; color: #059669; font-family: monospace;'>" . number_format($cryptoAmount, 8) . " " . htmlspecialchars($wallet['coin_symbol']) . "</div>
                <div style='font-size: 14px; color: #666; margin-top: 8px;'>≈ $" . number_format($fiatAmount, 2) . " USD</div>
            </div>
            
            <div style='background: #f3f4f6; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                <p><strong>Reference:</strong> <code>" . htmlspecialchars($reference) . "</code></p>
                <p><strong>Coin:</strong> " . htmlspecialchars($wallet['coin_name']) . "</p>
                <p><strong>Network:</strong> " . htmlspecialchars($wallet['network'] ?? 'Mainnet') . "</p>
                <p><strong>Deposit Address:</strong><br><code style='background: #fff; padding: 8px; display: block; margin-top: 8px; border-radius: 4px; word-break: break-all;'>" . htmlspecialchars($walletAddress) . "</code></p>
            </div>
            
            <p><strong>Next Steps:</strong></p>
            <ol>
                <li>Send exactly <strong>" . number_format($cryptoAmount, 8) . " " . htmlspecialchars($wallet['coin_symbol']) . "</strong> to the address above</li>
                <li>Wait for network confirmations (3-6 blocks)</li>
                <li>Your account will be credited automatically</li>
            </ol>
            
            <div style='background: #fef3c7; border-left: 4px solid #f59e0b; padding: 16px; margin: 20px 0; border-radius: 4px;'>
                <strong>⚠️ Important:</strong> Only send " . htmlspecialchars($wallet['coin_symbol']) . " on the " . htmlspecialchars($wallet['network'] ?? 'Mainnet') . " network. Sending other coins or using wrong networks will result in permanent loss.
            </div>
            
            <p style='font-size: 12px; color: #666; margin-top: 20px;'>This is an automated message. Please do not reply to this email.</p>
        </div>
    ";
    
    sendMail($userEmail, $userSubject, $userBody, $user['name'] ?? 'User');
}

setFlash('Deposit request submitted! Check your email for instructions. Reference: ' . $reference, 'success');
header('Location: crypto-deposit.php');
exit;
