<?php
session_name("admin_session");
session_start();
// Include database connection file
include("connection.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $name = $_POST['name'];
    $address = $_POST['address'];
    $number = $_POST['number'];
    $added_by=$_SESSION['username'];
    $currentDateTime = date('Y-m-d H:i:s'); // Get current date and time

    // Prepare the select query to check for any similar contact
    $select_query = "SELECT * FROM add_contact WHERE (name = '$name' AND number = '$number') OR (address = '$address' AND number = '$number') OR (name = '$name' AND address = '$address')";
    $select_result = mysqli_query($conn, $select_query);

    if (mysqli_num_rows($select_result) == 0) {
        // No similar contact found, proceed to insert the new contact
        $insert_query = "INSERT INTO add_contact (name, address, number, added_by,datetime) VALUES ('$name', '$address', '$number', '$added_by','$currentDateTime')";
        $insert_result = mysqli_query($conn, $insert_query);

        if ($insert_result) {
            // Contact added successfully
            header("Location: contact-add.php?success=Contact%20Added%20Successfully!");
            exit();
        } else {
            // Error occurred while adding contact
            header("Location: contact-add.php?error=Failed%20to%20Insert%20Contact!!!");
            exit();
        }
    } else {
        // A similar contact already exists, display a SweetAlert error message
        header("Location: contact-add.php?error=Contact%20Already%20Exists");
        exit();
    }
}
?>