<?php
// Include database connection file
//ish waale se update kaam kar raha but same name ka channel insert nhi ho raha 
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_channels = $_POST['tele_channel'];
    $channel_urls = $_POST['channel_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_channels); $i++) {
        $tele_channel = $tele_channels[$i];
        $channel_url = $channel_urls[$i];

        // Check if a record already exists with the same username, number, tele_channel, and channel_url
        $checkQuery = "SELECT * FROM telegram_channel WHERE username = '$username' AND number = '$number' AND tele_channel = '$tele_channel'";
        $checkResult = $conn->query($checkQuery);
        
        if ($checkResult->num_rows > 0) {
            $existingRow = $checkResult->fetch_assoc();
            if ($existingRow['channel_url'] != $channel_url) {
                // If the channel_url is different, update it
                $updateQuery = "UPDATE telegram_channel SET channel_url = '$channel_url' WHERE username = '$username' AND number = '$number' AND tele_channel = '$tele_channel'";
                if ($conn->query($updateQuery) !== TRUE) {
                    echo "Error updating record: " . $conn->error;
                }
            }
        } else {
            // If no record exists, insert a new record
            $insertQuery = "INSERT INTO telegram_channel (username, number, tele_channel, channel_url, date_time) VALUES ('$username', '$number', '$tele_channel', '$channel_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
?>
