<?php
/**
 * Ultimate Sync Bot (Feature: Edit-to-Delete)
 * Architect: Hamid Mokarami
 * Version: 7.6
 */

ini_set('display_errors', 1);
error_reporting(E_ALL);

// ====================================================
// 1. CONFIGURATION
// ====================================================

define('TG_TOKEN', '8009685219:AAHQgFP6g9U-r498ZFDvUfDDfV4ibV_BhPI'); // توکن ربات تلگرام
define('BALE_TOKEN', '1328108468:hixrUhgTUq82uuwgMW2IGICvCpwHemVg4lk');   // توکن ربات بل
define('EITAA_TOKEN', 'TOKEN_EITAA_SHOMA'); 

// کلمه‌ای که اگر پیام به آن تغییر کرد، حذف شود (مثلا خط تیره یا del)
define('DELETE_TRIGGER', '-'); 

define('ADMIN_IDS', [
    'telegram' => [239053159],
    'bale'     => [1589915724],
    'eitaa'    => [0] 
]);

define('TG_PROXY', ''); 
define('LOG_FILE', __DIR__ . '/debug_log.txt');
define('DB_FILE', __DIR__ . '/database.sqlite');
define('SUPPORTED_MEDIA', ['photo', 'video', 'voice', 'audio', 'document', 'animation', 'sticker']);

// ====================================================
// 2. DATABASE
// ====================================================

class DB {
    private $pdo;
    public function __construct() {
        try {
            $this->pdo = new PDO("sqlite:" . DB_FILE);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->initTables();
        } catch (PDOException $e) { die("DB Error: " . $e->getMessage()); }
    }

