<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Artisan;
use App\Models\Setting;

class TelegramBotController extends Controller
{
    private $bot_token;
    private $admin_id;

    public function handleWebhook(Request $request)
    {
        // ডাটাবেজ থেকে ক্রেডেনশিয়াল নেওয়া
        $this->bot_token = Setting::val('telegram_bot_token');
        $this->admin_id = Setting::val('telegram_admin_id');

        if (!$this->bot_token || !$this->admin_id) {
            return response('OK', 200);
        }

        $update = $request->all();

        $chat_id = $update['message']['chat']['id'] ?? $update['callback_query']['message']['chat']['id'] ?? null;
        $user_id = $update['message']['from']['id'] ?? $update['callback_query']['from']['id'] ?? null;
        $text_msg = $update['message']['text'] ?? "";
        $message_id = $update['callback_query']['message']['message_id'] ?? null;

        if (!$chat_id) return response('OK', 200);

        // সিকিউরিটি চেক
        if ((string)$user_id !== (string)$this->admin_id) {
            $this->sendOrEdit($chat_id, null, "⛔ *Access Denied!*");
            return response('OK', 200);
        }

        // ১. রিপ্লাই হ্যান্ডলিং
        if (isset($update['message']['reply_to_message'])) {
            $this->handleReply($update, $chat_id, $text_msg);
            return response('OK', 200);
        }

        // ২. কমান্ডস
        if ($text_msg == "/start") {
            $this->showMainMenu($chat_id);
            return response('OK', 200);
        }

        // ৩. বাটন ক্লিক হ্যান্ডলিং
        if (isset($update['callback_query'])) {
            $this->handleCallback($update['callback_query'], $chat_id, $message_id);
        }

        return response('OK', 200);
    }

    // ==========================================
    // ১. রিপ্লাই লজিক (ব্যালেন্স, প্রাইস, মেসেজ)
    // ==========================================
    private function handleReply($update, $chat_id, $text_msg)
    {
        $reply_text = $update['message']['reply_to_message']['text'];
        $reply_msg_id = $update['message']['reply_to_message']['message_id'];
        $user_msg_id = $update['message']['message_id'];

        // ক. ব্যালেন্স অ্যাড
        if (strpos($reply_text, "টাকার পরিমাণ লিখুন (অ্যাড)") !== false) {
            $parts = explode("ID:", $reply_text);
            $target_uid = trim(rtrim($parts[1], ")"));
            $amount = floatval($text_msg);

            if ($amount > 0) {
                DB::table('users')->where('id', $target_uid)->increment('balance', $amount);
                DB::table('transactions')->insert([
                    'user_id' => $target_uid, 'transaction_type' => 'credit', 
                    'amount' => $amount, 'description' => 'Admin Added', 
                    'status' => 'approved', 'created_at' => now()
                ]);
                $this->deleteInputMessages($chat_id, $reply_msg_id, $user_msg_id);
                $this->sendOrEdit($chat_id, null, "✅ *ব্যালেন্স অ্যাড সফল!*\n👤 ID: `$target_uid`\n💰 Amount: `+৳$amount`");
            }
        }
        
        // খ. ব্যালেন্স কাটুন
        elseif (strpos($reply_text, "টাকার পরিমাণ লিখুন (কাটুন)") !== false) {
            $parts = explode("ID:", $reply_text);
            $target_uid = trim(rtrim($parts[1], ")"));
            $amount = floatval($text_msg);

            if ($amount > 0) {
                DB::table('users')->where('id', $target_uid)->decrement('balance', $amount);
                DB::table('transactions')->insert([
                    'user_id' => $target_uid, 'transaction_type' => 'debit', 
                    'amount' => $amount, 'description' => 'Admin Deducted', 
                    'status' => 'approved', 'created_at' => now()
                ]);
                $this->deleteInputMessages($chat_id, $reply_msg_id, $user_msg_id);
                $this->sendOrEdit($chat_id, null, "🔻 *ব্যালেন্স কমানো হয়েছে!*\n👤 ID: `$target_uid`\n💰 Amount: `-৳$amount`");
            }
        }

        // গ. ডোমেইন প্রাইস আপডেট
        elseif (strpos($reply_text, "ডোমেইনের নতুন দাম লিখুন (ID:") !== false) {
            $parts = explode("ID:", $reply_text);
            $did = trim(rtrim($parts[1], ")"));
            $price = floatval($text_msg);
            
            DB::table('subdomain_settings')->where('id', $did)->update(['price_per_month' => $price]);
            $this->deleteInputMessages($chat_id, $reply_msg_id, $user_msg_id);
            $this->sendOrEdit($chat_id, null, "🏷 *দাম আপডেট হয়েছে!*\n💰 নতুন দাম: `৳$price`");
        }

        // ঘ. ইউজারকে মেসেজ পাঠানো
        elseif (strpos($reply_text, "মেসেজটি লিখুন (User ID:") !== false) {
            $parts = explode("ID:", $reply_text);
            $target_uid = trim(rtrim($parts[1], ")"));
            
            $u = DB::table('users')->where('id', $target_uid)->first();
            
            // যদি ইউজারের টেলিগ্রাম চ্যাট আইডি ডাটাবেজে থাকে
            if ($u && isset($u->chat_id) && !empty($u->chat_id)) {
                $msg_body = "📢 *Admin Notice:*\n\n" . $text_msg;
                $this->sendToUser($u->chat_id, $msg_body);
                $this->deleteInputMessages($chat_id, $reply_msg_id, $user_msg_id);
                $this->sendOrEdit($chat_id, null, "✅ মেসেজ পাঠানো হয়েছে!");
            } else {
                $this->deleteInputMessages($chat_id, $reply_msg_id, $user_msg_id);
                $this->sendOrEdit($chat_id, null, "⚠️ এই ইউজারের টেলিগ্রাম চ্যাট আইডি ডাটাবেজে পাওয়া যায়নি।");
            }
        }
    }

