<?php
// webhook.php - COMPLETE WORKING VERSION

// Enable all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log file
$log_file = 'webhook_debug.log';

// Log request details
file_put_contents($log_file, "\n" . str_repeat("=", 50) . "\n", FILE_APPEND);
file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] NEW REQUEST\n", FILE_APPEND);
file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Method: " . $_SERVER['REQUEST_METHOD'] . "\n", FILE_APPEND);

// Get input data
$input = file_get_contents('php://input');
file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Raw Input Length: " . strlen($input) . " bytes\n", FILE_APPEND);

// For browser access - show info
if (empty($input) && php_sapi_name() !== 'cli') {
    echo "<h1>🤖 File Locker Bot - Webhook</h1>";
    echo "<p><strong>Status:</strong> ✅ ACTIVE</p>";
    echo "<p><strong>Last Check:</strong> " . date('Y-m-d H:i:s') . "</p>";
    echo "<p><strong>Webhook URL:</strong> https://squids.in/bot/webhook.php</p>";
    echo "<p><strong>Debug Log:</strong> webhook_debug.log</p>";
    echo "<hr>";
    echo "<h3>Next Steps:</h3>";
    echo "<ol>";
    echo "<li>Bot ko /start bhejein</li>";
    echo "<li>Check karein response aata hai ya nahi</li>";
    echo "</ol>";
    exit;
}

// If no input from Telegram, exit
if (empty($input)) {
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] ❌ EMPTY INPUT - No data from Telegram\n", FILE_APPEND);
    http_response_code(200);
    echo "OK";
    exit;
}

// Try to decode JSON
$update = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] ❌ JSON ERROR: " . json_last_error_msg() . "\n", FILE_APPEND);
    http_response_code(200);
    echo "OK";
    exit;
}

file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] ✅ Valid JSON Received\n", FILE_APPEND);

// Process the update
try {
    // Include required files
    require_once 'config.php';
    require_once 'inc/db.php';
    require_once 'inc/functions.php';
    require_once 'inc/telegram.php';
    
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] ✅ Required files loaded\n", FILE_APPEND);
    
    if (isset($update['message'])) {
        process_message($update['message']);
    } elseif (isset($update['callback_query'])) {
        process_callback_query($update['callback_query']);
    } else {
        file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] ⚠️ Unknown update type\n", FILE_APPEND);
    }
    
} catch (Exception $e) {
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] ❌ EXCEPTION: " . $e->getMessage() . "\n", FILE_APPEND);
}

http_response_code(200);
echo "OK";

/**
 * Process incoming message
 */
function process_message($message) {
    global $log_file;
    
    $chat_id = $message['chat']['id'];
    $user_id = $message['from']['id'];
    $username = $message['from']['username'] ?? '';
    $first_name = $message['from']['first_name'] ?? '';
    $last_name = $message['from']['last_name'] ?? '';
    $text = $message['text'] ?? '';
    
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] 📨 Message from {$user_id}: {$text}\n", FILE_APPEND);
    
    // Create or get user
    get_or_create_user($user_id, $username, $first_name, $last_name);
    
    log_activity($user_id, 'message_received', "Text: $text");
    
    if ($text == '/start') {
        file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] /start command received\n", FILE_APPEND);
        show_welcome_message($chat_id, $user_id);
    } elseif (strpos($text, '/fil') === 0) {
        $public_id = substr($text, 4);
        file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] File request: $public_id\n", FILE_APPEND);
        process_file_request($chat_id, $user_id, $public_id);
    } elseif ($text == '/help') {
        show_help_message($chat_id);
    } else {
        send_message($chat_id, "❌ Unknown command. Use /start to see available options.");
    }
}

/**
 * Show welcome message with buttons
 */
function show_welcome_message($chat_id, $user_id) {
    global $log_file;
    
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Showing welcome message to $chat_id\n", FILE_APPEND);
    
    $welcome_message = "👋 <b>Welcome to File Locker Bot!</b>\n\n";
    $welcome_message .= "📦 <b>Your Ultimate File Sharing Solution</b>\n\n";
    $welcome_message .= "✨ <b>Features:</b>\n";
    $welcome_message .= "✅ Free & Paid Files\n";
    $welcome_message .= "✅ Secure File Delivery\n";
    $welcome_message .= "✅ Instant Access\n";
    $welcome_message .= "✅ 24/7 Available\n\n";
    $welcome_message .= "🎯 <b>Get started by clicking the buttons below:</b>";
    
    $keyboard = [
        'inline_keyboard' => [
            [
                ['text' => '📁 Available Files', 'callback_data' => 'show_files'],
                ['text' => 'ℹ️ Help', 'callback_data' => 'show_help']
            ],
            [
                ['text' => '👨‍💻 Contact Admin', 'url' => 'https://t.me/' . ADMIN_USERNAME]
            ]
        ]
    ];
    
    $result = send_message($chat_id, $welcome_message, $keyboard);
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Send message result: " . print_r($result, true) . "\n", FILE_APPEND);
    
    if (!$result['ok']) {
        file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Failed to send message: " . $result['description'] . "\n", FILE_APPEND);
    }
    
    log_activity($user_id, 'welcome_message_shown');
}

