<?php
/**
 * USER MANAGER v4.0 - Device Setup
 *
 * Attivazione device tramite token da email
 * Sistema DUAL-TOKEN per sicurezza massima
 *
 * SUPPORTA: Prima attivazione + Ri-attivazione cookie (max 5 volte)
 *
 * FIX: Query usa services_configured come FK da devices
 * FIX: Cookie con suffisso servizio per evitare sovrascrittura!
 *      Es: USRMGR_DEVICE_ID_webmin, USRMGR_DEVICE_ID_usermanager
 */

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;
$reactivated = false;
$device = null;
$client_ip = '';

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

    $device = $db->fetch();

    if (!$device) {
        $error = 'Token non valido o device eliminato';
    } elseif ($device['status'] === 'revoked') {
        $error = 'Device revocato. Contatta amministratore.';
    } elseif ($device['status'] === 'active' && $device['reactivation_count'] >= $device['max_reactivations']) {
        // LIMITE RIATTIVAZIONI RAGGIUNTO
        $error = 'Limite riattivazioni raggiunto (' . $device['max_reactivations'] . '). Contatta amministratore.';
    } else {
        // ATTIVA O RI-ATTIVA DEVICE!
        $client_ip = get_client_ip();
        $is_first_activation = ($device['status'] === 'pending');

        if ($is_first_activation) {
            // PRIMA ATTIVAZIONE
            try {
                $result = $db->update('devices', [
                    'status' => 'active',
                    'ip_address' => $client_ip,
                    'activated_at' => date('Y-m-d H:i:s'),
                    'reactivation_count' => 0
                ], ['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;
            }
        } else {
            // RI-ATTIVAZIONE (device già active, utente ha perso cookie)
            $success = true;
            $reactivated = true;

            // Incrementa contatore riattivazioni
            $new_count = $device['reactivation_count'] + 1;

            // Aggiorna device
            $db->update('devices', [
                'ip_address' => $client_ip,
                'last_access_at' => date('Y-m-d H:i:s'),
                'reactivation_count' => $new_count
            ], ['id' => $device['id']]);

            // Logga riattivazione nella tabella dedicata
            $db->insert('device_reactivations', [
                'device_id' => $device['id'],
                'ip_address' => $client_ip,
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'created_at' => date('Y-m-d H:i:s')
            ]);

            error_log("SUCCESS: Device {$device['id']} cookie re-activation #{$new_count} for IP: $client_ip");
        }

        // =====================================================
        // AGGIUNGI IP A MODSECURITY WHITELIST AUTOMATICAMENTE
        // =====================================================
        if ($success) {
            $service_name = $device['service_name'];

            $script = "/usr/local/bin/usermanager-modsec-whitelist.sh";

            $remove_cmd = escapeshellcmd($script) . " remove " . escapeshellarg($device['id']);
            exec($remove_cmd . " 2>&1", $remove_output, $remove_code);

            $add_cmd = escapeshellcmd($script) . " add-service " .
                       escapeshellarg($service_name) . " " .
                       escapeshellarg($client_ip) . " " .
                       escapeshellarg($device['id']);
            exec($add_cmd . " 2>&1", $add_output, $add_code);

            if ($add_code === 0) {
                error_log("SUCCESS: IP $client_ip added to ModSec whitelist for {$service_name}, Device #{$device['id']}");
            } else {
                error_log("ERROR: Failed to add IP to whitelist: " . implode("\n", $add_output));
            }
        }

        // =====================================================
        // CREA DUAL-TOKEN COOKIE SYSTEM - CON SUFFISSO SERVIZIO!
        // =====================================================
        if ($success) {
            $service_name = $device['service_name']; // webmin, usermanager, phpmyadmin, etc.
            $device_token_permanent = $device['device_token'];

            $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'));

            $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
            ]);

            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: " . $e->getMessage());
            }

            $cookie_domain = "vmi2830426.contaboserver.net";
            $cookie_expire_long = time() + (365 * 24 * 60 * 60);
            $cookie_expire_session = strtotime($session_expires);

            // =====================================================
            // COOKIE CON SUFFISSO SERVIZIO - NON SI SOVRASCRIVONO!
            // Es: USRMGR_DEVICE_ID_webmin, USRMGR_DEVICE_ID_usermanager
            // =====================================================
            
            setcookie("USRMGR_DEVICE_ID_{$service_name}", $device['id'], [
                'expires' => $cookie_expire_long,
                'path' => '/',
                'domain' => $cookie_domain,
                'secure' => true,
                'httponly' => false,
                'samesite' => 'Lax'
            ]);

            setcookie("USRMGR_DEVICE_TOKEN_{$service_name}", $device_token_permanent, [
                'expires' => $cookie_expire_long,
                'path' => '/',
                'domain' => $cookie_domain,
                'secure' => true,
                'httponly' => false,
                'samesite' => 'Lax'
            ]);

            setcookie("USRMGR_SESSION_{$service_name}", $session_token, [
                'expires' => $cookie_expire_session,
                'path' => '/',
                'domain' => $cookie_domain,
                'secure' => true,
                'httponly' => false,
                'samesite' => 'Lax'
            ]);

            error_log("SUCCESS: 3 cookies created for device #{$device['id']} with suffix _{$service_name}");
        }

        // Audit log
        if ($success) {
            $action = $reactivated ? 'device_cookie_reactivated' : 'device_activated';
            try {
                $db->insert('audit_log', [
                    'user_id' => $device['user_id'],
                    'device_id' => $device['id'],
                    'action' => $action,
                    'ip_address' => $client_ip,
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            } catch (Exception $e) {
                error_log("WARNING: Audit log failed: " . $e->getMessage());
            }
        }
    }
}

// Ricarica device per mostrare contatore aggiornato
if ($device && $success && $reactivated) {
    $db->query("SELECT reactivation_count, max_reactivations FROM devices WHERE id = :id", ['id' => $device['id']]);
    $updated = $db->fetch();
    $device['reactivation_count'] = $updated['reactivation_count'];
    $device['max_reactivations'] = $updated['max_reactivations'];
}
?>
<!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; }
        .reactivated-box { background: #fff3e0; color: #e65100; padding: 20px; border-radius: 10px; border-left: 4px solid #ff9800; margin: 20px 0; }
        .warning-badge { background: #fff3e0; color: #e65100; padding: 10px; border-radius: 8px; margin: 15px 0; font-size: 12px; text-align: center; }
        .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"><?= $reactivated ? '🔄' : '✅' ?></div>

            <?php if ($reactivated): ?>
                <div class="reactivated-box">
                    <h2 style="margin-bottom: 10px;">🔄 Cookie Ripristinati!</h2>
                    <p>I cookie di autenticazione sono stati reinstallati.</p>
                </div>
                <div class="warning-badge">
                    ⚠️ Riattivazione <?= $device['reactivation_count'] ?>/<?= $device['max_reactivations'] ?> - Usa questo link solo se necessario
                </div>
            <?php else: ?>
                <div class="success-box">
                    <h2 style="margin-bottom: 10px;">🎉 Device Attivato!</h2>
                    <p>Il tuo dispositivo è stato autorizzato con sistema dual-token.</p>
                </div>
            <?php endif; ?>

            <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 per <?= htmlspecialchars($device['service_name']) ?> | 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>