    // ==========================================
    // ২. কলব্যাক লজিক (বাটন ক্লিক)
    // ==========================================
    private function handleCallback($callback, $chat_id, $message_id)
    {
        $callback_id = $callback['id'];
        $data = $callback['data'];
        
        $this->answerCallbackQuery($callback_id);

        if ($data == "main_menu") {
            $this->showMainMenu($chat_id, $message_id);
        }
        elseif ($data == "tools_menu") {
            $this->showToolsMenu($chat_id, $message_id);
        }
        elseif ($data == "refresh_stats") {
            $this->showMainMenu($chat_id, $message_id);
            $this->answerCallbackQuery($callback_id, "🔄 রিফ্রেশড!");
        }
        elseif (strpos($data, "users_page_") === 0) {
            $page = intval(str_replace("users_page_", "", $data));
            $this->showUsersList($chat_id, $page, $message_id);
        }
        elseif (strpos($data, "u_manage_") === 0) {
            $uid = intval(str_replace("u_manage_", "", $data));
            $this->showUserActions($chat_id, $uid, $message_id);
        }
        elseif (strpos($data, "u_add_") === 0) {
            $uid = intval(str_replace("u_add_", "", $data));
            $this->sendForceReply($chat_id, "💰 টাকার পরিমাণ লিখুন (অ্যাড) (ID:$uid)");
        }
        elseif (strpos($data, "u_sub_") === 0) {
            $uid = intval(str_replace("u_sub_", "", $data));
            $this->sendForceReply($chat_id, "🔻 টাকার পরিমাণ লিখুন (কাটুন) (ID:$uid)");
        }
        elseif (strpos($data, "u_msg_") === 0) {
            $uid = intval(str_replace("u_msg_", "", $data));
            $this->sendForceReply($chat_id, "📩 মেসেজটি লিখুন (User ID:$uid)");
        }
        elseif ($data == "tool_price") {
            $this->showPriceList($chat_id, $message_id);
        }
        elseif (strpos($data, "edit_p_") === 0) {
            $did = intval(str_replace("edit_p_", "", $data));
            $this->sendForceReply($chat_id, "🏷 ডোমেইনের নতুন দাম লিখুন (ID:$did)");
        }
        elseif (strpos($data, "orders_page_") === 0) {
            $page = intval(str_replace("orders_page_", "", $data));
            $this->showOrdersList($chat_id, $page, $message_id, 'all');
        }
        elseif ($data == "pending_orders") {
            $this->showOrdersList($chat_id, 1, $message_id, 'pending');
        }
        elseif (strpos($data, "o_manage_") === 0) {
            $oid = intval(str_replace("o_manage_", "", $data));
            $this->showOrderActions($chat_id, $oid, $message_id);
        }
        elseif (strpos($data, "o_act_") === 0) {
            $oid = intval(str_replace("o_act_", "", $data));
            $this->updateOrderStatus($oid, 'active');
            $this->showOrderActions($chat_id, $oid, $message_id);
            $this->answerCallbackQuery($callback_id, "✅ অ্যাক্টিভ!");
        }
        elseif (strpos($data, "o_sus_") === 0) {
            $oid = intval(str_replace("o_sus_", "", $data));
            $this->updateOrderStatus($oid, 'suspended');
            $this->showOrderActions($chat_id, $oid, $message_id);
            $this->answerCallbackQuery($callback_id, "🚫 সাসপেন্ড!");
        }
        elseif ($data == "run_cron") {
            $this->sendOrEdit($chat_id, null, "🚀 *Checking System...*");
            Artisan::call('domains:check-expiry');
            $this->sendOrEdit($chat_id, null, "✅ *চেক কমপ্লিট!*\nরেজাল্ট নোটিফিকেশন আসছে...");
        }
    }

