@extends('admin.layouts.app')
@section('title', 'Telegram Bot Configuration')

@section('content')

    @php
        $botToken = \App\Models\Setting::val('telegram_bot_token');
        $appUrl = url('/telegram/webhook');
        $webhookUrl = $botToken 
            ? "https://api.telegram.org/bot{$botToken}/setWebhook?url={$appUrl}" 
            : "https://api.telegram.org/bot{YOUR_BOT_TOKEN}/setWebhook?url={$appUrl}";
            
        $cronCommand = "cd " . base_path() . " && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1";
        
        $lastCronRun = \Illuminate\Support\Facades\Cache::get('cron_last_run');
        $isCronRunning = $lastCronRun && now()->diffInMinutes($lastCronRun) <= 5;
    @endphp

    <div class="flex flex-col md:flex-row md:justify-between md:items-end mb-8 gap-4">
        <div>
            <h1 class="text-3xl font-extrabold text-white tracking-tight">Telegram Integration</h1>
            <p class="text-slate-400 mt-1 text-sm">Configure bot credentials, Webhook, and Cron Job.</p>
        </div>
        <a href="{{ route('admin.settings.index') }}" class="bg-slate-800 border border-slate-700 hover:bg-slate-700 px-4 py-2 rounded-xl text-sm font-medium text-slate-300 transition-colors">
            <i class="fas fa-cog mr-2"></i> General Settings
        </a>
    </div>

    @if(session('success'))
        <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-4 py-3 rounded-xl mb-6 flex items-center gap-3">
            <i class="fas fa-check-circle"></i> {{ session('success') }}
        </div>
    @endif

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
        <div class="bg-slate-800/40 border border-slate-700 rounded-2xl p-6 shadow-lg h-fit">
            <h2 class="text-lg font-bold text-white mb-6 border-b border-slate-700 pb-3">
                <i class="fab fa-telegram text-blue-400 mr-2"></i> 1. Bot Credentials
            </h2>
            <p class="text-sm text-slate-400 mb-5">Save your bot credentials first before setting up the Webhook.</p>
            
            <form action="{{ route('admin.settings.bot.update') }}" method="POST">
                @csrf
                <div class="mb-5">
                    <label class="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-2">Bot API Token</label>
                    <input type="text" name="telegram_bot_token" value="{{ $botToken }}" class="w-full bg-slate-900 border border-slate-700 text-white text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 p-3 outline-none font-mono" placeholder="123456789:ABCDefghIJKlmnopQRstUVwxyz">
                    <p class="text-[10px] text-slate-500 mt-2">Get this token from @BotFather on Telegram.</p>
                </div>
                
                <div class="mb-6">
                    <label class="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-2">Admin Chat ID</label>
                    <input type="text" name="telegram_admin_id" value="{{ \App\Models\Setting::val('telegram_admin_id') }}" class="w-full bg-slate-900 border border-slate-700 text-white text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 p-3 outline-none font-mono" placeholder="e.g. 7725438622">
                    <p class="text-[10px] text-slate-500 mt-2">The chat ID where notifications (like domain expiry alerts) will be sent.</p>
                </div>

                <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-blue-600/20 transition-all hover:scale-[1.02] flex items-center justify-center gap-2">
                    <i class="fas fa-save"></i> Save Credentials
                </button>
            </form>
        </div>

        <div class="flex flex-col gap-6">

            <div class="bg-slate-800/40 border border-slate-700 rounded-2xl p-6 shadow-lg border-l-4 border-l-purple-500">
                <h3 class="text-white font-bold mb-3"><i class="fas fa-link text-purple-400 mr-2"></i> 2. Webhook Setup (Required)</h3>
                <p class="text-sm text-slate-400 mb-4">You MUST set up the webhook so the bot can receive commands. Copy the URL below and open it in your browser <b>once</b> to connect the bot.</p>

                <div class="bg-[#020617] border border-slate-700 p-4 rounded-xl relative group pr-12">
                    <div class="absolute -top-3 left-4 bg-slate-700 text-[10px] text-white px-2 py-0.5 rounded font-bold uppercase tracking-wider">Webhook URL</div>
                    
                    <button type="button" onclick="copyCode('webhookUrl', this)" class="absolute top-1/2 -translate-y-1/2 right-2 w-8 h-8 flex items-center justify-center bg-slate-800 hover:bg-slate-600 text-slate-300 rounded-lg transition-colors" title="Copy to clipboard">
                        <i class="fas fa-copy"></i>
                    </button>

                    <code id="webhookUrl" class="text-purple-400 text-xs sm:text-sm font-mono break-all leading-relaxed block overflow-hidden">{{ $webhookUrl }}</code>
                </div>
                @if(!$botToken)
                    <p class="text-xs text-rose-400 mt-2"><i class="fas fa-exclamation-triangle"></i> Save your Bot Token first to generate the correct URL.</p>
                @endif
            </div>

            <div class="bg-slate-800/40 border border-slate-700 rounded-2xl p-6 shadow-lg border-l-4 border-l-emerald-500">
                <h3 class="text-white font-bold mb-3"><i class="fas fa-clock text-emerald-400 mr-2"></i> 3. Cron Job Setup (Required)</h3>
                <p class="text-sm text-slate-400 mb-4">To enable auto-suspension, you must set up a Cron Job in your cPanel. Follow these steps:</p>
                
                <ul class="space-y-2 text-sm text-slate-400 mb-5 list-decimal list-inside font-medium">
                    <li>Go to your cPanel and open <strong>Cron Jobs</strong>.</li>
                    <li>Select <strong>Once Per Minute (* * * * *)</strong>.</li>
                    <li>Copy & paste the command below and click <strong>Add</strong>.</li>
                </ul>

                <div class="bg-[#020617] border border-slate-700 p-4 rounded-xl relative group pr-12 mb-6">
                    <div class="absolute -top-3 left-4 bg-slate-700 text-[10px] text-white px-2 py-0.5 rounded font-bold uppercase tracking-wider">Command</div>
                    
                    <button type="button" onclick="copyCode('cronCmd', this)" class="absolute top-1/2 -translate-y-1/2 right-2 w-8 h-8 flex items-center justify-center bg-slate-800 hover:bg-slate-600 text-slate-300 rounded-lg transition-colors" title="Copy to clipboard">
                        <i class="fas fa-copy"></i>
                    </button>

                    <code id="cronCmd" class="text-emerald-400 text-xs sm:text-sm font-mono break-all leading-relaxed block overflow-hidden">{{ $cronCommand }}</code>
                </div>

                <div class="border-t border-slate-700 pt-5">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="text-white text-sm font-bold">Cron Status</h4>
                        @if($isCronRunning)
                            <span class="bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-2 py-1 rounded text-xs flex items-center gap-1 font-medium">
                                <i class="fas fa-circle text-[8px] animate-pulse"></i> Active
                            </span>
                        @else
                            <span class="bg-rose-500/10 text-rose-400 border border-rose-500/20 px-2 py-1 rounded text-xs flex items-center gap-1 font-medium">
                                <i class="fas fa-exclamation-circle"></i> Not Running
                            </span>
                        @endif
                    </div>
                    
                    <div class="bg-slate-900/50 rounded-lg overflow-hidden border border-slate-700/50">
                        <table class="w-full text-left text-sm text-slate-400">
                            <thead class="bg-slate-800/50 text-xs uppercase text-slate-300">
                                <tr>
                                    <th class="px-4 py-3">Item</th>
                                    <th class="px-4 py-3">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-700/50">
                                <tr>
                                    <td class="px-4 py-3">Cron Setup</td>
                                    <td class="px-4 py-3 font-medium">
                                        @if($isCronRunning)
                                            <i class="fas fa-check text-emerald-400"></i> <span class="text-emerald-400 text-xs ml-1">Ok</span>
                                        @else
                                            <i class="fas fa-times text-rose-400"></i> <span class="text-rose-400 text-xs ml-1">Pending</span>
                                        @endif
                                    </td>
                                </tr>
                                <tr>
                                    <td class="px-4 py-3">Cron Invocation Frequency</td>
                                    <td class="px-4 py-3 font-medium">
                                        @if($isCronRunning)
                                            <i class="fas fa-check text-emerald-400"></i> <span class="text-emerald-400 text-xs ml-1">Ok</span>
                                        @else
                                            <i class="fas fa-times text-rose-400"></i> <span class="text-rose-400 text-xs ml-1">Pending</span>
                                        @endif
                                    </td>
                                </tr>
                                <tr>
                                    <td class="px-4 py-3">Daily Cron Run</td>
                                    <td class="px-4 py-3 font-medium">
                                        @if($isCronRunning)
                                            <i class="fas fa-check text-emerald-400"></i> <span class="text-emerald-400 text-xs ml-1">Ok</span>
                                        @else
                                            <i class="fas fa-times text-rose-400"></i> <span class="text-rose-400 text-xs ml-1">Pending</span>
                                        @endif
                                    </td>
                                </tr>
                                <tr>
                                    <td class="px-4 py-3">Daily Cron Completing</td>
                                    <td class="px-4 py-3 font-medium">
                                        @if($isCronRunning)
                                            <i class="fas fa-check text-emerald-400"></i> <span class="text-emerald-400 text-xs ml-1">Ok</span>
                                        @else
                                            <i class="fas fa-times text-rose-400"></i> <span class="text-rose-400 text-xs ml-1">Pending</span>
                                        @endif
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="mt-4 flex justify-end">
                        <a href="{{ request()->url() }}" class="bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs text-white px-3 py-2 rounded-lg transition-colors flex items-center gap-2">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </a>
                    </div>
                </div>

            </div>

        </div>

    </div>

    <script>
        function copyCode(elementId, btnElement) {
            const textToCopy = document.getElementById(elementId).innerText;
            navigator.clipboard.writeText(textToCopy).then(() => {
                const originalHtml = btnElement.innerHTML;
                btnElement.innerHTML = '<i class="fas fa-check text-emerald-400"></i>';
                btnElement.classList.add('bg-emerald-500/20');
                
                setTimeout(() => {
                    btnElement.innerHTML = originalHtml;
                    btnElement.classList.remove('bg-emerald-500/20');
                }, 2000);
            }).catch(err => {
                console.error('Failed to copy text: ', err);
                alert('Failed to copy!');
            });
        }
    </script>

@endsection
