<?php
/**
 * USER MANAGER v4.0 - Device Setup
 *
 * Attivazione device tramite token da email
 * Sistema DUAL-TOKEN per sicurezza massima
 */

define('USER_MANAGER_V4', true);

require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/db.php';
require_once '../includes/session.php';

$session = new Session();
$db = new Database();

$token = $_GET['token'] ?? '';
$error = '';
$success = false;
$device = null;
$client_ip = '';

if (empty($token)) {
    $error = 'Token mancante';
} else {
    // Cerca device con questo token
    $db->query("SELECT d.*, u.first_name, u.last_name, u.email, u.role,
                sa.name as service_name, sa.url as service_url
                FROM devices d
                JOIN users u ON d.user_id = u.id
                JOIN services_available sa ON d.service_id = sa.id
                WHERE d.device_token = :token",
                ['token' => $token]);

    $device = $db->fetch();

    if (!$device) {
        $error = 'Token non valido o device già attivato';
    } elseif ($device['status'] === 'revoked') {
        $error = 'Device revocato. Contatta amministratore.';
    } elseif ($device['status'] === 'active') {
        $error = 'Device già attivato in precedenza';
    } else {
        // ATTIVA DEVICE!
        $client_ip = get_client_ip();

        // Update device status
        try {
            $result = $db->update('devices', [
                'status' => 'active',
                'ip_address' => $client_ip,
                'activated_at' => date('Y-m-d H:i:s')
            ], ['id' => $device['id']]);

            if ($result === 0) {
                error_log("WARNING: Device update returned 0 rows for ID: {$device['id']}, IP: $client_ip");
            } else {
                error_log("SUCCESS: Device {$device['id']} activated with IP: $client_ip");
                $success = true;
            }

        } catch (Exception $e) {
            error_log("CRITICAL: Device update exception for ID {$device['id']}: " . $e->getMessage());
            $error = 'Errore attivazione device. Contatta amministratore.';
            $success = false;
        }

        // =====================================================
        // AGGIUNGI IP A MODSECURITY WHITELIST AUTOMATICAMENTE
        // =====================================================
        if ($success) {
            $service_name = $device['service_name'];
            $whitelist_file = '/etc/modsecurity/usermanager-service-whitelist.conf';
            $rule_id = 2000000 + $device['id'];
            
            // Scrivi direttamente nel file (www-data ha permessi 664)
            $rule = "\n# Device #{$device['id']} - $service_name\n";
            $rule .= "SecRule REMOTE_ADDR \"@ipMatch $client_ip\" \"id:$rule_id,phase:1,pass,skipAfter:END_SERVICE_CHECK,msg:'Device {$device['id']} - $service_name'\"\n";
            
            if (file_put_contents($whitelist_file, $rule, FILE_APPEND)) {
                error_log("SUCCESS: IP $client_ip added to ModSec whitelist for {$service_name}, Device #{$device['id']}");
                
                // Invia segnale a daemon per reload Apache
                $socket = '/var/run/usermanager-reload.sock';
                if (file_exists($socket)) {
                    @file_put_contents($socket, "reload\n");
                    error_log("SUCCESS: Apache reload requested via daemon for Device #{$device['id']}");
                } else {
                    error_log("WARNING: Daemon socket not found, Apache not reloaded");
                }
            } else {
                error_log("ERROR: Failed to write to whitelist file for Device #{$device['id']}");
            }
        }

        // =====================================================
        // CREA DUAL-TOKEN COOKIE SYSTEM (SICUREZZA MASSIMA)
        // =====================================================
        if ($success) {
            // 1. device_token rimane invariato (fingerprint permanente)
            $device_token_permanent = $device['device_token'];

            // 2. Genera session_token (30 giorni)
            $session_token = bin2hex(random_bytes(32));
            $session_created = date('Y-m-d H:i:s');
            $session_expires = date('Y-m-d H:i:s', strtotime('+30 days'));

            // 3. Browser fingerprint
            $fingerprint = json_encode([
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'accept_language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '',
                'accept_encoding' => $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '',
                'created_at' => $session_created
            ]);

            // 4. Update DB con session token
            try {
                $db->update('devices', [
                    'session_token' => $session_token,
                    'session_created_at' => $session_created,
                    'session_expires_at' => $session_expires,
                    'browser_fingerprint' => $fingerprint,
                    'last_access_at' => $session_created
                ], ['id' => $device['id']]);

                error_log("SUCCESS: Session token created for device #{$device['id']}, expires: $session_expires");

            } catch (Exception $e) {
                error_log("ERROR: Failed to create session token for device #{$device['id']}: " . $e->getMessage());
            }

            // 5. Crea 3 COOKIE (dual-token system)
            $cookie_domain = ".contaboserver.net";
            $cookie_expire_long = time() + (365 * 24 * 60 * 60);  // 1 anno
            $cookie_expire_session = strtotime($session_expires);  // 30 giorni

            // Cookie 1: Device ID (JavaScript readable per debug)
            setcookie("USRMGR_DEVICE_ID", $device['id'], [
                'expires' => $cookie_expire_long,
                'path' => '/',
                'domain' => $cookie_domain,
                'secure' => true,
                'httponly' => false,  // JS può leggere
                'samesite' => 'Lax'
            ]);

            // Cookie 2: Device Token PERMANENTE (fingerprint device)
            setcookie("USRMGR_DEVICE_TOKEN", $device_token_permanent, [
                'expires' => $cookie_expire_long,
                'path' => '/',
                'domain' => $cookie_domain,
                'secure' => true,
                'httponly' => true,  // NO JS access (sicurezza!)
                'samesite' => 'Lax'
            ]);

            // Cookie 3: Session Token (rotante 30gg)
            setcookie("USRMGR_SESSION", $session_token, [
                'expires' => $cookie_expire_session,
                'path' => '/',
                'domain' => $cookie_domain,
                'secure' => true,
                'httponly' => true,  // NO JS access (sicurezza!)
                'samesite' => 'Lax'
            ]);

            error_log("SUCCESS: 3 cookies created for device #{$device['id']} (ID, TOKEN, SESSION)");
        }

        // Audit log
        if ($success) {
            $db->insert('audit_log', [
                'user_id' => $device['user_id'],
                'action' => 'device_activated',
                'ip_address' => $client_ip,
                'user_agent' => get_user_agent(),
                'created_at' => date('Y-m-d H:i:s')
            ]);

            log_audit("Device activated: ID {$device['id']}, Service {$device['service_name']}, IP $client_ip");
        }
    }
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attivazione Device</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
        .setup-container { background: white; padding: 40px; border-radius: 15px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); width: 100%; max-width: 600px; }
        .logo { text-align: center; margin-bottom: 30px; }
        .logo h1 { color: #667eea; font-size: 32px; margin-bottom: 10px; }
        .success-icon { font-size: 80px; text-align: center; margin: 30px 0; }
        .error-icon { font-size: 80px; text-align: center; margin: 30px 0; }
        .device-info { background: #f8f9fa; padding: 20px; border-radius: 10px; margin: 20px 0; border-left: 4px solid #667eea; }
        .device-info h3 { color: #667eea; margin-bottom: 15px; }
        .info-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #e0e0e0; }
        .info-row:last-child { border-bottom: none; }
        .btn { display: inline-block; padding: 15px 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600; transition: transform 0.3s; }
        .btn:hover { transform: translateY(-2px); }
        .error-box { background: #fee; color: #c33; padding: 20px; border-radius: 10px; border-left: 4px solid #f00; margin: 20px 0; }
        .success-box { background: #efe; color: #3c3; padding: 20px; border-radius: 10px; border-left: 4px solid #0f0; margin: 20px 0; }
        .footer { text-align: center; margin-top: 30px; color: #666; font-size: 12px; }
        .security-badge { background: #e8f5e9; color: #2e7d32; padding: 10px; border-radius: 8px; margin: 15px 0; font-size: 12px; text-align: center; }
    </style>
</head>
<body>
    <div class="setup-container">
        <div class="logo">
            <h1>🔐 User Manager v4.0</h1>
            <p>Attivazione Device - Sistema Dual-Token</p>
        </div>

        <?php if ($success): ?>
            <div class="success-icon">✅</div>
            <div class="success-box">
                <h2 style="margin-bottom: 10px;">🎉 Device Attivato!</h2>
                <p>Il tuo dispositivo è stato autorizzato con sistema dual-token.</p>
            </div>
            <div class="device-info">
                <h3>📱 Device</h3>
                <div class="info-row">
                    <strong>Nome:</strong>
                    <span><?= htmlspecialchars($device['device_name']) ?></span>
                </div>
                <div class="info-row">
                    <strong>Servizio:</strong>
                    <span><?= htmlspecialchars($device['service_name']) ?></span>
                </div>
                <div class="info-row">
                    <strong>IP Autorizzato:</strong>
                    <code><?= htmlspecialchars($client_ip) ?></code>
                </div>
            </div>
            <div class="security-badge">
                🔒 3 cookie di sicurezza installati | Scadenza sessione: 30 giorni
            </div>
            <div style="text-align: center; margin-top: 30px;">
                <a href="<?= htmlspecialchars($device['service_url']) ?>" class="btn">
                    🚀 Vai al Servizio
                </a>
            </div>
        <?php else: ?>
            <div class="error-icon">❌</div>
            <div class="error-box">
                <h2>⚠️ Errore</h2>
                <p><?= htmlspecialchars($error) ?></p>
            </div>
        <?php endif; ?>

        <div class="footer">
            <p>© <?= date('Y') ?> User Manager v4.0 - Dual-Token Security System</p>
        </div>
    </div>
</body>
</html>
