<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

$configPath = __DIR__ . '/../backend/config.php';
if (!file_exists($configPath)) {
    die('Errore interno: file di configurazione non trovato. Percorso cercato: ' . htmlspecialchars($configPath));
}

require_once $configPath;

// Gestione logout
if (isset($_GET['logout'])) {
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    session_destroy();
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}

$incidents = require __DIR__ . '/../backend/incidents.php';

// Login
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    if ($_POST['password'] === DASHBOARD_PASSWORD) {
        $_SESSION['logged_in'] = true;
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $error = 'Password errata';
    }
}

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    ?>
    <!DOCTYPE html>
    <html lang="it">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>SecureNet Cloud - Accesso</title>
        <link rel="stylesheet" href="assets/css/style.css?v=20260716b">
        <link href="../lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" rel="stylesheet">
    </head>
    <body class="login-body">
        <div class="login-card">
            <div class="login-icon"><span class="material-symbols-outlined" style="font-size:48px;">lock</span></div>
            <h3>SecureNet Cloud</h3>
            <p class="login-subtitle">Accesso Riservato alla Dashboard</p>
            <?php if ($error): ?>
                <div class="alert alert-danger"><?= $error ?></div>
            <?php endif; ?>
            <form method="post">
                <div class="mb-3">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" required autofocus placeholder="Inserisci la password">
                </div>
                <button class="btn-accent w-100">Accedi</button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// ---- DASHBOARD (utente loggato) ----

// Calcoli statistiche
$statoCounts = [];
$pericoloCounts = [];
foreach ($incidents as $inc) {
    $stato = $inc['stato'];
    $pericolo = $inc['pericolo'];
    if (!isset($statoCounts[$stato])) $statoCounts[$stato] = 0;
    $statoCounts[$stato]++;
    if (!isset($pericoloCounts[$pericolo])) $pericoloCounts[$pericolo] = 0;
    $pericoloCounts[$pericolo]++;
}
$totale = count($incidents);
$bloccati = $statoCounts['Bloccato'] ?? 0;
$rilevati = $statoCounts['Rilevato'] ?? 0;
$isolati = $statoCounts['Isolato'] ?? 0;
$monitorati = $statoCounts['Monitorato'] ?? 0;
$percentualeBloccati = $totale > 0 ? round(($bloccati / $totale) * 100) : 0;
$percentualeRilevati = $totale > 0 ? round(($rilevati / $totale) * 100) : 0;

$critici = $pericoloCounts['Critico'] ?? 0;
$alti = $pericoloCounts['Alto'] ?? 0;
$medi = $pericoloCounts['Medio'] ?? 0;
$bassi = $pericoloCounts['Basso'] ?? 0;

