<?php
session_name("admin_session");
session_start();
include("connection.php");

if (isset($_POST['submit'])) {
    $upi_type = $_POST['upi_type'];

    $upi_qr = $_FILES['upi_qr']['name'];
    $upi_qr_temp = $_FILES['upi_qr']['tmp_name'];
    $upi_qr_destination = 'img/' . $upi_qr;
    
    $currentDateTime = date('Y-m-d H:i:s');
    $added_by = $_SESSION['username'];

    // Check if the combination of bank_name and added_by already exists in the database
    $checkQuery = "SELECT COUNT(*) AS count FROM upi_payment WHERE upi_type = '$upi_type' AND added_by = '$added_by'";
    $result = mysqli_query($conn, $checkQuery);

    if ($result) {
        $row = mysqli_fetch_assoc($result);
        $count = $row['count'];

        if ($count > 0) {
            header("Location: upi_payment.php?msg=3"); // Bank name already exists for the current user
            exit;
        } else {
            // Perform the insert query using prepared statements
            $insertQuery = "INSERT INTO upi_payment (added_by, upi_type, upi_qr, date_time) VALUES ('$added_by', '$upi_type','$upi_qr', '$currentDateTime')";
            $res = mysqli_query($conn, $insertQuery);

            if ($res) {
                move_uploaded_file($upi_qr_temp, $upi_qr_destination);
                header("Location: upi_payment.php?msg=1"); // Inserted successfully
                exit;
            } else {
                header("Location: upi_payment.php?msg=2"); // Failed to insert
                exit;
            }
        }
    } else {
        header("Location: upi_payment.php?msg=2"); // Database error
        exit;
    }
}
?>
