<?php
/**
 * USER MANAGER v4.0 - SuperAdmin Panel
 */
ob_start();

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';
require_once '../includes/email.php';

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

// Check autenticazione
if (!$session->isLoggedIn()) {
    redirect(BASE_URL . '/login.php');
}

// Check superadmin
if (!$session->isSuperAdmin()) {
    $session->logout();
    redirect(BASE_URL . '/login.php');
}

$user_name = $session->getFullName();
$user_email = $session->getEmail();
$page = $_GET['page'] ?? 'dashboard';
$success = $session->getFlash('success');
$error = $session->getFlash('error');

// ============================================================================
// ACTIONS HANDLER
// ============================================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'create_user':
            // Crea nuovo user
            $first_name = sanitize_string($_POST['first_name'] ?? '');
            $last_name = sanitize_string($_POST['last_name'] ?? '');
            $user_email_new = sanitize_email($_POST['email'] ?? '');
            $phone = sanitize_string($_POST['phone'] ?? '');
            $role = $_POST['role'] ?? 'user';
            $password = $_POST['password'] ?? '';
            
            if (!$first_name || !$last_name || !$user_email_new || !validate_role($role)) {
                $session->setFlash('error', 'Tutti i campi obbligatori devono essere compilati');
            } else {
                // Genera password se vuota
                if (empty($password)) {
                    $password = generate_token(14);
                    // Assicura policy
                    if (!preg_match('/[A-Z]/', $password)) $password = 'A' . $password;
                    if (!preg_match('/[a-z]/', $password)) $password .= 'a';
                    if (!preg_match('/[0-9]/', $password)) $password .= '1';
                    if (!preg_match('/[^A-Za-z0-9]/', $password)) $password .= '!';
                }
                
                $password_plain = $password;
                $password_hash = hash_password($password);
                
                // Max devices per ruolo
                $max_devices = match($role) {
                    'superadmin' => 999,
                    'admin' => 3,
                    'user' => 6,
                    default => 3
                };
                
                // Allowed device types
                $allowed_types = match($role) {
                    'superadmin' => 'desktop,laptop,mobile,tablet',
                    'admin' => 'desktop,laptop',
                    'user' => 'desktop,laptop,mobile,tablet',
                    default => 'desktop,laptop'
                };
                
                try {
                    $user_id = $db->insert('users', [
                        'first_name' => $first_name,
                        'last_name' => $last_name,
                        'email' => $user_email_new,
                        'phone' => $phone ?: null,
                        'password_hash' => $password_hash,
                        'role' => $role,
                        'status' => 'active',
                        'max_devices' => $max_devices,
                        'allowed_device_types' => $allowed_types,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => $session->getEmail()
                    ]);
                    
                    // Invia email benvenuto
                    $new_user = [
                        'id' => $user_id,
                        'first_name' => $first_name,
                        'last_name' => $last_name,
                        'email' => $user_email_new
                    ];
                    
                    $email->sendWelcomeWithSetup($new_user, $password_plain, []);
                    
                    // Audit log
                    $db->insert('audit_log', [
                        'user_id' => $user_id,
                        'action' => 'user_created',
                        'ip_address' => get_client_ip(),
                        'user_agent' => get_user_agent(),
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    $session->setFlash('success', "User creato! Email inviata a $user_email_new");
                    redirect(BASE_URL . '/superadmin_panel.php?page=users');
                    
                } catch (Exception $e) {
                    $session->setFlash('error', 'Errore creazione user: email già esistente?');
                }
            }
            break;
            
        case 'reset_password':
            $user_id = (int)$_POST['user_id'];
            
            // Genera nuova password
            $new_password = generate_token(14);
            if (!preg_match('/[A-Z]/', $new_password)) $new_password = 'A' . $new_password;
            if (!preg_match('/[a-z]/', $new_password)) $new_password .= 'a';
            if (!preg_match('/[0-9]/', $new_password)) $new_password .= '1';
            if (!preg_match('/[^A-Za-z0-9]/', $new_password)) $new_password .= '!';
            
            $password_hash = hash_password($new_password);
            
            $db->update('users', ['password_hash' => $password_hash], ['id' => $user_id]);
            
            $db->select('users', ['id' => $user_id]);
            $user = $db->fetch();
            
            $email->sendPasswordReset($user, $new_password);
            
            $session->setFlash('success', "Password reimpostata! Email inviata a {$user['email']}");
            redirect(BASE_URL . '/superadmin_panel.php?page=users');
            break;
            
        case 'delete_user':
            $user_id = (int)$_POST['user_id'];
            $db->delete('users', ['id' => $user_id]);
            $session->setFlash('success', 'User eliminato!');
            redirect(BASE_URL . '/superadmin_panel.php?page=users');
            break;
    }
}