function getPericoloClass($pericolo) {
    switch ($pericolo) {
        case 'Critico': return 'critical';
        case 'Alto':    return 'high';
        case 'Medio':   return 'medium';
        default:        return 'low';
    }
}
function getBadgeClass($pericolo) {
    switch ($pericolo) {
        case 'Critico': return 'badge-critical';
        case 'Alto':    return 'badge-high';
        case 'Medio':   return 'badge-medium';
        default:        return 'badge-low';
    }
}
function getStatoBadge($stato) {
    switch ($stato) {
        case 'Bloccato':   return 'badge-blocked';
        case 'Rilevato':   return 'badge-detected';
        case 'Isolato':    return 'badge-isolated';
        case 'Monitorato': return 'badge-monitored';
        default:           return '';
    }
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SecureNet Cloud - Dashboard</title>
    <link rel="stylesheet" href="assets/css/style.css?v=20260716b">
    <link href="../lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" rel="stylesheet">
</head>
<body>

<div class="app-layout">
    <!-- ========== SIDEBAR ========== -->
    <nav class="sidebar" id="sidebar">
        <div class="sidebar-brand">
            <span class="material-symbols-outlined brand-icon">shield</span>
            <h4>SecureNet</h4>
            <span class="brand-sub">Cloud Security</span>
        </div>
        <hr class="sidebar-divider">
        <ul class="sidebar-nav">
            <li><a href="#" class="sidebar-link active" data-section="dashboard">
                <span class="material-symbols-outlined nav-icon">dashboard</span> Dashboard
            </a></li>
            <li><a href="#" class="sidebar-link" data-section="incidents">
                <span class="material-symbols-outlined nav-icon">warning</span> Incidenti
            </a></li>
            <li><a href="#" class="sidebar-link" data-section="ai-consultant">
                <span class="material-symbols-outlined nav-icon">psychology</span> AI Consultant
            </a></li>
        </ul>
        <div class="sidebar-footer">
            <a href="?logout=1" class="sidebar-link logout-link">
                <span class="material-symbols-outlined nav-icon">logout</span> Logout
            </a>
        </div>
    </nav>

    <!-- ========== MAIN CONTENT ========== -->
    <main class="main-content">

        <!-- Top Bar -->
        <header class="top-bar">
            <h2 class="page-title" id="pageTitle">Dashboard</h2>
            <div class="top-bar-info">
                <span class="status-dot"></span>
                <span>Sistema Attivo</span>
            </div>
        </header>

        <!-- ===== SEZIONE 1: DASHBOARD (Panoramica) ===== -->
        <section class="content-section active" id="section-dashboard">

            <!-- Riga cards statistiche -->
            <div class="stats-grid">
                <div class="stat-card stat-card-1">
                    <div class="stat-icon" style="background: rgba(255,107,107,0.16); color: #ff8e8e;">
                        <span class="material-symbols-outlined">crisis_alert</span>
                    </div>
                    <div class="stat-info">
                        <span class="stat-number"><?= $totale ?></span>
                        <span class="stat-label">Incidenti Totali</span>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: rgba(52,201,123,0.16); color: #72d69e;">
                        <span class="material-symbols-outlined">verified_user</span>
                    </div>
                    <div class="stat-info">
                        <span class="stat-number"><?= $bloccati ?></span>
                        <span class="stat-label">Bloccati</span>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: rgba(242,201,76,0.16); color: #f7d56b;">
                        <span class="material-symbols-outlined">report</span>
                    </div>
                    <div class="stat-info">
                        <span class="stat-number"><?= $critici ?></span>
                        <span class="stat-label">Critici</span>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: rgba(119,169,255,0.16); color: #9dc0ff;">
                        <span class="material-symbols-outlined">search</span>
                    </div>
                    <div class="stat-info">
                        <span class="stat-number"><?= $rilevati ?></span>
                        <span class="stat-label">Rilevati</span>
                    </div>
                </div>
            </div>

            <!-- Riga grafico + ultimi incidenti -->
            <div class="dashboard-panels">
                <!-- Grafico -->
                <div class="panel">
                    <div class="panel-header">
                        <h5>Stato Minacce</h5>
                    </div>
                    <div class="panel-body chart-area">
                        <div class="pie-chart" style="background: conic-gradient(
                            #28a745 0% <?= $percentualeBloccati ?>%,
                            #dc3545 <?= $percentualeBloccati ?>% <?= $percentualeBloccati + $percentualeRilevati ?>%,
                            #fd7e14 <?= $percentualeBloccati + $percentualeRilevati ?>% 100%
                        );"></div>
                        <div class="chart-legend">
                            <div class="legend-item"><span class="legend-dot" style="background:#28a745;"></span> Bloccati: <?= $bloccati ?> (<?= $percentualeBloccati ?>%)</div>
                            <div class="legend-item"><span class="legend-dot" style="background:#dc3545;"></span> Rilevati: <?= $rilevati ?></div>
                            <div class="legend-item"><span class="legend-dot" style="background:#fd7e14;"></span> Isolati/Monitorati: <?= $isolati + $monitorati ?></div>
                        </div>
                    </div>
                </div>

                <!-- Ultimi 5 incidenti -->
                <div class="panel">
                    <div class="panel-header">
                        <h5>Ultimi Incidenti</h5>
                        <a href="#" class="panel-link" data-goto="incidents">Vedi tutti &rarr;</a>
                    </div>
                    <div class="panel-body">
                        <div class="mini-incident-list">
                            <?php foreach (array_slice($incidents, 0, 5) as $inc): ?>
                            <div class="mini-incident <?= getPericoloClass($inc['pericolo']) ?>">
                                <div class="mini-incident-left">
                                    <span class="mini-id"><?= $inc['id'] ?></span>
                                    <span class="mini-type"><?= $inc['tipo'] ?></span>
                                </div>
                                <div class="mini-incident-right">
                                    <span class="mini-badge <?= getBadgeClass($inc['pericolo']) ?>"><?= $inc['pericolo'] ?></span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- ===== SEZIONE 2: INCIDENTI (Tabella completa) ===== -->
        <section class="content-section" id="section-incidents">
            <div class="panel">
                <div class="panel-header">
                    <h5>Registro Incidenti</h5>
                    <span class="panel-count"><?= $totale ?> eventi registrati. Clicca su un incidente per il consiglio specifico
