<?php
session_start();
include 'session.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(['success' => false, 'message' => 'Invalid request method']));
}

// Validate required fields
$required = ['deposit_amount', 'transaction_hash'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        die(json_encode(['success' => false, 'message' => "Missing required field: $field"]));
    }
}

// Validate amount
$amount = floatval($_POST['deposit_amount']);
if ($amount < 10) {
    die(json_encode(['success' => false, 'message' => 'Minimum deposit amount is $10.00']));
}

// Validate transaction hash
$transaction_hash = trim($_POST['transaction_hash']);
if (strlen($transaction_hash) < 10) {
    die(json_encode(['success' => false, 'message' => 'Invalid transaction hash']));
}

// Get user details for notification
$userQuery = mysqli_query($conn, "SELECT first_name, last_name, email, fund_balance FROM users WHERE id='$user_id'");
$userData = mysqli_fetch_assoc($userQuery);
$first_name = $userData['first_name'];
$email = $userData['email'];
$current_balance = floatval($userData['fund_balance']);
$new_balance = $current_balance + $amount;

// Get IP address for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];

// Check for duplicate transaction hash
$check_sql = "SELECT id FROM deposits WHERE transaction_hash = '$transaction_hash' AND user_id = '$user_id'";
$check_result = mysqli_query($conn, $check_sql);
if (mysqli_num_rows($check_result) > 0) {
    die(json_encode(['success' => false, 'message' => 'This transaction has already been submitted']));
}

// Handle file upload
$receipt_path = '';
if (isset($_FILES['receipt']) && $_FILES['receipt']['error'] === UPLOAD_ERR_OK) {
    $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
    $max_size = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($_FILES['receipt']['type'], $allowed_types)) {
        die(json_encode(['success' => false, 'message' => 'Invalid file type. Only JPG, PNG, and PDF are allowed']));
    }
    
    if ($_FILES['receipt']['size'] > $max_size) {
        die(json_encode(['success' => false, 'message' => 'File size too large. Maximum 5MB']));
    }
    
    // Create uploads directory if it doesn't exist
    $upload_dir = 'uploads/deposits/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Generate unique filename
    $extension = pathinfo($_FILES['receipt']['name'], PATHINFO_EXTENSION);
    $filename = 'deposit_' . $user_id . '_' . time() . '_' . bin2hex(random_bytes(5)) . '.' . $extension;
    $receipt_path = $upload_dir . $filename;
    
    if (!move_uploaded_file($_FILES['receipt']['tmp_name'], $receipt_path)) {
        die(json_encode(['success' => false, 'message' => 'Failed to upload receipt']));
    }
} else {
    die(json_encode(['success' => false, 'message' => 'Receipt file is required']));
}

// Get note if provided
$note = mysqli_real_escape_string($conn, $_POST['note'] ?: '');

// Insert deposit record
$insert_sql = "INSERT INTO deposits (user_id, amount, transaction_hash, receipt_path, note, status, created_at) 
               VALUES ('$user_id', '$amount', '$transaction_hash', '$receipt_path', '$note', 'pending', NOW())";

