<?php
// ── Respond to Telegram immediately (fix timeout) ──────
ignore_user_abort(true);
set_time_limit(600);
ob_start();
http_response_code(200);
echo 'OK';
$size = ob_get_length();
header("Content-Length: $size");
header("Connection: close");
header("Content-Type: text/plain");
ob_end_flush();
@ob_flush();
flush();
if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
// ── Now process in background (Telegram won't wait) ────

$config_file = __DIR__ . '/config.json';
$config = json_decode(file_get_contents($config_file), true) ?? [];
$TOKEN  = $config['bot_token'] ?? '';
$API    = "https://api.telegram.org/bot{$TOKEN}";

$raw    = file_get_contents('php://input');
$update = json_decode($raw, true);
if (!$update || !$TOKEN) exit;

// Log
file_put_contents(__DIR__.'/log.txt',
    date('Y-m-d H:i:s').' | '.json_encode($update, JSON_UNESCAPED_UNICODE)."\n",
    FILE_APPEND | LOCK_EX);

// ── Chat Join Request ──────────────────────────────────
if (isset($update['chat_join_request'])) {
    $req     = $update['chat_join_request'];
    $user    = $req['from'];
    $user_id = $user['id'];
    $chat_id = $req['chat']['id'];

    trackUser($user);

    if (!empty($config['auto_approve'])) {
        tgCall('approveChatJoinRequest', ['chat_id'=>$chat_id, 'user_id'=>$user_id]);
    }

    // Send DM to user
    if (!empty($config['send_to_private']) || !isset($config['send_to_private'])) {
        sendWelcomePackage($user_id, $user);
    }

    // Optionally send to group
    if (!empty($config['send_to_group'])) {
        sendWelcomePackage($chat_id, $user);
    }
}

// ── /start ─────────────────────────────────────────────
if (isset($update['message']['text']) && strpos($update['message']['text'], '/start') === 0) {
    $cid   = $update['message']['chat']['id'];
    $fname = htmlspecialchars($update['message']['from']['first_name'] ?? 'বন্ধু');
    tgCall('sendMessage', [
        'chat_id'    => $cid,
        'text'       => "হ্যালো <b>{$fname}</b>! 👋\nআপনার join request পাঠানো হয়েছে।\nAdmin approve করলে গ্রুপে যোগ দিতে পারবেন। ✅",
        'parse_mode' => 'HTML'
    ]);
}

exit;