</span>
                </div>
                <div class="panel-body table-container">
                    <div class="table-responsive">
                        <table class="incident-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>IP</th>
                                    <th>Tipo Minaccia</th>
                                    <th>Pericolo</th>
                                    <th>Stato</th>
                                    <th>Data/Ora</th>
                                    <th>Azioni</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($incidents as $inc):
                                $rowClass = getPericoloClass($inc['pericolo']);
                            ?>
                                <tr class="incident-row <?= $rowClass ?>" data-id="<?= $inc['id'] ?>" data-tipo="<?= $inc['tipo'] ?>" data-ip="<?= $inc['ip'] ?>">
                                    <td><span class="cell-id"><?= $inc['id'] ?></span></td>
                                    <td><code><?= $inc['ip'] ?></code></td>
                                    <td><?= $inc['tipo'] ?></td>
                                    <td><span class="badge-pill <?= getBadgeClass($inc['pericolo']) ?>"><?= $inc['pericolo'] ?></span></td>
                                    <td><span class="badge-pill <?= getStatoBadge($inc['stato']) ?>"><?= $inc['stato'] ?></span></td>
                                    <td class="cell-date"><?= $inc['data'] ?></td>
                                    <td>
                                        <a href="../backend/api/pdf.php?id=<?= $inc['id'] ?>" class="btn-action" target="_blank" title="Scarica Report PDF">
                                            <span class="material-symbols-outlined" style="font-size:14px;vertical-align:middle;">picture_as_pdf</span> PDF
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </section>

        <!-- ===== SEZIONE 3: AI SECURITY CONSULTANT ===== -->
        <section class="content-section" id="section-ai-consultant">
            <div class="panel">
                <div class="panel-header">
                    <h5>AI Security Consultant</h5>
                </div>
                <div class="panel-body">
                    <p class="ai-description">Inserisci un indirizzo IP per ricevere un'analisi approfondita sulle possibili minacce, la geolocalizzazione e le contromisure consigliate.</p>
                    <div class="ai-input-group">
                        <input type="text" id="ipPrompt" class="ai-input" placeholder="es. 192.168.1.45">
                        <button id="askAiBtn" class="btn-accent">
                            <span class="material-symbols-outlined" style="font-size:18px;vertical-align:middle;">smart_toy</span> Chiedi all'AI
                        </button>
                    </div>
                    <div id="aiResponse" class="ai-response-box" style="display:none;"></div>
                </div>
            </div>

            <!-- Suggerimenti rapidi per tipo di minaccia -->
            <div class="panel">
                <div class="panel-header">
                    <h5>Consigli per Tipo di Minaccia</h5>
                </div>
                <div class="panel-body">
                    <div class="advice-grid">
                        <div class="advice-card">
                            <div class="advice-icon"><span class="material-symbols-outlined">password</span></div>
                            <h6>Brute Force</h6>
                            <p>Attivare 2FA e blocco IP dopo 3 tentativi.</p>
                        </div>
                        <div class="advice-card">
                            <div class="advice-icon"><span class="material-symbols-outlined">database</span></div>
                            <h6>SQL Injection</h6>
                            <p>Utilizzare Prepared Statements (PDO) e sanitizzare gli input.</p>
                        </div>
                        <div class="advice-card">
                            <div class="advice-icon"><span class="material-symbols-outlined">cloud_off</span></div>
                            <h6>DDoS Attack</h6>
                            <p>Attivare protezione DDoS e limitare il traffico sospetto.</p>
                        </div>
                        <div class="advice-card">
                            <div class="advice-icon"><span class="material-symbols-outlined">phishing</span></div>
                            <h6>Phishing</h6>
                            <p>Resettare le credenziali dell'utente e formare il personale.</p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

    </main>
</div>

<!-- Modale Consiglio AI (cliccando sulla riga incidente) -->
<div class="modal fade" id="adviceModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content modal-custom">
      <div class="modal-header">
        <h5 class="modal-title"><span class="material-symbols-outlined" style="vertical-align:middle;">shield</span> Consiglio AI</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="adviceText"></div>
    </div>
  </div>
</div>

<script src="../lib/gsap/gsap.min.js"></script>
<script src="../lib/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/animations.js"></script>
<script src="assets/js/app.js"></script>
</body>
</html>