    private function initTables() {
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS channels (id INTEGER PRIMARY KEY AUTOINCREMENT, tg_id TEXT, bale_id TEXT, eitaa_id TEXT)");
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS message_map (id INTEGER PRIMARY KEY AUTOINCREMENT, origin_key TEXT, tg_msg_id TEXT, bale_msg_id TEXT, eitaa_msg_id TEXT, timestamp INTEGER)");
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)");
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS user_states (user_id TEXT PRIMARY KEY, step TEXT, data TEXT)");
    }

    public function addGroup($tg, $bale, $eitaa) { $this->pdo->prepare("INSERT INTO channels (tg_id, bale_id, eitaa_id) VALUES (?, ?, ?)")->execute([$tg, $bale, $eitaa]); }
    public function getGroups() { return $this->pdo->query("SELECT * FROM channels")->fetchAll(PDO::FETCH_ASSOC); }
    public function deleteGroup($id) { $this->pdo->prepare("DELETE FROM channels WHERE id = ?")->execute([$id]); }
    
    public function findRowByChatId($chatId, $platform) {
        $col = ($platform == 'telegram' ? 'tg_id' : ($platform == 'bale' ? 'bale_id' : 'eitaa_id'));
        $stmt = $this->pdo->prepare("SELECT * FROM channels WHERE $col = ?"); $stmt->execute([$chatId]); return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function saveMap($key, $tg, $bale, $eitaa) {
        $this->pdo->prepare("INSERT INTO message_map (origin_key, tg_msg_id, bale_msg_id, eitaa_msg_id, timestamp) VALUES (?, ?, ?, ?, ?)")->execute([$key, $tg, $bale, $eitaa, time()]);
    }

    public function getMap($plat, $chatId, $msgId) {
        $key = "{$plat}_{$chatId}_{$msgId}";
        $res = $this->pdo->prepare("SELECT * FROM message_map WHERE origin_key = ?"); $res->execute([$key]); 
        if ($row = $res->fetch(PDO::FETCH_ASSOC)) return $row;
        $col = ($plat == 'telegram' ? 'tg_msg_id' : ($plat == 'bale' ? 'bale_msg_id' : 'eitaa_msg_id'));
        $res = $this->pdo->prepare("SELECT * FROM message_map WHERE $col = ?"); $res->execute([$msgId]);
        return $res->fetch(PDO::FETCH_ASSOC);
    }
    
    // متد حذف از دیتابیس (اختیاری برای تمیزکاری)
    public function deleteMap($id) {
        $this->pdo->prepare("DELETE FROM message_map WHERE id = ?")->execute([$id]);
    }

    public function setSetting($k, $v) { $this->pdo->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")->execute([$k, $v]); }
    public function getSetting($k, $d=null) { $stmt = $this->pdo->prepare("SELECT value FROM settings WHERE key = ?"); $stmt->execute([$k]); return $stmt->fetchColumn() ?: $d; }
    public function setState($u, $s, $d=[]) { $this->pdo->prepare("INSERT OR REPLACE INTO user_states (user_id, step, data) VALUES (?, ?, ?)")->execute([$u, $s, json_encode($d)]); }
    public function getState($u) { $stmt = $this->pdo->prepare("SELECT * FROM user_states WHERE user_id = ?"); $stmt->execute([$u]); $r = $stmt->fetch(PDO::FETCH_ASSOC); return $r ? ['step'=>$r['step'], 'data'=>json_decode($r['data'], true)] : null; }
    public function clearState($u) { $this->pdo->prepare("DELETE FROM user_states WHERE user_id = ?")->execute([$u]); }
}

// ====================================================
// 3. CORE LOGIC
// ====================================================

class RobotCore {
    private $db;
    public function __construct() { $this->db = new DB(); }

    public function handle() {
        $update = json_decode(file_get_contents("php://input"), true);
        $source = $_GET['source'] ?? '';
        if (!$update) { echo "System V7.6 Online (Ghost Delete)."; return; }
        if (in_array($source, ['telegram', 'bale', 'eitaa'])) $this->processUpdate($update, $source);
    }

    private function processUpdate($update, $platform) {
        $msg = $update['message'] ?? $update['channel_post'] ?? $update['edited_channel_post'] ?? null;
        if (!$msg) return;

        $chatId = $msg['chat']['id'];
        $userId = $msg['from']['id'] ?? $chatId;
        $msgId = $msg['message_id'];
        $text = $msg['text'] ?? $msg['caption'] ?? '';
        $isEdit = isset($update['edited_channel_post']);

        // Admin
        if ($msg['chat']['type'] == 'private' && in_array($userId, ADMIN_IDS[$platform]??[])) {
            $this->adminPanel($userId, $chatId, $text, $msg, $platform); return;
        }

        // Channel Sync
        if ($msg['chat']['type'] == 'channel') {
            if ($isEdit) { 
                $this->handleEditSync($chatId, $msgId, $msg, $platform); 
                return; 
            }
            if (isset($msg['reply_to_message']) && $this->handleReplyCommands($msg, $text, $platform)) return;
            if (strpos($text, '#nosync') !== false) return;
            if (isset($msg['voice']) && $this->db->getSetting('voice_mode', 'default') == 'manual') return;

            $group = $this->db->findRowByChatId($chatId, $platform);
            if ($group) $this->syncToGroup($group, $msg, $platform);
        }
    }

    private function syncToGroup($group, $msg, $src) {
        $targets = [];
        if ($src != 'telegram' && $group['tg_id']) $targets['telegram'] = $group['tg_id'];
        if ($src != 'bale' && $group['bale_id']) $targets['bale'] = $group['bale_id'];
        if ($src != 'eitaa' && $group['eitaa_id']) $targets['eitaa'] = $group['eitaa_id'];

        $cleanText = str_ireplace(['#tgon', '#baleon', '#eitaaon', '#send'], '', $msg['text']??$msg['caption']??'');
        $originKey = "{$src}_{$msg['chat']['id']}_{$msg['message_id']}";
        $msgIds = [];

        foreach ($targets as $dest => $destChatId) {
            if ($this->shouldSkip($msg['text']??$msg['caption']??'', $dest)) continue;

            $replyToId = null;
            if (isset($msg['reply_to_message'])) {
                $mapRow = $this->db->getMap($src, $msg['chat']['id'], $msg['reply_to_message']['message_id']);
                if ($mapRow) $replyToId = $mapRow[($dest=='telegram'?'tg':$dest).'_msg_id'];
            }

            if (isset($msg['text'])) {
                $res = $this->sendText($destChatId, $cleanText, $dest, $replyToId);
            } else {
                $type = $this->detectType($msg);
                if ($type) $res = $this->transferFile($msg, $type, $destChatId, $src, $dest, $cleanText, $replyToId);
            }

            if (isset($res['result']['message_id'])) {
                $msgIds[$dest] = $res['result']['message_id'];
                $this->log("Sent to $dest ID: " . $res['result']['message_id']);
            } else {
                $this->log("Fail send to $dest", $res);
            }
        }

        $this->db->saveMap($originKey, 
            ($src=='telegram'?$msg['message_id']:($msgIds['telegram']??null)),
            ($src=='bale'?$msg['message_id']:($msgIds['bale']??null)),
            ($src=='eitaa'?$msg['message_id']:($msgIds['eitaa']??null))
        );
    }

    private function transferFile($msg, $type, $targetChatId, $from, $to, $caption, $replyToId) {
        $fileObj = ($type == 'photo') ? end($msg[$type]) : $msg[$type];
        $fileId = $fileObj['file_id'];
        $pathInfo = $this->apiCall('getFile', ['file_id'=>$fileId], $from);
        if (!isset($pathInfo['result']['file_path'])) return ['ok'=>false, 'desc'=>'No file path'];
        $remotePath = $pathInfo['result']['file_path'];

        $ext = pathinfo($remotePath, PATHINFO_EXTENSION);
        if (!$ext && $type == 'voice') $ext = 'ogg'; 
        if (!$ext && $type == 'photo') $ext = 'jpg';
        if (!$ext) $ext = 'tmp';

        $fileName = "file_" . time() . ".$ext";
        $temp = sys_get_temp_dir() . '/' . $fileName;
        
        $token = ($from=='telegram') ? TG_TOKEN : (($from=='bale') ? BALE_TOKEN : EITAA_TOKEN);
        $domain = ($from=='telegram') ? 'api.telegram.org' : (($from=='bale') ? 'tapi.bale.ai' : 'eitaa.com/api');
        $content = $this->curlDownload("https://$domain/file/bot$token/$remotePath", $from);
        if (!$content) return ['ok'=>false, 'desc'=>'Empty download'];
        file_put_contents($temp, $content);

        $methods = ['photo'=>'sendPhoto', 'video'=>'sendVideo', 'voice'=>'sendVoice', 'audio'=>'sendAudio', 'document'=>'sendDocument', 'animation'=>'sendAnimation', 'sticker'=>'sendSticker'];
        $method = $methods[$type];
        $cfile = new CURLFile($temp, mime_content_type($temp), $fileName);

        $data = ['chat_id' => $targetChatId, 'caption' => $caption, $type => $cfile];
        if ($replyToId) $data['reply_to_message_id'] = $replyToId;

        $res = $this->apiCall($method, $data, $to, true);
        @unlink($temp);
        return $res;
    }

    // --- FEATURE: GHOST DELETE (EDIT-TO-DELETE) ---
    private function handleEditSync($chatId, $msgId, $msg, $platform) {
        $text = trim($msg['text'] ?? $msg['caption'] ?? '');
        
        $map = $this->db->getMap($platform, $chatId, $msgId);
        if (!$map) return;

        // 1. چک کن آیا متن به "تریگر حذف" تبدیل شده؟ (مثلا -)
        if ($text === DELETE_TRIGGER) {
            $this->log("Ghost Delete Triggered on $platform ($msgId)");
            
            // پیدا کردن گروه برای بدست آوردن ChatID ها
            $group = $this->db->findRowByChatId($chatId, $platform);
            if (!$group) return;

            // حذف از همه جا (شامل خود مبدا)
            $platforms = ['telegram' => 'tg', 'bale' => 'bale', 'eitaa' => 'eitaa'];
            
            foreach ($platforms as $pName => $pColPrefix) {
                // آیدی پیام در این پلتفرم چیست؟
                $pMsgId = $map[$pColPrefix . '_msg_id']; // مثلا tg_msg_id
                $pChatId = $group[$pColPrefix . '_id']; // مثلا tg_id

                if ($pMsgId && $pChatId) {
                    $this->deleteMessage($pChatId, $pMsgId, $pName);
                    $this->log("Ghost Delete executed on $pName (Msg: $pMsgId)");
                }
            }
            
            // پاک کردن از دیتابیس مپ
            $this->db->deleteMap($map['id']);
            return; // عملیات تمام شد
        }

        // 2. اگر تریگر حذف نبود، عملیات ادیت معمولی را انجام بده
        $targets = [];
        if ($platform != 'telegram' && $map['tg_msg_id']) $targets['telegram'] = $map['tg_msg_id'];
        if ($platform != 'bale' && $map['bale_msg_id']) $targets['bale'] = $map['bale_msg_id'];
        if ($platform != 'eitaa' && $map['eitaa_msg_id']) $targets['eitaa'] = $map['eitaa_msg_id'];
        
        $group = $this->db->findRowByChatId($chatId, $platform);
        foreach ($targets as $p => $mid) {
            $col = ($p=='telegram'?'tg':$p).'_id';
            $tChatId = $group[$col];

            $res = $this->editMessageCaption($tChatId, $mid, $text, $p);
            if (!$res['ok']) {
                $this->editMessageText($tChatId, $mid, $text, $p);
            }
        }
    }

    private function handleReplyCommands($msg, $text, $platform) {
        $replyId = $msg['reply_to_message']['message_id'];
        $chatId = $msg['chat']['id'];

        if (stripos($text, '#send') !== false) {
            $group = $this->db->findRowByChatId($chatId, $platform);
            if ($group) {
                $this->syncToGroup($group, $msg['reply_to_message'], $platform);
                $this->sendText($chatId, "✅ Sync executed.", $platform, $msg['message_id']);
            }
            return true;
        }
        if (stripos($text, '#del') !== false) {
            $map = $this->db->getMap($platform, $chatId, $replyId);
            if ($map && $group = $this->db->findRowByChatId($chatId, $platform)) {
                if (stripos($text, '#del_bale') !== false) {
                    if ($map['bale_msg_id']) $this->deleteMessage($group['bale_id'], $map['bale_msg_id'], 'bale');
                } else {
                    if ($map['tg_msg_id'] && $platform!='telegram') $this->deleteMessage($group['tg_id'], $map['tg_msg_id'], 'telegram');
                    if ($map['bale_msg_id'] && $platform!='bale') $this->deleteMessage($group['bale_id'], $map['bale_msg_id'], 'bale');
                    if ($map['eitaa_msg_id'] && $platform!='eitaa') $this->deleteMessage($group['eitaa_id'], $map['eitaa_msg_id'], 'eitaa');
                }
                $this->sendText($chatId, "🗑 Deleted.", $platform, $msg['message_id']);
            }
            return true;
        }
        return false;
    }

    private function adminPanel($userId, $chatId, $text, $fullMsg, $p) {
        $state = $this->db->getState($userId);
        $step = $state['step'] ?? 'MAIN';

        if ($text == '🔙 بازگشت') { $this->db->clearState($userId); $this->menu($chatId, $p); return; }

        if ($step == 'MAIN') {
            if ($text == '⚙️ تنظیمات ویس') $this->sendKeyboard($chatId, "وضعیت: " . ($this->db->getSetting('voice_mode')=='manual'?'⛔ دستی':'✅ خودکار'), [['✅ حالت خودکار', '⛔ حالت دستی'], ['🔙 بازگشت']], $p);
            elseif ($text == '✅ حالت خودکار') { $this->db->setSetting('voice_mode', 'default'); $this->menu($chatId, $p, "✅ خودکار شد."); }
            elseif ($text == '⛔ حالت دستی') { $this->db->setSetting('voice_mode', 'manual'); $this->menu($chatId, $p, "⛔ دستی شد."); }
            elseif ($text == '➕ اتصال جدید') { $this->db->setState($userId, 'GET_TG'); $this->sendText($chatId, "آیدی تلگرام:", $p, null, true); }
            elseif ($text == '📋 لیست') {
                $out = ""; foreach($this->db->getGroups() as $g) $out .= "G: {$g['id']} | TG: {$g['tg_id']} | Bale: {$g['bale_id']}\n";
                $this->sendText($chatId, $out ?: "خالی", $p);
            }
            elseif ($text == '➖ حذف') { $this->db->setState($userId, 'DEL_ID'); $this->sendText($chatId, "آیدی گروه:", $p, null, true); }
            else $this->menu($chatId, $p);
        }
        elseif ($step == 'GET_TG') { $this->db->setState($userId, 'GET_BALE', ['tg'=>$text]); $this->sendText($chatId, "آیدی بله:", $p, null, true); }
        elseif ($step == 'GET_BALE') { $d=$state['data']; $d['bale']=$text; $this->db->setState($userId, 'GET_EITAA', $d); $this->sendText($chatId, "آیدی ایتا:", $p, null, true); }
        elseif ($step == 'GET_EITAA') { $d=$state['data']; $this->db->addGroup($d['tg'], $d['bale'], $text); $this->db->clearState($userId); $this->menu($chatId, $p, "✅ ذخیره شد."); }
        elseif ($step == 'DEL_ID') { $this->db->deleteGroup($text); $this->db->clearState($userId); $this->menu($chatId, $p, "حذف شد."); }
    }

    private function menu($c, $p, $t="منو:") { $this->sendKeyboard($c, $t, [['➕ اتصال جدید', '➖ حذف', '📋 لیست'], ['⚙️ تنظیمات ویس']], $p); }
    private function shouldSkip($t, $target) { return (strpos($t, '#tgon')!==false && $target!='telegram') || (strpos($t, '#baleon')!==false && $target!='bale') || (strpos($t, '#eitaaon')!==false && $target!='eitaa'); }
    private function detectType($m) { foreach(SUPPORTED_MEDIA as $t) if(isset($m[$t])) return $t; return null; }
    
    private function sendText($c, $t, $p, $r=null, $kb=false) { 
        $d=['chat_id'=>(is_numeric($c)?(int)$c:$c), 'text'=>$t]; 
        if($r) $d['reply_to_message_id']=(int)$r; 
        if($kb) $d['reply_markup']=json_encode(['keyboard'=>[['🔙 بازگشت']], 'resize_keyboard'=>true]); 
        return $this->apiCall('sendMessage', $d, $p); 
    }
    private function sendKeyboard($c, $t, $k, $p) { return $this->apiCall('sendMessage', ['chat_id'=>(is_numeric($c)?(int)$c:$c), 'text'=>$t, 'reply_markup'=>json_encode(['keyboard'=>$k, 'resize_keyboard'=>true])], $p); }
    private function editMessageText($c, $m, $t, $p) { return $this->apiCall('editMessageText', ['chat_id' => (is_numeric($c) ? (int)$c : $c), 'message_id' => (int)$m, 'text' => $t], $p); }
    private function editMessageCaption($c, $m, $t, $p) { return $this->apiCall('editMessageCaption', ['chat_id' => (is_numeric($c) ? (int)$c : $c), 'message_id' => (int)$m, 'caption' => $t], $p); }
    private function deleteMessage($c, $m, $p) { $this->apiCall('deleteMessage', ['chat_id' => (is_numeric($c) ? (int)$c : $c), 'message_id' => (int)$m], $p); }
    
    private function apiCall($m, $d, $p, $up=false) {
        if ($p == 'telegram') $u = "https://api.telegram.org/bot".TG_TOKEN;
        elseif ($p == 'bale') $u = "https://tapi.bale.ai/bot".BALE_TOKEN;
        elseif ($p == 'eitaa') $u = "https://eitaa.com/api/bot".EITAA_TOKEN;
        $ch = curl_init("$u/$m"); curl_setopt($ch, CURLOPT_POST, 1);
        if($up) curl_setopt($ch, CURLOPT_POSTFIELDS, $d); else { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($d)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if($p=='telegram'&&TG_PROXY) curl_setopt($ch, CURLOPT_PROXY, TG_PROXY);
        $r = curl_exec($ch); curl_close($ch); return json_decode($r, true);
    }
    private function curlDownload($u, $s) { $ch=curl_init($u); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); if($s=='telegram'&&TG_PROXY) curl_setopt($ch, CURLOPT_PROXY, TG_PROXY); $d=curl_exec($ch); curl_close($ch); return $d; }
    private function log($t, $d=null) { file_put_contents(LOG_FILE, date("[H:i:s] ").$t.($d?" | ".json_encode($d):"")."\n", FILE_APPEND); }
}

try { $bot = new RobotCore(); $bot->handle(); } catch(Exception $e) { file_put_contents(LOG_FILE, "Err: ".$e->getMessage(), FILE_APPEND); }
?>