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

// Check if the user is logged in
if (!isset($_SESSION['userid'])) {
    header("Location: ./login.php");
    exit();
}

// Retrieve the userid from the session
$userid = $_SESSION['userid'];

// Get the posted data
$product_id = $_POST['product_id'] ?? null;
$amount = $_POST['amount'] ?? null;
$full_name = $_POST['full_name'] ?? null;
$phone_number = $_POST['phone_number'] ?? null;
$wallet_type = $_POST['wallet_type'] ?? null;
$wallet_address = $_POST['wallet_address_input'] ?? null;
$proof_of_payment = $_FILES['proof_of_payment'] ?? null;

// Generate a unique deposit_id
$deposit_id = uniqid('deposit_', true); // Generates a unique ID prefixed with "deposit_"

// Validate required fields
if (!$product_id || !$amount || !$full_name || !$phone_number || !$wallet_type || !$wallet_address || !$proof_of_payment) {
    echo "Error: All fields are required.";
    exit();
}

// Check user account_balance
$query = "SELECT account_balance FROM user_login WHERE id = ?";
if ($stmt = $conn->prepare($query)) {
    $stmt->bind_param("s", $userid);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $current_account_balance = $row['account_balance'];

        // Ensure sufficient account_balance
        if ($current_account_balance < $amount) {
            echo "Error: Insufficient account_balance.";
            exit();
        }

        // Deduct amount from account_balance
        $new_account_balance = $current_account_balance - $amount;
        $update_query = "UPDATE user_login SET account_balance = ? WHERE id = ?";
        if ($update_stmt = $conn->prepare($update_query)) {
            $update_stmt->bind_param("ds", $new_account_balance, $userid);
            if (!$update_stmt->execute()) {
                echo "Error updating account_balance: " . $update_stmt->error;
                exit();
            }
        } else {
            echo "Error preparing account_balance update query: " . $conn->error;
            exit();
        }
    } else {
        echo "Error: User not found.";
        exit();
    }
} else {
    echo "Error preparing account_balance query: " . $conn->error;
    exit();
}

// Process the uploaded proof of payment
$target_dir = "uploads/";
$target_file = $target_dir . basename($proof_of_payment["name"]);
$uploadOk = 1;

// Check if the file is an actual image
if (isset($_POST["submit"])) {
    $check = getimagesize($proof_of_payment["tmp_name"]);
    if ($check === false) {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check file size (e.g., limit to 2MB)
if ($proof_of_payment["size"] > 2000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow any image file format
$imageMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
$fileMimeType = mime_content_type($proof_of_payment["tmp_name"]);

if (!in_array($fileMimeType, $imageMimeTypes)) {
    echo "Sorry, only image files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    exit();
// If everything is ok, try to upload the file
} else {
    if (move_uploaded_file($proof_of_payment["tmp_name"], $target_file)) {
        // File uploaded successfully, now save payment information in the database
        $query = "INSERT INTO payments (product_id, userid, deposit_id, amount, full_name, phone_number, wallet_type, wallet_address, proof_of_payment) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        if ($stmt = $conn->prepare($query)) {
            // Bind parameters including deposit_id
            $stmt->bind_param("sssssssss", $product_id, $userid, $deposit_id, $amount, $full_name, $phone_number, $wallet_type, $wallet_address, $target_file);
            if ($stmt->execute()) {
                // Redirect or show success message
                header("Location: advertisement_deposit.php?product_id=$product_id&status=success");
                exit();
            } else {
                echo "Error executing the query: " . $stmt->error;
            }
        } else {
            echo "Error preparing the query: " . $conn->error;
        }
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

$conn->close();
?>
