<?php
/**
 * USER MANAGER v4.0 - Device Setup
 * 
 * Attivazione device tramite token da email
 * URL: https://server:8444/setup.php?token=abc123...
 */

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;

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) {
                error_log("Device update failed for ID: {$device['id']}");
            }
        } catch (Exception $e) {
            error_log("Device update exception: " . $e->getMessage());
        }

        // =====================================================
        // AGGIUNGI IP A MODSECURITY WHITELIST AUTOMATICAMENTE
        // =====================================================
        if ($success) {
            $service_name = $device['service_name'];
            $script = "/usr/local/bin/usermanager-modsec-whitelist.sh";
            
            // Comando: add-service <service_name> <ip> <device_id>
            $cmd = escapeshellcmd($script) . " add-service " . 
                   escapeshellarg($service_name) . " " . 
                   escapeshellarg($client_ip) . " " . 
                   escapeshellarg($device['id']);
            
            exec($cmd . " 2>&1", $output, $return_code);
            
            if ($return_code === 0) {
                error_log("SUCCESS: IP $client_ip added to ModSec whitelist for {$service_name}, Device #{$device['id']}");
            } else {
                error_log("WARNING: ModSec whitelist script failed: " . implode("\n", $output));
            }
        }

        // Audit log
        $db->insert('audit_log', [
    
        // Audit log
        $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')
        ]);
        
        // TODO: Add IP to ModSecurity whitelist for this service
        
        log_audit("Device activated: ID {$device['id']}, Service {$device['service_name']}, IP $client_ip");
        
        $success = true;
    }
}
?>
<!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; }
        .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; }
    </style>
</head>
<body>
    <div class="setup-container">
        <div class="logo">
            <h1>🔐 User Manager v4.0</h1>
            <p>Attivazione Device</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.</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:</strong>
                    <code><?= htmlspecialchars($client_ip) ?></code>
                </div>
            </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</p>
        </div>
    </div>
</body>
</html>