    // ==========================================
    // UI ফাংশন (মেনুগুলো জেনারেট করা)
    // ==========================================
    private function showMainMenu($chat_id, $msg_id = null) 
    {
        $users = DB::table('users')->count();
        $orders = DB::table('user_domains')->where('status', 'active')->count();
        $pending = DB::table('user_domains')->where('status', 'pending')->count();
        $income = DB::table('transactions')->where('transaction_type', 'debit')->sum('amount'); 
        
        $text = "🔰 *AN HOSTING ADMIN PRO* 🔰\n──────────────────\n";
        $text .= "👥 ইউজার: `$users` | 📦 অ্যাক্টিভ: `$orders`\n";
        $text .= "⏳ পেন্ডিং: `$pending` | 💰 আয়: `৳" . number_format($income) . "`\n";
        $text .= "──────────────────\n👇 কুইক অ্যাকশন মেনু:";

        $kb = [
            [["text" => "👥 ইউজারস", "callback_data" => "users_page_1"], ["text" => "📦 অর্ডারস", "callback_data" => "orders_page_1"]],
            [["text" => "⏳ পেন্ডিং অর্ডার ($pending)", "callback_data" => "pending_orders"]],
            [["text" => "🛠 টুলস & সেটিংস", "callback_data" => "tools_menu"], ["text" => "🔄 রিফ্রেশ", "callback_data" => "refresh_stats"]]
        ];
        $this->sendOrEdit($chat_id, $msg_id, $text, $kb);
    }

    private function showToolsMenu($chat_id, $msg_id = null) {
        $text = "🛠 *অ্যাডভান্সড টুলস মেনু*\nপ্রয়োজনীয় টুল সিলেক্ট করুন:";
        $kb = [
            [["text" => "🏷 প্রাইস সেটআপ", "callback_data" => "tool_price"], ["text" => "🚀 রান ক্রন", "callback_data" => "run_cron"]],
            [["text" => "🔙 মেইন মেনু", "callback_data" => "main_menu"]]
        ];
        $this->sendOrEdit($chat_id, $msg_id, $text, $kb);
    }

    private function showUsersList($chat_id, $page, $msg_id = null) {
        $limit = 8; $offset = ($page - 1) * $limit;
        $total = DB::table('users')->count();
        $pages = ceil($total / $limit) ?: 1;
        
        $users = DB::table('users')->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        
        $text = "👥 *ইউজার লিস্ট* (Page $page/$pages)";
        $kb = [];
        foreach($users as $r) {
            $kb[] = [["text" => "👤 {$r->username} (৳{$r->balance})", "callback_data" => "u_manage_{$r->id}"]];
        }
        
        $nav = [];
        if($page > 1) $nav[] = ["text" => "⬅️", "callback_data" => "users_page_" . ($page - 1)];
        if($page < $pages) $nav[] = ["text" => "➡️", "callback_data" => "users_page_" . ($page + 1)];
        
        if(!empty($nav)) $kb[] = $nav;
        $kb[] = [["text" => "🔙 ব্যাক", "callback_data" => "main_menu"]];
        
        $this->sendOrEdit($chat_id, $msg_id, $text, $kb);
    }

    private function showUserActions($chat_id, $uid, $msg_id = null) {
        $u = DB::table('users')->where('id', $uid)->first();
        if(!$u) return;

        $text = "👤 *ইউজার প্রোফাইল*\n──────────────────\n";
        $text .= "🆔: `$uid` | 📛: `{$u->username}`\n";
        $text .= "📧: `{$u->email}`\n";
        $text .= "💰 ব্যালেন্স: `৳{$u->balance}`\n";
        $text .= "──────────────────";

        $kb = [
            [["text" => "➕ ব্যালেন্স দিন", "callback_data" => "u_add_$uid"], ["text" => "➖ ব্যালেন্স কাটুন", "callback_data" => "u_sub_$uid"]],
            [["text" => "📩 মেসেজ পাঠান", "callback_data" => "u_msg_$uid"]],
            [["text" => "🔙 লিস্ট", "callback_data" => "users_page_1"], ["text" => "🏠 হোম", "callback_data" => "main_menu"]]
        ];
        $this->sendOrEdit($chat_id, $msg_id, $text, $kb);
    }

    private function showPriceList($chat_id, $msg_id = null) {
        $settings = DB::table('subdomain_settings')->get();
        $text = "🏷 *ডোমেইন প্রাইস লিস্ট*\nদাম পরিবর্তন করতে ক্লিক করুন:";
        $kb = [];
        foreach($settings as $r) {
            $kb[] = [["text" => "🌐 .{$r->domain_name} - ৳{$r->price_per_month}", "callback_data" => "edit_p_{$r->id}"]];
        }
        $kb[] = [["text" => "🔙 টুলস মেনু", "callback_data" => "tools_menu"]];
        $this->sendOrEdit($chat_id, $msg_id, $text, $kb);
    }