if (mysqli_query($conn, $insert_sql)) {
    $deposit_id = mysqli_insert_id($conn);
    
    // Create transaction record
    $transaction_sql = "INSERT INTO transactions (user_id, type, amount, description, status, currency, created_at) 
                       VALUES ('$user_id', 'deposit', '$amount', 'USDT Deposit (Pending)', 'pending', 'USDT', NOW())";
    mysqli_query($conn, $transaction_sql);
    
    // Generate deposit reference number
    $deposit_ref = 'DEP-' . date('Ymd') . '-' . str_pad($deposit_id, 6, '0', STR_PAD_LEFT);
    
    // Update deposit with reference number
    mysqli_query($conn, "UPDATE deposits SET deposit_ref = '$deposit_ref' WHERE id = '$deposit_id'");
    
    // NOTIFICATION: Deposit Submitted Successfully (USER)
    $mail_subject = "Deposit Submitted - " . $deposit_ref;
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                        
                        <p class='message'>
                            ✅ <strong>Your deposit has been submitted successfully!</strong><br>
                            Our team will verify and process your deposit within 1-2 hours.
                        </p>

                        <!-- Deposit Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Deposit Reference:</strong> <span style='color: #2F2CD8; font-weight: bold;'>" . $deposit_ref . "</span><br>
                                <strong>Amount:</strong> $" . number_format($amount, 2) . " USDT<br>
                                <strong>Transaction Hash:</strong> <span style='font-family: monospace;'>" . substr($transaction_hash, 0, 20) . "..." . substr($transaction_hash, -20) . "</span><br>
                                <strong>Status:</strong> <span style='color: #ffc107; font-weight: bold;'>Pending Verification</span><br>
                                <strong>Submitted Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Current Balance:</strong> $" . number_format($current_balance, 2) . "<br>
                                <strong>Expected New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                <strong>IP Address:</strong> " . $user_ip . "
                            </div>
                        </div>

                        <!-- Processing Information -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>⏰ Processing Timeline</h4>
                            <ul style='color: #0056b3;'>
                                <li><strong>1-15 minutes:</strong> Initial review and confirmation</li>
                                <li><strong>1-2 hours:</strong> Blockchain confirmation (usually 6-12 confirmations)</li>
                                <li><strong>2-4 hours:</strong> Manual verification by our team</li>
                                <li><strong>Immediately after:</strong> Funds credited to your account</li>
                            </ul>
                            <p style='color: #0056b3; margin-top: 10px;'>
                                <strong>Note:</strong> Processing times may vary during peak hours.
                            </p>
                        </div>

                        <!-- What Happens Next -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                            <p style='color: #6c757d;'>You'll receive email updates:</p>
                            <ul style='color: #6c757d;'>
                                <li>When your deposit is being processed</li>
                                <li>When blockchain confirmations are complete</li>
                                <li>When funds are successfully credited</li>
                                <li>If additional information is needed</li>
                            </ul>
                        </div>

                        <!-- Tracking Your Deposit -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>📊 Track Your Deposit</h4>
                            <p style='color: #856404;'>
                                <strong>Deposit Status Page:</strong> <a href='" . $myUrl . "/deposit-status.php?id=" . $deposit_id . "' style='color: #856404; text-decoration: underline;'>View Real-time Status</a><br>
                                <strong>Transaction on Blockchain:</strong> <a href='https://tronscan.org/#/transaction/" . $transaction_hash . "' style='color: #856404; text-decoration: underline;' target='_blank'>View on TronScan</a><br>
                                <strong>Support:</strong> <a href='" . $myUrl . "/support.php?ref=" . $deposit_ref . "' style='color: #856404; text-decoration: underline;'>Contact Support</a>
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/deposit-status.php?id=" . $deposit_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Track Deposit Status
                            </a>
                            <a href='" . $myUrl . "/transactions.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                View Transactions
                            </a>
                        </div>

                        <!-- Important Notes -->
                        <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0c5460;'>💡 Important Notes</h4>
                            <ul style='color: #0c5460;'>
                                <li>Keep your transaction hash for reference</li>
                                <li>Do not submit the same transaction multiple times</li>
                                <li>Funds will be available for trading immediately after verification</li>
                                <li>Contact support if not credited within 6 hours</li>
                            </ul>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Questions about your deposit?</p>
                            <a href='" . $myUrl . "/support.php?category=deposits' class='support-link'>Contact Deposit Support</a>
                        </div>
                    </div>";

    // Send user notification
    require_once("../proccess/mail_sender.php");

    // NOTIFICATION: New Deposit Submitted (ADMIN)
    $admin_mail_subject = "NEW DEPOSIT: $" . number_format($amount, 2) . " - " . $deposit_ref;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>💰 New Deposit Submitted</h2>
                            
                            <p class='message'>
                                A user has submitted a new deposit requiring verification.
                            </p>

                            <!-- Deposit Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Deposit Reference:</strong> " . $deposit_ref . "<br>
                                    <strong>Deposit ID:</strong> " . $deposit_id . "<br>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                    <strong>User Email:</strong> " . $email . "<br>
                                    <strong>Amount:</strong> <span style='color: #198754; font-weight: bold;'>$" . number_format($amount, 2) . " USDT</span><br>
                                    <strong>Transaction Hash:</strong> <br>
                                    <div style='background: #f8f9fa; padding: 10px; border-radius: 4px; font-family: monospace; word-break: break-all; margin: 5px 0;'>
                                        " . $transaction_hash . "
                                    </div>
                                    <strong>Status:</strong> <span style='color: #ffc107; font-weight: bold;'>Pending Verification</span><br>
                                    <strong>Submitted Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>User IP:</strong> " . $user_ip . "<br>
                                    <strong>User Current Balance:</strong> $" . number_format($current_balance, 2) . "<br>
                                    <strong>Expected New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                    <strong>Receipt File:</strong> " . basename($receipt_path) . "<br>
                                    <strong>Note:</strong> " . (empty($note) ? 'None' : htmlspecialchars($note)) . "
                                </div>
                            </div>

                            <!-- User Information -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>👤 User Profile</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Account Created:</strong> " . (isset($userData['created_at']) ? date('F j, Y', strtotime($userData['created_at'])) : 'N/A') . "<br>
                                    <strong>Total Deposits:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as total FROM deposits 
                                             WHERE user_id='$user_id' AND status='completed'"))['total'] ?? 0) . "<br>
                                    <strong>Total Deposit Amount:</strong> $" . 
                                        number_format(mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT SUM(amount) as total FROM deposits 
                                             WHERE user_id='$user_id' AND status='completed'"))['total'] ?? 0, 2) . "<br>
                                    <strong>Active Bots:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as total FROM user_bot_subscriptions 
                                             WHERE user_id='$user_id' AND status='active'"))['total'] ?? 0) . "<br>
                                    <strong>Verification Status:</strong> " . 
                                        (isset($userData['verified']) && $userData['verified'] == 1 ? 'Verified' : 'Not Verified') . "
                                </p>
                            </div>

                            <!-- Verification Checklist -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>✅ Verification Checklist</h4>
                                <ul style='color: #856404;'>
                                    <li>✅ Confirm transaction hash on blockchain explorer</li>
                                    <li>✅ Verify amount matches submitted amount</li>
                                    <li>✅ Check receipt/image for accuracy</li>
                                    <li>✅ Confirm funds received in wallet</li>
                                    <li>✅ Check for duplicate transactions</li>
                                    <li>✅ Verify user account status</li>
                                </ul>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/deposits.php?id=" . $deposit_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Verify Deposit
                                </a>
                                <a href='https://tronscan.org/#/transaction/" . $transaction_hash . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;' target='_blank'>
                                    View on TronScan
                                </a>
                                <a href='" . $myUrl . "/" . $receipt_path . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;' target='_blank'>
                                    View Receipt
                                </a>
                            </div>

                            <!-- Priority Information -->
                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #721c24;'>⏰ Priority Information</h4>
                                <p style='color: #721c24;'>
                                    <strong>Amount-Based Priority:</strong><br>
                                    • $" . number_format($amount, 2) . " - " . 
                                        ($amount >= 1000 ? 'HIGH PRIORITY (Process within 1 hour)' : 
                                         ($amount >= 500 ? 'MEDIUM PRIORITY (Process within 2 hours)' : 
                                         'STANDARD PRIORITY (Process within 4 hours)')) . "<br>
                                    <strong>Current Queue:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as pending FROM deposits WHERE status='pending'"))['pending'] ?? 0) . " pending deposits<br>
                                    <strong>Average Processing Time:</strong> 2.5 hours
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Deposit requires manual verification.</p>
                                <p class='support-text'>Please process within appropriate timeframe.</p>
                            </div>
                        </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    echo json_encode([
        'success' => true, 
        'message' => 'Deposit submitted successfully. Your funds will be credited after verification.'
    ]);
} else {
    // Clean up uploaded file if database insert fails
    if (file_exists($receipt_path)) {
        unlink($receipt_path);
    }
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
}
?>