// Stats
$db->query("SELECT COUNT(*) as total FROM users");
$total_users = $db->fetch()['total'];

$db->query("SELECT COUNT(*) as total FROM devices");
$total_devices = $db->fetch()['total'];

$db->query("SELECT COUNT(*) as total FROM devices WHERE status = 'active'");
$active_devices = $db->fetch()['total'];

$db->query("SELECT COUNT(*) as total FROM devices WHERE status = 'pending'");
$pending_devices = $db->fetch()['total'];

?>
<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SuperAdmin Panel</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #f5f7fa; color: #333; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header-content { max-width: 1400px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; }
        .logo h1 { font-size: 24px; font-weight: 600; }
        .user-info { display: flex; align-items: center; gap: 20px; }
        .btn-logout { background: rgba(255,255,255,0.2); color: white; border: none; padding: 8px 20px; border-radius: 5px; text-decoration: none; }
        .container { max-width: 1400px; margin: 0 auto; padding: 30px 20px; }
        .nav-tabs { background: white; border-radius: 10px; padding: 15px; margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); display: flex; gap: 10px; flex-wrap: wrap; }
        .nav-tab { padding: 12px 24px; background: #f5f7fa; border: none; border-radius: 8px; cursor: pointer; font-size: 15px; color: #666; text-decoration: none; transition: all 0.3s; }
        .nav-tab:hover { background: #e0e7ff; color: #667eea; }
        .nav-tab.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
        .alert-success { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
        .alert-error { background: #f8d7da; color: #721c24; border-left: 4px solid #dc3545; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .stat-card { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .stat-icon { font-size: 40px; margin-bottom: 10px; }
        .stat-value { font-size: 32px; font-weight: 600; color: #667eea; margin: 10px 0; }
        .stat-label { color: #666; font-size: 14px; }
        .content-box { background: white; border-radius: 10px; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .content-box h2 { margin-bottom: 20px; color: #333; }
        .table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .table th { background: #f8f9fa; padding: 12px; text-align: left; font-weight: 600; color: #666; border-bottom: 2px solid #dee2e6; }
        .table td { padding: 12px; border-bottom: 1px solid #dee2e6; }
        .table tr:hover { background: #f8f9fa; }
        .badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; }
        .badge-superadmin { background: #ff6b6b; color: white; }
        .badge-admin { background: #4ecdc4; color: white; }
        .badge-user { background: #95e1d3; color: #333; }
        .badge-active { background: #51cf66; color: white; }
        .badge-pending { background: #ffd43b; color: #333; }
        .btn { padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; text-decoration: none; display: inline-block; transition: all 0.3s; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-primary:hover { transform: translateY(-2px); }
        .btn-danger { background: #ff6b6b; color: white; }
        .btn-warning { background: #ffd43b; color: #333; }
        .btn-sm { padding: 6px 12px; font-size: 12px; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: 500; color: #555; }
        .form-control { width: 100%; padding: 10px; border: 2px solid #e0e7ff; border-radius: 6px; font-size: 14px; }
        .form-control:focus { outline: none; border-color: #667eea; }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <div class="logo">
                <h1>🔐 User Manager v4.0</h1>
                <small>SuperAdmin Panel</small>
            </div>
            <div class="user-info">
                <div>
                    <strong><?= htmlspecialchars($user_name) ?></strong><br>
                    <small><?= htmlspecialchars($user_email) ?></small>
                </div>
                <a href="logout.php" class="btn-logout">🚪 Logout</a>
            </div>
        </div>
    </div>
    
    <div class="container">
        <?php if ($success): ?>
            <div class="alert alert-success">✅ <?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-error">⚠️ <?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <div class="nav-tabs">
            <a href="?page=dashboard" class="nav-tab <?= $page === 'dashboard' ? 'active' : '' ?>">📊 Dashboard</a>
            <a href="?page=users" class="nav-tab <?= $page === 'users' ? 'active' : '' ?>">👥 Users</a>
            <a href="?page=security" class="nav-tab <?= $page === 'security' ? 'active' : '' ?>">🔒 Sicurezza</a>
            <a href="?page=devices" class="nav-tab <?= $page === 'devices' ? 'active' : '' ?>">📱 Devices</a>
        </div>
        
        <?php
        $page_file = __DIR__ . '/pages/' . $page . '.php';
        if (file_exists($page_file)) {
            include $page_file;
        } else {
            include __DIR__ . '/pages/dashboard.php';
        }
        ?>
    </div>
</body>
</html>