    private function showOrdersList($chat_id, $page, $msg_id = null, $filter = 'all') {
        $limit = 6; $offset = ($page - 1) * $limit;
        
        $query = DB::table('user_domains');
        if ($filter == 'pending') $query->where('status', 'pending');
        
        $total = $query->count();
        $pages = ceil($total / $limit) ?: 1;
        
        $orders = DB::table('user_domains');
        if ($filter == 'pending') $orders->where('status', 'pending');
        $orders = $orders->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        
        $title = ($filter == 'pending') ? "⏳ পেন্ডিং অর্ডার" : "📦 সকল অর্ডার";
        $text = "*$title* (Page $page/$pages)";
        
        $kb = [];
        foreach($orders as $r) {
            $icon = $r->status == 'active' ? '🟢' : ($r->status == 'pending' ? '🟡' : '🔴');
            $kb[] = [["text" => "$icon {$r->domain_name}", "callback_data" => "o_manage_{$r->id}"]];
        }
        
        $nav = [];
        $prefix = ($filter == 'pending') ? "pending_orders" : "orders_page_"; 
        if($filter != 'pending') {
            if($page > 1) $nav[] = ["text" => "⬅️", "callback_data" => $prefix . ($page - 1)];
            if($page < $pages) $nav[] = ["text" => "➡️", "callback_data" => $prefix . ($page + 1)];
        }
        
        if(!empty($nav)) $kb[] = $nav;
        $kb[] = [["text" => "🔙 মেইন মেনু", "callback_data" => "main_menu"]];
        
        $this->sendOrEdit($chat_id, $msg_id, $text, $kb);
    }

    private function showOrderActions($chat_id, $oid, $msg_id = null) {
        $o = DB::table('user_domains')
            ->join('users', 'user_domains.user_id', '=', 'users.id')
            ->where('user_domains.id', $oid)
            ->select('user_domains.*', 'users.username')
            ->first();
            
        if(!$o) return;
        
        $text = "📦 *অর্ডার ম্যানেজমেন্ট*\n──────────────────\n";
        $text .= "🌐: `{$o->domain_name}`\n";
        $text .= "👤: `{$o->username}`\n";
        $text .= "📅: `{$o->expiry_date}`\n";
        $text .= "📡: `{$o->status}`\n";
        
        $kb = [
            [["text" => "✅ অ্যাক্টিভ করুন", "callback_data" => "o_act_$oid"], ["text" => "🚫 সাসপেন্ড করুন", "callback_data" => "o_sus_$oid"]],
            [["text" => "🔙 ব্যাক", "callback_data" => "orders_page_1"]]
        ];
        $this->sendOrEdit($chat_id, $msg_id, $text, $kb);
    }

    // ==========================================
    // API হেল্পার
    // ==========================================
    private function updateOrderStatus($order_id, $new_status) {
        DB::table('user_domains')->where('id', $order_id)->update(['status' => $new_status]);
    }

    private function sendOrEdit($chat_id, $message_id, $text, $keyboard = null) 
    {
        $data = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'Markdown'];
        if ($keyboard) $data['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);

        $method = $message_id ? 'editMessageText' : 'sendMessage';
        if ($message_id) $data['message_id'] = $message_id;

        Http::withoutVerifying()->post("https://api.telegram.org/bot{$this->bot_token}/{$method}", $data);
    }

    private function sendForceReply($chat_id, $text) {
        $data = ['chat_id' => $chat_id, 'text' => $text, 'reply_markup' => json_encode(['force_reply' => true]), 'parse_mode' => 'Markdown'];
        Http::withoutVerifying()->post("https://api.telegram.org/bot{$this->bot_token}/sendMessage", $data);
    }

    private function deleteInputMessages($chat_id, $msg1, $msg2) 
    {
        Http::withoutVerifying()->get("https://api.telegram.org/bot{$this->bot_token}/deleteMessage?chat_id={$chat_id}&message_id={$msg1}");
        Http::withoutVerifying()->get("https://api.telegram.org/bot{$this->bot_token}/deleteMessage?chat_id={$chat_id}&message_id={$msg2}");
    }

    private function answerCallbackQuery($callback_id, $text = null) 
    {
        $data = ['callback_query_id' => $callback_id];
        if ($text) $data['text'] = $text;
        Http::withoutVerifying()->post("https://api.telegram.org/bot{$this->bot_token}/answerCallbackQuery", $data);
    }
    
    private function sendToUser($chat_id, $text) {
        $data = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'Markdown'];
        Http::withoutVerifying()->post("https://api.telegram.org/bot{$this->bot_token}/sendMessage", $data);
    }
}