/**
 * Show help message
 */
function show_help_message($chat_id) {
    $help_message = "❓ <b>How to Use This Bot:</b>\n\n";
    $help_message .= "1. <b>Browse Files:</b> Click 'Available Files' to see all files\n";
    $help_message .= "2. <b>Free Files:</b> Join required channels and get instant access\n";
    $help_message .= "3. <b>Paid Files:</b> Request access and admin will approve\n";
    $help_message .= "4. <b>Channel Membership:</b> Some files require channel subscription\n\n";
    $help_message .= "🔧 <b>Commands:</b>\n";
    $help_message .= "/start - Show welcome message\n";
    $help_message .= "/help - Show this help message\n\n";
    $help_message .= "📞 <b>Need Help?</b> Contact admin using the button below";
    
    $keyboard = [
        'inline_keyboard' => [
            [
                ['text' => '📁 Available Files', 'callback_data' => 'show_files'],
                ['text' => '🔙 Back to Main', 'callback_data' => 'show_welcome']
            ],
            [
                ['text' => '👨‍💻 Contact Admin', 'url' => 'https://t.me/' . ADMIN_USERNAME]
            ]
        ]
    ];
    
    send_message($chat_id, $help_message, $keyboard);
}

/**
 * Process callback query from buttons
 */
function process_callback_query($callback_query) {
    global $log_file;
    
    $chat_id = $callback_query['message']['chat']['id'];
    $user_id = $callback_query['from']['id'];
    $callback_id = $callback_query['id'];
    $data = $callback_query['data'];
    $message_id = $callback_query['message']['message_id'];
    
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Callback query: $data from user $user_id\n", FILE_APPEND);
    
    answer_callback_query($callback_id, "");
    
    switch ($data) {
        case 'show_files':
            show_main_menu($chat_id, $user_id, $message_id);
            break;
            
        case 'show_help':
            show_help_message($chat_id);
            break;
            
        case 'show_welcome':
            show_welcome_message($chat_id, $user_id);
            break;
            
        case 'check_membership':
            // Get the original message to find which file was requested
            $message_text = $callback_query['message']['text'];
            preg_match('/File: (.+?) -/', $message_text, $matches);
            if (isset($matches[1])) {
                $public_id = trim($matches[1]);
                process_file_request($chat_id, $user_id, $public_id, $message_id);
            } else {
                send_message($chat_id, "⚠️ Please use the file buttons to access files.");
            }
            break;
            
        default:
            // Check if it's a file request from new button system
            if (strpos($data, 'file_') === 0) {
                $public_id = substr($data, 5);
                process_file_request($chat_id, $user_id, $public_id, $message_id);
            }
            break;
    }
}

/**
 * Show main menu with available files
 */
function show_main_menu($chat_id, $user_id, $edit_message_id = null) {
    global $log_file;
    
    $files = get_all_files();
    
    if (empty($files)) {
        $message = "📭 <b>No Files Available</b>\n\n";
        $message .= "There are no files available at the moment.\n";
        $message .= "Please check back later or contact admin.";
        
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '🔙 Back to Main', 'callback_data' => 'show_welcome'],
                    ['text' => 'ℹ️ Help', 'callback_data' => 'show_help']
                ]
            ]
        ];
        
        if ($edit_message_id) {
            edit_message_text($chat_id, $edit_message_id, $message, $keyboard);
        } else {
            send_message($chat_id, $message, $keyboard);
        }
        return;
    }
    
    $message = "📁 <b>Available Files</b>\n\n";
    $message .= "Click on any file below to access it:\n\n";
    
    // Create buttons for files
    $keyboard = [];
    
    foreach ($files as $file) {
        $price_icon = $file['is_paid'] ? "💰" : "🆓";
        $button_text = "{$price_icon} {$file['title']}";
        
        $keyboard[] = [
            ['text' => $button_text, 'callback_data' => 'file_' . $file['public_id']]
        ];
    }
    
    // Add navigation buttons
    $keyboard[] = [
        ['text' => '🔙 Back to Main', 'callback_data' => 'show_welcome'],
        ['text' => 'ℹ️ Help', 'callback_data' => 'show_help']
    ];
    
    $final_keyboard = ['inline_keyboard' => $keyboard];
    
    if ($edit_message_id) {
        edit_message_text($chat_id, $edit_message_id, $message, $final_keyboard);
    } else {
        send_message($chat_id, $message, $final_keyboard);
    }
    
    log_activity($user_id, 'files_list_shown');
}

/**
 * Process file unlock request - THIS FUNCTION WAS MISSING!
 */
