<?php
if (!defined('USER_MANAGER_V4')) {
    http_response_code(403);
    die('Direct access not permitted');
}

// ============================================================================
// ACTIONS - Gestione servizi
// ============================================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $svc_action = $_POST['action'];

    switch ($svc_action) {

        case 'add_service':
            $name = strtolower(preg_replace('/[^a-zA-Z0-9_]/', '', $_POST['service_name'] ?? ''));
            $display_name = trim($_POST['display_name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $base_url = trim($_POST['base_url'] ?? '');
            $doc_root_input = trim($_POST['doc_root'] ?? '');
            $allowed_roles = implode(',', $_POST['allowed_roles'] ?? ['superadmin']);
            $modsec_uri = trim($_POST['modsec_uri_pattern'] ?? '');

            if (!$name || !$display_name || !$base_url) {
                $session->setFlash('error', 'Nome, Display Name e Base URL sono obbligatori');
                redirect(BASE_URL . '/superadmin_panel.php?page=services');
                break;
            }

            // Verifica nome unico
            $db->query("SELECT id FROM services_available WHERE name = ?", [$name]);
            if ($db->fetch()) {
                $session->setFlash('error', "Il servizio '$name' esiste già");
                redirect(BASE_URL . '/superadmin_panel.php?page=services');
                break;
            }

            try {
                // 1. Inserisci in services_available
                $sa_id = $db->insert('services_available', [
                    'name' => $name,
                    'display_name' => $display_name,
                    'description' => $description ?: null,
                    'service_type' => 'server',
                    'category' => 'admin',
                    'default_port' => null,
                    'default_path' => '/',
                    'icon' => 'server',
                    'requires_auth' => 1,
                    'is_common' => 0,
                    'is_active' => 1,
                    'modsec_uri_pattern' => $modsec_uri ?: null,
                    'modsec_enabled' => 1,
                    'url' => $base_url
                ]);

                // 2. Inserisci in services_configured (con doc_root)
                $sc_id = $db->insert('services_configured', [
                    'service_id' => $sa_id,
                    'custom_name' => $display_name,
                    'base_url' => $base_url,
                    'doc_root' => $doc_root_input ?: null,
                    'allowed_roles' => $allowed_roles,
                    'status' => 'active',
                    'show_in_menu' => 1,
                    'configured_at' => date('Y-m-d H:i:s'),
                    'configured_by' => $session->getEmail()
                ]);

                // 3. Crea whitelist ModSecurity vuota
                $whitelist_file = "/etc/modsecurity/usermanager-whitelist-{$name}.conf";
                $whitelist_content = "# WHITELIST {$display_name} - Generata automaticamente\n";
                $whitelist_content .= "# Servizio: {$name} (services_configured id: {$sc_id})\n";
                $whitelist_content .= "# Data: " . date('Y-m-d H:i:s') . "\n";
                $whitelist_content .= "# Nessun device registrato\n";
                file_put_contents($whitelist_file, $whitelist_content);
                chmod($whitelist_file, 0664);
                chown($whitelist_file, 'root');
                chgrp($whitelist_file, 'FTP');

                // 4. Crea 403.html dedicato
                $return_url = rtrim($base_url, '/') . '/';
                $api_url = 'https://vmi2830426.contaboserver.net:8444/api/auto-update-ip.php';

                $html_403 = <<<HTML403
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Accesso Riservato</title>
    <style>
        body { font-family: Arial; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #fff; }
        .box { text-align: center; padding: 40px; background: #16213e; border-radius: 10px; max-width: 450px; }
        .spinner { width: 40px; height: 40px; border: 4px solid #333; border-top: 4px solid #00d4ff; border-radius: 50%; animation: spin 1s linear infinite; margin: 20px auto; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        .success { color: #00ff88; }
        .error { color: #ff4444; }
        .denied { color: #ff4444; font-size: 48px; margin-bottom: 10px; }
        a { color: #00d4ff; }
        .hint { color: #888; font-size: 13px; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="box" id="content">
        <h2>🔒 Area Riservata</h2>
        <div class="spinner" id="spinner"></div>
        <p id="status">Verifica accesso in corso...</p>
    </div>
    <script>
        const SERVICE = '{$name}';
        const API_URL = '{$api_url}';
        const RETURN_URL = '{$return_url}';

        function getCookie(name) {
            const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
            return match ? match[2] : null;
        }

        async function checkAccess() {
            const deviceId = getCookie('USRMGR_DEVICE_ID_' + SERVICE);
            const deviceToken = getCookie('USRMGR_DEVICE_TOKEN_' + SERVICE);
            const sessionToken = getCookie('USRMGR_SESSION_' + SERVICE);

            if (!deviceId || !deviceToken || !sessionToken) {
                document.getElementById('spinner').style.display = 'none';
                document.getElementById('status').innerHTML =
                    '<div class="denied">⛔</div>' +
                    '<h2 style="color: #ff4444; margin: 10px 0;">Accesso non autorizzato</h2>' +
                    '<p style="color: #aaa;">Questa area è riservata.</p>' +
                    '<p class="hint">Se sei un utente autorizzato, utilizza il link di attivazione ricevuto via email.</p>';
                return;
            }

            try {
                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    credentials: 'include',
                    body: 'device_id=' + deviceId + '&device_token=' + deviceToken + '&session_token=' + sessionToken
                });
                const data = await response.json();

                if (data.success) {
                    document.getElementById('status').innerHTML =
                        '<span class="success">✅ Accesso verificato.<br>Reindirizzamento...</span>';
                    document.getElementById('spinner').style.display = 'none';
                    setTimeout(function() { window.location.href = RETURN_URL; }, 1500);
                } else {
                    document.getElementById('status').innerHTML =
                        '<span class="error">' + data.message + '</span>' +
                        '<br><p class="hint">Se il problema persiste, utilizza il link di attivazione ricevuto via email.</p>';
                    document.getElementById('spinner').style.display = 'none';
                }
            } catch (e) {
                document.getElementById('status').innerHTML =
                    '<span class="error">Errore di connessione</span>' +
                    '<br><p class="hint">Riprova tra qualche istante.</p>';
                document.getElementById('spinner').style.display = 'none';
            }
        }

        checkAccess();
    </script>
</body>
</html>
HTML403;

                // Usa doc_root dal form per posizionare 403.html
                $html_403_path = '';
                if ($doc_root_input && is_dir($doc_root_input)) {
                    $html_403_path = "{$doc_root_input}/403.html";
                    file_put_contents($html_403_path, $html_403);
                    chmod($html_403_path, 0644);
                }

                // 5. Audit log
                $db->insert('audit_log', [
                    'user_id' => $session->getUserId(),
                    'action' => 'service_added',
                    'details' => "Servizio '{$display_name}' ({$name}) aggiunto - SC#{$sc_id}",
                    'ip_address' => get_client_ip(),
                    'user_agent' => get_user_agent(),
                    'created_at' => date('Y-m-d H:i:s')
                ]);

                $msg = "✅ Servizio '{$display_name}' aggiunto! (SC#{$sc_id})";
                $msg .= " | Whitelist: {$whitelist_file}";
                if ($html_403_path) $msg .= " | 403.html: {$html_403_path}";
                else $msg .= " | ⚠️ 403.html: specifica DocumentRoot per creazione automatica";

                $session->setFlash('success', $msg);

            } catch (Exception $e) {
                $session->setFlash('error', 'Errore aggiunta servizio: ' . $e->getMessage());
            }

            redirect(BASE_URL . '/superadmin_panel.php?page=services');
            break;

        case 'toggle_service':
            $sc_id = (int)$_POST['sc_id'];
            $new_status = $_POST['new_status'] === 'active' ? 'active' : 'inactive';
            $db->update('services_configured', ['status' => $new_status], ['id' => $sc_id]);
            $session->setFlash('success', "Servizio " . ($new_status === 'active' ? 'attivato' : 'disattivato'));
            redirect(BASE_URL . '/superadmin_panel.php?page=services');
            break;

        case 'delete_service':
            $sc_id = (int)$_POST['sc_id'];

            // Non eliminare webmin o usermanager
            if ($sc_id == 1 || $sc_id == 19) {
                $session->setFlash('error', 'Non puoi eliminare Webmin o User Manager');
                redirect(BASE_URL . '/superadmin_panel.php?page=services');
                break;
            }

            // Controlla device collegati
            $db->query("SELECT COUNT(*) as cnt FROM devices WHERE service_id = ?", [$sc_id]);
            $device_count = $db->fetch()['cnt'];
            if ($device_count > 0) {
                $session->setFlash('error', "Impossibile eliminare: {$device_count} device collegati. Rimuovi prima i device.");
                redirect(BASE_URL . '/superadmin_panel.php?page=services');
                break;
            }

            // Recupera info per cleanup
            $db->query("SELECT sc.*, sa.name FROM services_configured sc JOIN services_available sa ON sc.service_id = sa.id WHERE sc.id = ?", [$sc_id]);
            $svc = $db->fetch();

            if ($svc) {
                // Elimina whitelist
                $wl_file = "/etc/modsecurity/usermanager-whitelist-{$svc['name']}.conf";
                if (file_exists($wl_file)) unlink($wl_file);

                // Elimina 403.html se doc_root disponibile
                if (!empty($svc['doc_root'])) {
                    $html_file = "{$svc['doc_root']}/403.html";
                    if (file_exists($html_file)) unlink($html_file);
                }

                // Elimina da DB
                $db->delete('services_configured', ['id' => $sc_id]);
                $db->delete('services_available', ['id' => $svc['service_id']]);

                $session->setFlash('success', "Servizio '{$svc['custom_name']}' eliminato con whitelist e 403.html");
            }

            redirect(BASE_URL . '/superadmin_panel.php?page=services');
            break;
    }
}

// ============================================================================
// CARICA DATI
// ============================================================================

$db->query("SELECT sc.*, sa.name as svc_name, sa.display_name as sa_display,
            sa.modsec_uri_pattern, sa.modsec_enabled,
            (SELECT COUNT(*) FROM devices d WHERE d.service_id = sc.id AND d.status = 'active') as active_devices,
            (SELECT COUNT(*) FROM devices d WHERE d.service_id = sc.id) as total_devices
            FROM services_configured sc
            JOIN services_available sa ON sc.service_id = sa.id
            ORDER BY sc.id ASC");
$services = $db->fetchAll();

$total_services = count($services);
$active_services = count(array_filter($services, fn($s) => $s['status'] === 'active'));
?>

<!-- STATS SERVIZI -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon">⚙️</div>
        <div class="stat-value"><?= $total_services ?></div>
        <div class="stat-label">Servizi Totali</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">✅</div>
        <div class="stat-value"><?= $active_services ?></div>
        <div class="stat-label">Servizi Attivi</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">📱</div>
        <div class="stat-value"><?= array_sum(array_column($services, 'active_devices')) ?></div>
        <div class="stat-label">Device Totali Collegati</div>
    </div>
</div>

<!-- LISTA SERVIZI -->
<div class="content-box" style="margin-bottom: 30px;">
    <h2>⚙️ Servizi Configurati</h2>

    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Servizio</th>
                <th>URL</th>
                <th>Ruoli</th>
                <th>Devices</th>
                <th>Stato</th>
                <th>File</th>
                <th>Azioni</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($services as $s): ?>
                <?php
                $wl_file = "/etc/modsecurity/usermanager-whitelist-{$s['svc_name']}.conf";
                $wl_exists = file_exists($wl_file);
                $html_403_exists = !empty($s['doc_root']) && file_exists("{$s['doc_root']}/403.html");
                $is_protected = ($s['id'] == 1 || $s['id'] == 19);
                ?>
                <tr>
                    <td>#<?= $s['id'] ?></td>
                    <td>
                        <strong><?= htmlspecialchars($s['custom_name']) ?></strong>
                        <br><small style="color: #666;"><?= htmlspecialchars($s['svc_name']) ?></small>
                    </td>
                    <td>
                        <a href="<?= htmlspecialchars($s['base_url']) ?>" target="_blank" style="color: #667eea; font-size: 13px;">
                            <?= htmlspecialchars($s['base_url']) ?>
                        </a>
                        <?php if (!empty($s['doc_root'])): ?>
                            <br><small style="color: #999;" title="DocumentRoot">📁 <?= htmlspecialchars($s['doc_root']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php foreach (explode(',', $s['allowed_roles']) as $role): ?>
                            <span class="badge badge-<?= trim($role) ?>"><?= strtoupper(trim($role)) ?></span>
                        <?php endforeach; ?>
                    </td>
                    <td>
                        <strong><?= $s['active_devices'] ?></strong> attivi
                        <?php if ($s['total_devices'] > $s['active_devices']): ?>
                            <br><small style="color: #999;"><?= $s['total_devices'] ?> totali</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="badge badge-<?= $s['status'] ?>"><?= strtoupper($s['status']) ?></span>
                    </td>
                    <td style="font-size: 12px;">
                        <?= $wl_exists ? '<span style="color: #51cf66;">✅ WL</span>' : '<span style="color: #ff6b6b;">❌ WL</span>' ?>
                        <br>
                        <?= $html_403_exists ? '<span style="color: #51cf66;">✅ 403</span>' : '<span style="color: #ff6b6b;">❌ 403</span>' ?>
                    </td>
                    <td>
                        <?php if (!$is_protected): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="action" value="toggle_service">
                                <input type="hidden" name="sc_id" value="<?= $s['id'] ?>">
                                <input type="hidden" name="new_status" value="<?= $s['status'] === 'active' ? 'inactive' : 'active' ?>">
                                <button type="submit" class="btn btn-sm <?= $s['status'] === 'active' ? 'btn-warning' : 'btn-success' ?>" title="<?= $s['status'] === 'active' ? 'Disattiva' : 'Attiva' ?>">
                                    <?= $s['status'] === 'active' ? '⏸️' : '▶️' ?>
                                </button>
                            </form>
                            <form method="POST" style="display: inline;" onsubmit="return confirm('Eliminare questo servizio? Operazione irreversibile!');">
                                <input type="hidden" name="action" value="delete_service">
                                <input type="hidden" name="sc_id" value="<?= $s['id'] ?>">
                                <button type="submit" class="btn btn-sm btn-danger" title="Elimina">🗑️</button>
                            </form>
                        <?php else: ?>
                            <span style="color: #999;">🔒 Protetto</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- FORM AGGIUNGI SERVIZIO -->
<div class="content-box">
    <h2>➕ Aggiungi Nuovo Servizio</h2>
    <p style="color: #666; margin-bottom: 20px;">Aggiunge il servizio al database, crea whitelist ModSecurity e 403.html automaticamente.</p>

    <form method="POST">
        <input type="hidden" name="action" value="add_service">

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div class="form-group">
                <label>Nome Servizio (identificativo, solo lettere/numeri/underscore) *</label>
                <input type="text" name="service_name" class="form-control" placeholder="es: phpmyadmin" required pattern="[a-zA-Z0-9_]+" title="Solo lettere, numeri e underscore">
            </div>

            <div class="form-group">
                <label>Display Name (nome visibile) *</label>
                <input type="text" name="display_name" class="form-control" placeholder="es: phpMyAdmin" required>
            </div>

            <div class="form-group" style="grid-column: span 2;">
                <label>Base URL (indirizzo completo del servizio) *</label>
                <input type="url" name="base_url" class="form-control" placeholder="es: https://vmi2830426.contaboserver.net:8443/" required>
            </div>

            <div class="form-group" style="grid-column: span 2;">
                <label>DocumentRoot (percorso directory web del servizio)</label>
                <input type="text" name="doc_root" class="form-control" placeholder="es: /usr/share/phpmyadmin oppure /var/www/html/cloud.restless.it">
                <small style="color: #999;">Necessario per creare automaticamente il file 403.html nella directory corretta</small>
            </div>

            <div class="form-group" style="grid-column: span 2;">
                <label>Descrizione</label>
                <input type="text" name="description" class="form-control" placeholder="es: Gestione database MariaDB">
            </div>

            <div class="form-group">
                <label>Pattern URI ModSecurity</label>
                <input type="text" name="modsec_uri_pattern" class="form-control" placeholder="es: ^/phpmyadmin">
                <small style="color: #999;">Lascia vuoto se il servizio ha un vhost/porta dedicata</small>
            </div>

            <div class="form-group">
                <label>Ruoli Autorizzati *</label>
                <div style="display: flex; gap: 15px; padding: 10px;">
                    <label><input type="checkbox" name="allowed_roles[]" value="superadmin" checked> SuperAdmin</label>
                    <label><input type="checkbox" name="allowed_roles[]" value="admin"> Admin</label>
                    <label><input type="checkbox" name="allowed_roles[]" value="user"> User</label>
                </div>
            </div>
        </div>

        <div style="margin-top: 20px; padding: 15px; background: #f0f4ff; border-radius: 8px; border-left: 4px solid #667eea;">
            <strong>ℹ️ Cosa verrà creato automaticamente:</strong>
            <ul style="margin-top: 10px; padding-left: 20px; color: #555;">
                <li>Entry in <code>services_available</code> e <code>services_configured</code></li>
                <li>File whitelist: <code>/etc/modsecurity/usermanager-whitelist-[nome].conf</code></li>
                <li>Pagina 403.html nella DocumentRoot specificata</li>
            </ul>
            <p style="margin-top: 10px; color: #e65100;"><strong>⚠️ Dopo l'aggiunta, configura manualmente:</strong> Include whitelist nel vhost Apache e ErrorDocument 403</p>
        </div>

        <div style="margin-top: 20px;">
            <button type="submit" class="btn btn-primary">➕ Aggiungi Servizio</button>
        </div>
    </form>
</div>
