<?php
// Include database connection
include('db_connection.php');

// Retrieve the form data
$planId = $_POST['plan_id'] ?? null;
$planTitle = $_POST['plan_title'] ?? 'N/A';
$minAmount = $_POST['min_amount'] ?? 0;
$maxAmount = $_POST['max_amount'] ?? 0;
$roi = $_POST['roi'] ?? 'N/A';
$duration = $_POST['duration'] ?? 'N/A';
$depositAmount = $_POST['depositAmount'] ?? 0;
$userid = $_POST['userid'];// Example: Get the logged-in user's ID from your session or authentication system

// Ensure deposit amount is within the valid range
if ($depositAmount < $minAmount || $depositAmount > $maxAmount) {
    echo "Error: Deposit amount must be between $".number_format($minAmount, 2)." and $".number_format($maxAmount, 2).".";
    exit;
}

// Process the file upload
if (isset($_FILES['paymentProof']) && $_FILES['paymentProof']['error'] == 0) {
    $fileTmpPath = $_FILES['paymentProof']['tmp_name'];
    $fileName = $_FILES['paymentProof']['name'];
    $fileSize = $_FILES['paymentProof']['size'];
    $fileType = $_FILES['paymentProof']['type'];
    
    // Define the allowed file types and max file size (adjust as needed)
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    $maxFileSize = 5 * 1024 * 1024; // 5 MB

    // Validate the file type and size
    if (!in_array($fileType, $allowedTypes)) {
        echo "Error: Only JPG, PNG, and PDF files are allowed.";
        exit;
    }
    if ($fileSize > $maxFileSize) {
        echo "Error: The file size exceeds the maximum allowed size of 5 MB.";
        exit;
    }

    // Create a unique name for the file to prevent overwriting
    $fileName = time() . '_' . $fileName;
    $uploadDir = 'uploads/';
    $destFilePath = $uploadDir . $fileName;

    // Move the uploaded file to the destination folder
    if (move_uploaded_file($fileTmpPath, $destFilePath)) {
        echo "Proof of payment has been uploaded successfully.";
    } else {
        echo "Error: Unable to upload the proof of payment. Please try again.";
        exit;
    }
} else {
    echo "Error: No file uploaded or there was an upload error.";
    exit;
}

// Insert deposit into the database
$stmt = $conn->prepare("INSERT INTO depositt (userid, plan_id, amount, proof_of_payment, status, roi, duration) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $userId, $planId, $depositAmount, $destFilePath, $status = 'pending', $roi, $duration);

// Execute the query
if ($stmt->execute()) {
    echo "Deposit of $".number_format($depositAmount, 2)." has been successfully submitted for the plan: ".$planTitle.". Please wait for confirmation.";
} else {
    echo "Error: Unable to process the deposit. Please try again later.";
}

// Close the database connection
$stmt->close();
$conn->close();
?>