function process_file_request($chat_id, $user_id, $public_id, $edit_message_id = null) {
    global $log_file;
    
    $file = get_file_by_public_id($public_id);
    
    if (!$file) {
        $message = "❌ <b>File Not Found</b>\n\n";
        $message .= "The requested file was not found.\n";
        $message .= "Please check the file list again.";
        
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '📁 Available Files', 'callback_data' => 'show_files'],
                    ['text' => '🔙 Back to Main', 'callback_data' => 'show_welcome']
                ]
            ]
        ];
        
        if ($edit_message_id) {
            edit_message_text($chat_id, $edit_message_id, $message, $keyboard);
        } else {
            send_message($chat_id, $message, $keyboard);
        }
        return;
    }
    
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] Processing file: {$file['title']}\n", FILE_APPEND);
    
    // Check channel membership
    $membership_check = check_channel_membership($user_id, $file['required_channels']);
    
    if ($membership_check !== true) {
        // User hasn't joined all channels
        $message = "🔒 <b>{$file['title']}</b>\n\n";
        $message .= "📋 <b>Requirements:</b>\n";
        $message .= "To access this file, please join the following channel(s):\n\n";
        
        foreach ($membership_check as $channel) {
            $message .= "• @$channel\n";
        }
        
        $message .= "\nAfter joining, click the button below to verify.";
        
        // Create join buttons
        $keyboard = [];
        foreach ($membership_check as $channel) {
            $keyboard[] = [
                ['text' => "Join @$channel", 'url' => "https://t.me/" . ltrim($channel, '@')]
            ];
        }
        
        $keyboard[] = [
            ['text' => "✅ I've Joined - Check Now", 'callback_data' => 'file_' . $public_id]
        ];
        
        $keyboard[] = [
            ['text' => '📁 Back to Files', 'callback_data' => 'show_files']
        ];
        
        $final_keyboard = ['inline_keyboard' => $keyboard];
        
        if ($edit_message_id) {
            edit_message_text($chat_id, $edit_message_id, $message, $final_keyboard);
        } else {
            send_message($chat_id, $message, $final_keyboard);
        }
        
        log_activity($user_id, 'membership_required', "File: {$file['title']}");
        return;
    }
    
    // User has joined all required channels
    if (!$file['is_paid']) {
        // Free file - send immediately
        $file_path = __DIR__ . '/uploads/' . $file['filename'];
        
        if (file_exists($file_path)) {
            // Success message with download button
            $success_message = "✅ <b>Access Granted!</b>\n\n";
            $success_message .= "📁 <b>File:</b> {$file['title']}\n";
            $success_message .= "🆓 <b>Type:</b> Free File\n\n";
            $success_message .= "Your file is being sent...";
            
            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => '📁 More Files', 'callback_data' => 'show_files'],
                        ['text' => '🔙 Main Menu', 'callback_data' => 'show_welcome']
                    ]
                ]
            ];
            
            if ($edit_message_id) {
                edit_message_text($chat_id, $edit_message_id, $success_message, $keyboard);
            }
            
            // Send the file
            send_document($chat_id, $file_path, "📁 <b>{$file['title']}</b>\n\nEnjoy your file! 🎉");
            log_activity($user_id, 'file_sent_free', "File: {$file['title']}");
        } else {
            $error_message = "❌ <b>File Delivery Failed</b>\n\n";
            $error_message .= "The file was not found on our server.\n";
            $error_message .= "Please contact admin for support.";
            
            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => '👨‍💻 Contact Admin', 'url' => 'https://t.me/' . ADMIN_USERNAME],
                        ['text' => '📁 Back to Files', 'callback_data' => 'show_files']
                    ]
                ]
            ];
            
            if ($edit_message_id) {
                edit_message_text($chat_id, $edit_message_id, $error_message, $keyboard);
            } else {
                send_message($chat_id, $error_message, $keyboard);
            }
            
            log_activity($user_id, 'file_not_found', "File: {$file['title']}");
        }
    } else {
        // Paid file - create unlock request
        $request_id = create_unlock_request($user_id, $file['id']);
        
        $message = "💰 <b>Paid File Request</b>\n\n";
        $message .= "📁 <b>File:</b> {$file['title']}\n";
        $message .= "💵 <b>Price:</b> {$file['price_text']}\n\n";
        $message .= "📨 <b>Status:</b> Request Sent to Admin\n\n";
        $message .= "You will receive the file once admin approves your request.";
        
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '📁 Browse More Files', 'callback_data' => 'show_files'],
                    ['text' => '🔙 Main Menu', 'callback_data' => 'show_welcome']
                ]
            ]
        ];
        
        if ($edit_message_id) {
            edit_message_text($chat_id, $edit_message_id, $message, $keyboard);
        } else {
            send_message($chat_id, $message, $keyboard);
        }
        
        // Notify admin
        $user_info = get_or_create_user($user_id, '', '', '');
        $admin_message = "🆕 <b>New Unlock Request</b>\n\n";
        $admin_message .= "👤 <b>User:</b> {$user_info['first_name']}";
        if ($user_info['username']) {
            $admin_message .= " (@{$user_info['username']})";
        }
        $admin_message .= "\n📁 <b>File:</b> {$file['title']}\n";
        $admin_message .= "💰 <b>Price:</b> {$file['price_text']}\n";
        $admin_message .= "🆔 <b>Request ID:</b> {$request_id}\n\n";
        $admin_message .= "💻 <i>Go to admin panel to approve</i>";
        
        send_message(ADMIN_ID, $admin_message);
        
        log_activity($user_id, 'unlock_request_created', "File: {$file['title']}, Request ID: {$request_id}");
    }
}
?>