<?php
require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';
require_once __DIR__ . '/PHPMailer/src/Exception.php';
require_once __DIR__ . '/config/config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
    exit;
}

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $usd_amount = $_POST['usdAmount'] ?? '';
    $crypto_amount = $_POST['cryptoAmount'] ?? '';
    $crypto_type = $_POST['cryptoType'] ?? '';
    $wallet_address = $_POST['wallet_address'] ?? '';
    $proofFile = $_FILES['proofFile'] ?? null;

    if (!$crypto_type || !$wallet_address || !$usd_amount || !$crypto_amount || !$proofFile || $proofFile['error'] !== 0) {
        echo json_encode(['success' => false, 'message' => 'All fields are required, and proof file must be valid.']);
        exit;
    }

    // Upload proof file
    // Keep receipt uploads inside this application, whether it is hosted at
    // a virtual host root or in a subdirectory such as /Octaltrade.
    $uploadDir = __DIR__ . '/uploads/proofs/';
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];

    if (!in_array($proofFile['type'], $allowedTypes)) {
        echo json_encode(['success' => false, 'message' => 'Invalid proof file type.']);
        exit;
    }

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $filename = uniqid('proof_') . '_' . basename($proofFile['name']);
    $targetFile = $uploadDir . $filename;

    if (!move_uploaded_file($proofFile['tmp_name'], $targetFile)) {
        echo json_encode(['success' => false, 'message' => 'Failed to upload file.']);
        exit;
    }

    // Save to database
    $stmt = $conn->prepare('INSERT INTO deposits (user_id, usd_amount, crypto_amount, crypto_type, wallet_address, proof_file) VALUES (?, ?, ?, ?, ?, ?)');
    if (!$stmt) {
        echo json_encode(["status" => "error", "message" => "SQL error: " . $conn->error]);
        exit;
    }

    $stmt->bind_param('isssss', $user_id, $usd_amount, $crypto_amount, $crypto_type, $wallet_address, $filename);

    if ($stmt->execute()) {
        $action = 'deposit';
        $actor = 'user';
        $formattedAmount = number_format($usd_amount, 2);
        $description = "You submitted a deposit request of \$$formattedAmount using $crypto_type. Awaiting approval. 💰";

        $logStmt = $conn->prepare("INSERT INTO activity_logs (user_id, actor, action_type, description) VALUES (?, ?, ?, ?)");
        if ($logStmt) {
            $logStmt->bind_param('isss', $user_id, $actor, $action, $description);
            $logStmt->execute();
            $logStmt->close();
        }

        // Send Email
        $mail = new PHPMailer(true);
        try {
            // SMTP Settings
            $mail->isSMTP();
            $mail->Host = 'mail.octaltrade.net'; // Replace with your SMTP server
            $mail->SMTPAuth = true;
            $mail->Username = 'support@octaltrade.net'; // Your email
            $mail->Password = 'f4LFSXaFM45ZfnU';     // Your password
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;

            // Sender & Recipient
            $mail->setFrom('support@octaltrade.net', 'OctalTrade Deposits');
            $mail->addAddress('prolificmk20@gmail.com');
            $mail->addAddress('Davehack227@gmail.com');

            // Email Content
            $mail->isHTML(true);
            $mail->Subject = "New Deposit Request from User #$user_id";

            $proofUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/uploads/proofs/' . $filename;

            $mail->Body = "
                <div style='font-family: Arial, sans-serif; padding: 20px; color: #333;'>
                    <h2 style='color: #0057ff;'>ðŸš€ New Deposit Request</h2>
                    <p><strong>User ID:</strong> #$user_id</p>
                    <p><strong>USD Amount:</strong> \$$usd_amount</p>
                    <p><strong>Crypto Amount:</strong> $crypto_amount $crypto_type</p>
                    <p><strong>Wallet Address:</strong> $wallet_address</p>
                    <p><strong>Proof of Payment:</strong> <a href='$proofUrl' target='_blank' style='color: #0057ff;'>Download File</a></p>
                    <hr style='margin: 20px 0;'>
                    <p style='font-size: 14px; color: #666;'>This deposit was submitted via the OctalTrade investment platform.</p>
                </div>
            ";

            $mail->send();
            echo json_encode(['success' => true, 'message' => 'Deposit submitted successfully.']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Database insert failed.']);
    }

    $stmt->close();
    $conn->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