// ══════════════════════════════════════════════════════
function sendWelcomePackage($chat_id, $user) {
    global $config, $config_file;

    $fname    = $user['first_name'] ?? '';
    $lname    = $user['last_name']  ?? '';
    $uname    = isset($user['username']) ? '@'.$user['username'] : trim($fname.' '.$lname);
    $fullname = trim($fname.' '.$lname);
    $r        = ['{name}' => $fullname, '{username}' => $uname];

    // ── 1. Welcome Video ────────────────────────────────
    $cap  = str_replace(array_keys($r), array_values($r), $config['welcome_caption'] ?? '');
    $sent = false;

    // Try cached file_id first (fastest)
    if (!empty($config['welcome_video_file_id'])) {
        $res  = tgCall('sendVideo', [
            'chat_id'           => $chat_id,
            'video'             => $config['welcome_video_file_id'],
            'caption'           => $cap,
            'parse_mode'        => 'HTML',
            'supports_streaming'=> true,
        ]);
        if (!empty($res['ok'])) {
            $sent = true;
        } else {
            // Cache invalid — clear it
            $config['welcome_video_file_id'] = '';
            saveConfig($config, $config_file);
        }
    }

    // Try local file
    if (!$sent && !empty($config['welcome_video_path']) && file_exists($config['welcome_video_path'])) {
        $res = sendFile('sendVideo', $chat_id, 'video', $config['welcome_video_path'], $cap);
        if (!empty($res['ok'])) {
            $sent = true;
            // Cache the file_id for next time
            $fid = $res['result']['video']['file_id'] ?? '';
            if ($fid) {
                $config['welcome_video_file_id'] = $fid;
                saveConfig($config, $config_file);
            }
        }
    }

    // Try video URL
    if (!$sent && !empty($config['welcome_video_url'])) {
        $res = tgCall('sendVideo', [
            'chat_id'           => $chat_id,
            'video'             => $config['welcome_video_url'],
            'caption'           => $cap,
            'parse_mode'        => 'HTML',
            'supports_streaming'=> true,
        ]);
        if (!empty($res['ok'])) {
            $sent = true;
            $fid = $res['result']['video']['file_id'] ?? '';
            if ($fid) {
                $config['welcome_video_file_id'] = $fid;
                saveConfig($config, $config_file);
            }
        }
    }

    // Fallback: text message
    if (!$sent) {
        $text = str_replace(array_keys($r), array_values($r),
            $config['welcome_text'] ?? 'স্বাগতম!');
        tgCall('sendMessage', ['chat_id'=>$chat_id, 'text'=>$text, 'parse_mode'=>'HTML']);
    }

    // ── 2. Extra Videos ─────────────────────────────────
    foreach (($config['videos'] ?? []) as $i => $v) {
        if (empty($v['enabled'])) continue;
        $vcap = str_replace(array_keys($r), array_values($r), $v['caption'] ?? '');
        if (!empty($v['file_id'])) {
            $res = tgCall('sendVideo', [
                'chat_id'           => $chat_id,
                'video'             => $v['file_id'],
                'caption'           => $vcap,
                'parse_mode'        => 'HTML',
                'supports_streaming'=> true,
            ]);
            if (empty($res['ok'])) {
                // file_id expired — re-upload
                $config['videos'][$i]['file_id'] = '';
                saveConfig($config, $config_file);
                if (!empty($v['path']) && file_exists($v['path'])) {
                    $res2 = sendFile('sendVideo', $chat_id, 'video', $v['path'], $vcap);
                    if (!empty($res2['result']['video']['file_id'])) {
                        $config['videos'][$i]['file_id'] = $res2['result']['video']['file_id'];
                        saveConfig($config, $config_file);
                    }
                }
            }
        } elseif (!empty($v['path']) && file_exists($v['path'])) {
            $res = sendFile('sendVideo', $chat_id, 'video', $v['path'], $vcap);
            if (!empty($res['result']['video']['file_id'])) {
                $config['videos'][$i]['file_id'] = $res['result']['video']['file_id'];
                saveConfig($config, $config_file);
            }
        }
    }

    // ── 3. APKs ─────────────────────────────────────────
    foreach (($config['apks'] ?? []) as $i => $apk) {
        if (empty($apk['enabled'])) continue;
        $acap = str_replace(array_keys($r), array_values($r), $apk['caption'] ?? '');
        if (!empty($apk['file_id'])) {
            $res = tgCall('sendDocument', [
                'chat_id'  => $chat_id,
                'document' => $apk['file_id'],
                'caption'  => $acap,
                'parse_mode'=>'HTML',
            ]);
            if (empty($res['ok']) && !empty($apk['path']) && file_exists($apk['path'])) {
                $config['apks'][$i]['file_id'] = '';
                saveConfig($config, $config_file);
                $res2 = sendFile('sendDocument', $chat_id, 'document', $apk['path'], $acap);
                if (!empty($res2['result']['document']['file_id'])) {
                    $config['apks'][$i]['file_id'] = $res2['result']['document']['file_id'];
                    saveConfig($config, $config_file);
                }
            }
        } elseif (!empty($apk['path']) && file_exists($apk['path'])) {
            $res = sendFile('sendDocument', $chat_id, 'document', $apk['path'], $acap);
            if (!empty($res['result']['document']['file_id'])) {
                $config['apks'][$i]['file_id'] = $res['result']['document']['file_id'];
                saveConfig($config, $config_file);
            }
        }
    }

    // ── 4. Other files ──────────────────────────────────
    $methodMap = ['video'=>'sendVideo','photo'=>'sendPhoto','audio'=>'sendAudio'];
    $fieldMap  = ['video'=>'video','photo'=>'photo','audio'=>'audio'];
    foreach (($config['extra_files'] ?? []) as $i => $ef) {
        if (empty($ef['enabled'])) continue;
        $fcap   = str_replace(array_keys($r), array_values($r), $ef['caption'] ?? '');
        $method = $methodMap[$ef['type']??''] ?? 'sendDocument';
        $field  = $fieldMap[$ef['type']??'']  ?? 'document';
        if (!empty($ef['file_id'])) {
            $res = tgCall($method, [
                'chat_id'    => $chat_id,
                $field       => $ef['file_id'],
                'caption'    => $fcap,
                'parse_mode' => 'HTML',
            ]);
            if (empty($res['ok']) && !empty($ef['path']) && file_exists($ef['path'])) {
                $config['extra_files'][$i]['file_id'] = '';
                saveConfig($config, $config_file);
                $res2 = sendFile($method, $chat_id, $field, $ef['path'], $fcap);
                $fid  = $res2['result'][$field]['file_id'] ?? ($res2['result']['document']['file_id'] ?? '');
                if ($fid) { $config['extra_files'][$i]['file_id'] = $fid; saveConfig($config, $config_file); }
            }
        } elseif (!empty($ef['path']) && file_exists($ef['path'])) {
            $res = sendFile($method, $chat_id, $field, $ef['path'], $fcap);
            $fid = $res['result'][$field]['file_id'] ?? ($res['result']['document']['file_id'] ?? '');
            if ($fid) { $config['extra_files'][$i]['file_id'] = $fid; saveConfig($config, $config_file); }
        }
    }
}

// ──────────────────────────────────────────────────────
function trackUser($user) {
    $f    = __DIR__.'/users.json';
    $data = [];
    if (file_exists($f)) {
        $raw = file_get_contents($f);
        $data = json_decode($raw, true) ?? [];
    }
    $id = (string)$user['id'];
    if (!isset($data[$id])) {
        $data[$id] = [
            'id'         => $user['id'],
            'first_name' => $user['first_name'] ?? '',
            'last_name'  => $user['last_name']  ?? '',
            'username'   => $user['username']   ?? '',
            'joined_at'  => date('Y-m-d H:i:s'),
        ];
        file_put_contents($f, json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE), LOCK_EX);
    }
}

function sendFile($method, $chat_id, $field, $path, $caption = '') {
    global $API;
    $ch = curl_init("{$API}/{$method}");
    $d  = [
        'chat_id'            => $chat_id,
        $field               => new CURLFile(realpath($path)),
        'parse_mode'         => 'HTML',
        'supports_streaming' => 'true',
    ];
    if ($caption !== '') $d['caption'] = $caption;
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $d,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 300,
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true) ?? [];
}

function tgCall($method, $params) {
    global $API;
    $ch = curl_init("{$API}/{$method}");
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($params),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 60,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $r = curl_exec($ch);
    curl_close($ch);
    return json_decode($r, true) ?? [];
}

function saveConfig($c, $f) {
    $tmp = $f . '.tmp';
    file_put_contents($tmp, json_encode($c, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE), LOCK_EX);
    rename($tmp, $f);
}