<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include_once('_db.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    try {
        // Check if user ID is present
        if (!isset($_POST['userid'])) {
            throw new Exception("User ID not found in form data.");
        }

        // Fetch user ID from form data
        $userid = $_POST['userid'];

        // Retrieve and validate form data
        $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
        $wallet_type = filter_var($_POST['wallet_type'], FILTER_SANITIZE_STRING);
        $wallet_address_input = filter_var($_POST['wallet_address_input'], FILTER_SANITIZE_STRING);

        // Check if wallet address is empty
        if (empty($wallet_address_input)) {
            throw new Exception("Wallet address input is empty.");
        }

        // Debugging - Check if the file is properly set
        if (!isset($_FILES['proof_of_payment'])) {
            throw new Exception("Proof of payment field is not set in the form.");
        }

        // Check if the file was uploaded without errors
        if ($_FILES['proof_of_payment']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception("Error uploading proof of payment. Error code: " . $_FILES['proof_of_payment']['error']);
        }

        // Handle file upload
        $proofOfPayment = $_FILES['proof_of_payment'];
        $targetDir = "uploads/";
        $targetFile = $targetDir . basename($proofOfPayment["name"]);
        if (!move_uploaded_file($proofOfPayment["tmp_name"], $targetFile)) {
            throw new Exception("Failed to move uploaded file.");
        }

        // Insert deposit details into the database
        $deposit_id = md5(uniqid());
        $stmt = $conn->prepare("INSERT INTO deposit (userid, deposit_id, amount, wallet_type, proof_of_payment, wallet_address_input) VALUES (?, ?, ?, ?, ?, ?)");
        if ($stmt === false) {
            throw new Exception("Failed to prepare statement: " . $conn->error);
        }

        // Bind parameters correctly
        $stmt->bind_param("ssssss", $userid, $deposit_id, $amount, $wallet_type, $targetFile, $wallet_address_input);
        $stmt->execute();

        // Check for successful insertion
        if ($stmt->affected_rows > 0) {
            header("Location: deposit.php?status=success");
            exit();
        } else {
            header("Location: deposit.php?status=error");
            exit();
        }
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}
?>
