<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "db.php"; 
include "commen.php";
$message = '';
$message_class = '';

// Initialize variables
$first_name = '';
$last_name = '';
$username = '';
$phonenumber = '';
$chat_id = '';
$edit_id = '';

// Check if edit_id is provided for editing
if (isset($_REQUEST['edit_id']) && $_REQUEST['edit_id'] != '') {
    $edit_id = $_REQUEST['edit_id'];

    // Fetch the current user data for editing
    $edit_query = "SELECT * FROM telegram_users WHERE id = ?";
    $stmt = $conn->prepare($edit_query);
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $edit_data = $result->fetch_assoc();
        $first_name = $edit_data['first_name'];
        $last_name = $edit_data['last_name'];
        $username = $edit_data['username'];
        $phonenumber = $edit_data['phonenumber'];
        $chat_id = $edit_data['chat_id'];
    } else {
        $message = "User not found!";
        $message_class = "alert-danger";
    }
}

if (isset($_POST['submit_user']) && $_POST['submit_user'] != '') {
    // Sanitize user input
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $username = trim($_POST['username']);
    $phonenumber = trim($_POST['phonenumber']);
    $chat_id = trim($_POST['chat_id']);

    // Validate input
    // Regex pattern for validating global phone numbers
    $phone_pattern = '/^\+?[0-9]{7,20}$/'; // + optional, 7 to 20 digits allowed

    if ((!empty($username) || !empty($phonenumber)) && 
        (empty($phonenumber) || preg_match($phone_pattern, $phonenumber))) {
        if ($edit_id) {
            // Update user data
            $update_query = "UPDATE telegram_users SET phonenumber = ? ,first_name = ? , last_name = ? , username = ?, chat_id = ? WHERE id = ?";
            $stmt = $conn->prepare($update_query);
            $stmt->bind_param("ssssii", $phonenumber,$first_name,$last_name,$username,$chat_id, $edit_id);

            if ($stmt->execute()) {
                $message = "User updated successfully!";
                $message_class = "alert-success";
            } else {
                $message = "Error updating user: " . $stmt->error;
                $message_class = "alert-danger";
            }
        } else {
            // Check if the user already exists
            $check_query = "SELECT * FROM telegram_users WHERE username = ?";
            $stmt = $conn->prepare($check_query);
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $message = "User already exists!";
                $message_class = "alert-warning";
            } else {
                // Insert new user
                $sql = "INSERT INTO telegram_users (first_name, last_name, username, phonenumber, chat_id) VALUES (?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($sql);

                if ($stmt) {
                    $stmt->bind_param("ssssi", $first_name, $last_name, $username, $phonenumber, $chat_id);
                    if ($stmt->execute()) {
                        $message = "User added successfully!";
                        $message_class = "alert-success";
                    } else {
                        $message = "Error: " . $stmt->error;
                        $message_class = "alert-danger";
                    }
                } else {
                    $message = "Error preparing the statement.";
                    $message_class = "alert-danger";
                }
            }
        }
    } else {
        $message = "Please provide a valid phone number (7-20 digits with optional +).";
        $message_class = "alert-warning";
    }
}
?>

<div class="content" id="dynamic-content">
    <h2><?php echo $edit_id ? 'Edit User' : 'Add New User'; ?></h2>
    <p class='alert <?php echo $message_class; ?>'><?php echo $message; ?></p>
    <form method="POST" action="">
        <div class="mb-3">
            <label for="firstname" class="form-label">Firstname</label>
            <input type="text" name="first_name" class="form-control" id="first_name" value="<?php echo htmlspecialchars($first_name ?? ''); ?>"   />
        </div>
        <div class="mb-3">
            <label for="lastname" class="form-label">Lastname</label>
            <input type="text" name="last_name" class="form-control" id="last_name" value="<?php echo htmlspecialchars($last_name ?? ''); ?>"  />
        </div>
        <div class="mb-3">
            <label for="username" class="form-label">UserName</label>
            <input type="text" name="username" class="form-control" id="username" value="<?php echo htmlspecialchars($username ?? ''); ?>" />
        </div>
        <div class="mb-3">
            <label for="phonenumber" class="form-label">Phone Number</label>
            
            <input type="text" name="phonenumber" class="form-control" id="phonenumber" placeholder="+1 123 456 7890" / value="<?php echo htmlspecialchars($phonenumber ?? ''); ?>" />
        </div>
        <div class="mb-3">
            <label for="chat_id" class="form-label">Chat ID</label>
            <input type="text" name="chat_id" class="form-control" id="chat_id" value="<?php echo htmlspecialchars($chat_id ?? ''); ?>">
        </div>
        <button type="submit" name="submit_user" value="submit" class="btn btn-primary"><?php echo $edit_id ? 'Update' : 'Submit'; ?></button>
    </form>
</div>