<?php
session_name("admin_session");
session_start();

include("connection.php");

if (isset($_POST['submit'])) {
    $holder_name = $_POST['holder_name'];
    $bank_name = $_POST['bank_name'];
    $account_number = $_POST['account_number'];
    $ifsc_code = $_POST['ifsc_code'];
    $payment_type = $_POST['payment_type'];
    
    $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 bank_details WHERE bank_name = '$bank_name' 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: bank_details.php?msg=3"); // Bank name already exists for the current user
            exit;
        } else {
            // Perform the insert query using prepared statements
            $insertQuery = "INSERT INTO bank_details (added_by, payment_type, holder_name, bank_name, account_number, ifsc_code, date_time) VALUES ('$added_by', '$payment_type', '$holder_name', '$bank_name', '$account_number', '$ifsc_code', '$currentDateTime')";
            $res = mysqli_query($conn, $insertQuery);

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