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

// Initialize variables
$username = "";
$number = "";

// Check if 'add' button was clicked
if (isset($_POST['add'])) {
    // Get the form data
    $username = $_POST['username'];
    $number = $_POST['number'];
    $tele_groups = $_POST['tele_group'];
    $group_urls = $_POST['group_url'];
    $currentDateTime = date('Y-m-d H:i:s');
    
    // Loop through the data and insert or update it in the database
    for ($i = 0; $i < count($tele_groups); $i++) {
        $tele_group = $tele_groups[$i];
        $group_url = $group_urls[$i];

        // Check if a record already exists with the same username, number, tele_group, and group_url
        $checkQuery = "SELECT * FROM telegram_group WHERE username = '$username' AND number = '$number' AND tele_group = '$tele_group' AND group_url = '$group_url'";
        $checkResult = $conn->query($checkQuery);

        if ($checkResult->num_rows > 0) {
            // If a record exists, update its group_url
            $updateQuery = "UPDATE telegram_group SET group_url = '$group_url' WHERE username = '$username' AND number = '$number' AND tele_group = '$tele_group' AND group_url = '$group_url'";
            if ($conn->query($updateQuery) !== TRUE) {
                echo "Error updating record: " . $conn->error;
            }
        } else {
            // If no record exists, insert a new record
            $insertQuery = "INSERT INTO telegram_group (username, number, tele_group, group_url, date_time) VALUES ('$username', '$number', '$tele_group', '$group_url', '$currentDateTime')";
            if ($conn->query($insertQuery) !== TRUE) {
                echo "Error inserting record: " . $conn->error;
            }
        }
    }

    // Close the database connection
    $conn->close();

    // Redirect back to the page with a success message
    header("Location: add_telegram.php?success=Data%20Updated%20Successfully!");
    exit();
}

// The rest of your HTML and modal code goes here
?>
