<?php
/**
 * Estreka Ratsaklubi - Kasutajate haldamise süsteem
 * 🔧 PARANDATUD versioon - kõik funktsioonid töötavad
 */

require_once '../config/config.php';
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// PDO seaded
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Nõua admin õigusi
requireAdmin();

$error = '';
$success = '';

// ===============================
// 🔧 PARANDATUD: CSV EXPORT FUNKTSIOON
// ===============================
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    try {
        // Lae kasutajad
        $stmt = $pdo->prepare("
            SELECT 
                u.id, u.firstName, u.lastName, u.email, u.username, 
                u.role, u.isActive, u.email_verified, u.birthDate, u.createdAt,
                COUNT(r.id) as total_results
            FROM users u
            LEFT JOIN results r ON u.id = r.userId
            GROUP BY u.id
            ORDER BY u.createdAt DESC
        ");
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // CSV header
        $filename = "estreka_kasutajad_" . date('Y-m-d_H-i-s') . ".csv";
        
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        
        // BOM UTF-8 jaoks (Excel toetus)
        echo "\xEF\xBB\xBF";
        
        $output = fopen('php://output', 'w');
        
        // CSV header
        fputcsv($output, [
            'ID', 'Eesnimi', 'Perenimi', 'Email', 'Kasutajanimi', 
            'Roll', 'Staatus', 'Email kinnitatud', 'Sünniaeg', 'Registreeritud', 'Tulemusi'
        ], ';'); // Kasutame semikoolonit Estonian Excel'i jaoks
        
        // CSV data
        foreach ($users as $user) {
            fputcsv($output, [
                $user['id'],
                $user['firstName'],
                $user['lastName'],
                $user['email'],
                $user['username'],
                $user['role'] === 'admin' ? 'Administraator' : 'Sportlane',
                $user['isActive'] ? 'Aktiivne' : 'Mitteaktiivne',
                $user['email_verified'] ? 'Jah' : 'Ei',
                formatDate($user['birthDate']),
                formatDate($user['createdAt']),
                $user['total_results']
            ], ';');
        }
        
        fclose($output);
        exit;
        
    } catch (Exception $e) {
        $error = 'CSV eksport ebaõnnestus: ' . $e->getMessage();
        error_log('CSV export error: ' . $e->getMessage());
    }
}

// ===============================
// 🔧 PARANDATUD: KASUTAJA LISAMINE/MUUTMINE
// ===============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_user'])) {
    $user_id = getPost('user_id');
    $firstName = getPost('firstName');
    $lastName = getPost('lastName');
    $email = getPost('email');
    $phone = getPost('phone');
    $birthDate = getPost('birthDate');
    $username = getPost('username');
    $password = getPost('password');
    $role = getPost('role');
    $isActive = isset($_POST['isActive']) ? 1 : 0;
    
    if (empty($firstName) || empty($lastName) || empty($email) || empty($username) || empty($role) || empty($birthDate)) {
        $error = 'Kõik kohustuslikud väljad peavad olema täidetud';
    } elseif ($user_id && empty($password)) {
        // Muudame olemasolevat kasutajat ILMA parooli muutmata
        try {
            $stmt = $pdo->prepare("
                UPDATE users SET 
                    firstName = ?, lastName = ?, email = ?, phone = ?, 
                    birthDate = ?, username = ?, role = ?, isActive = ?, 
                    updatedAt = CURRENT_TIMESTAMP 
                WHERE id = ?
            ");
            $stmt->execute([
                $firstName, $lastName, $email, $phone, 
                $birthDate, $username, $role, $isActive, $user_id
            ]);
            
            $success = 'Kasutaja andmed edukalt uuendatud!';
            logActivity($_SESSION['user_id'], 'user_updated', "User $username updated");
            
        } catch(PDOException $e) {
            if (strpos($e->getMessage(), 'UNIQUE constraint failed') !== false) {
                $error = 'E-mail või kasutajanimi on juba kasutusel';
            } else {
                $error = 'Kasutaja uuendamine ebaõnnestus: ' . $e->getMessage();
            }
        }
    } elseif ($user_id && !empty($password)) {
        // Muudame olemasolevat kasutajat KOOS parooli muutmisega
        if (strlen($password) < 6) {
            $error = 'Parool peab olema vähemalt 6 tähemärki pikk';
        } else {
            try {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("
                    UPDATE users SET 
                        firstName = ?, lastName = ?, email = ?, phone = ?, 
                        birthDate = ?, username = ?, password = ?, role = ?, isActive = ?, 
                        updatedAt = CURRENT_TIMESTAMP 
                    WHERE id = ?
                ");
                $stmt->execute([
                    $firstName, $lastName, $email, $phone, 
                    $birthDate, $username, $hashedPassword, $role, $isActive, $user_id
                ]);
                
                $success = 'Kasutaja andmed ja parool edukalt uuendatud!';
                logActivity($_SESSION['user_id'], 'user_updated', "User $username updated with new password");
                
            } catch(PDOException $e) {
                if (strpos($e->getMessage(), 'UNIQUE constraint failed') !== false) {
                    $error = 'E-mail või kasutajanimi on juba kasutusel';
                } else {
                    $error = 'Kasutaja uuendamine ebaõnnestus: ' . $e->getMessage();
                }
            }
        }
    } else {
        // Lisame UUE kasutaja - parool on KOHUSTUSLIK
        if (empty($password)) {
            $error = 'Uue kasutaja puhul on parool kohustuslik';
        } elseif (strlen($password) < 6) {
            $error = 'Parool peab olema vähemalt 6 tähemärki pikk';
        } else {
            try {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("
                    INSERT INTO users (firstName, lastName, email, phone, birthDate, username, password, role, isActive)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $firstName, $lastName, $email, $phone, 
                    $birthDate, $username, $hashedPassword, $role, $isActive
                ]);
                
                $success = 'Uus kasutaja edukalt lisatud!';
                logActivity($_SESSION['user_id'], 'user_created', "User $username created");
                
            } catch(PDOException $e) {
                if (strpos($e->getMessage(), 'UNIQUE constraint failed') !== false) {
                    $error = 'E-mail või kasutajanimi on juba kasutusel';
                } else {
                    $error = 'Kasutaja lisamine ebaõnnestus: ' . $e->getMessage();
                }
            }
        }
    }
}

// ===============================
// KASUTAJA STAATUSE MUUTMINE
// ===============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_user_status'])) {
    $user_id = getPost('user_id');
    $new_status = getPost('new_status') === 'true' ? 1 : 0;
    
    if ($user_id == $_SESSION['user_id']) {
        $error = 'Sa ei saa muuta enda staatust';
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE users SET isActive = ?, updatedAt = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$new_status, $user_id]);
            
            $status_text = $new_status ? 'aktiveeritud' : 'deaktiveeritud';
            $success = "Kasutaja edukalt $status_text!";
            logActivity($_SESSION['user_id'], 'user_status_changed', "User status changed (ID: $user_id) to " . ($new_status ? 'active' : 'inactive'));
            
        } catch(PDOException $e) {
            $error = 'Staatuse muutmine ebaõnnestus: ' . $e->getMessage();
        }
    }
}

// ===============================
// EMAIL KINNITAMINE (ADMIN)
// ===============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_user_email'])) {
    $user_id = getPost('user_id');
    
    try {
        // Kontrolli kas kasutaja eksisteerib ja email on kinnitamata
        $stmt = $pdo->prepare("SELECT id, firstName, lastName, email, email_verified FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            $error = 'Kasutajat ei leitud';
        } elseif ($user['email_verified']) {
            $error = 'Kasutaja email on juba kinnitatud';
        } else {
            // Kinnita email
            $stmt = $pdo->prepare("
                UPDATE users 
                SET email_verified = 1, 
                    isActive = 1, 
                    verification_token = NULL, 
                    verification_expires = NULL,
                    updatedAt = CURRENT_TIMESTAMP
                WHERE id = ?
            ");
            $stmt->execute([$user_id]);
            
            $success = "Kasutaja {$user['firstName']} {$user['lastName']} email edukalt kinnitatud!";
            logActivity($_SESSION['user_id'], 'admin_email_verified', "Admin verified email for user ID: $user_id ({$user['email']})");
        }
        
    } catch(PDOException $e) {
        $error = 'Email kinnitamine ebaõnnestus: ' . $e->getMessage();
        error_log('Admin email verification error: ' . $e->getMessage());
    }
}

// ===============================
// KASUTAJA KUSTUTAMINE
// ===============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_user'])) {
    $user_id = getPost('user_id');
    
    if ($user_id == $_SESSION['user_id']) {
        $error = 'Sa ei saa kustutada iseenda kontot';
    } else {
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM results WHERE userId = ?");
            $stmt->execute([$user_id]);
            $results_count = $stmt->fetch()['count'];
            
            if ($results_count > 0) {
                $error = "Kasutajat ei saa kustutada, kuna tal on $results_count tulemust. Deaktiveeri kasutaja selle asemel.";
            } else {
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $success = 'Kasutaja edukalt kustutatud!';
                logActivity($_SESSION['user_id'], 'user_deleted', "User deleted (ID: $user_id)");
            }
            
        } catch(PDOException $e) {
            $error = 'Kasutaja kustutamine ebaõnnestus: ' . $e->getMessage();
        }
    }
}

// ===============================
// BULK ACTIONS
// ===============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    $action = getPost('bulk_action');
    $selected_users = $_POST['selected_users'] ?? [];
    
    if (empty($selected_users)) {
        $error = 'Palun vali vähemalt üks kasutaja';
    } else {
        $user_count = count($selected_users);
        $placeholders = str_repeat('?,', $user_count - 1) . '?';
        
        try {
            switch ($action) {
                case 'activate':
                    $stmt = $pdo->prepare("UPDATE users SET isActive = 1, updatedAt = CURRENT_TIMESTAMP WHERE id IN ($placeholders)");
                    $stmt->execute($selected_users);
                    $success = "$user_count kasutajat aktiveeritud";
                    break;
                    
                case 'deactivate':
                    $stmt = $pdo->prepare("UPDATE users SET isActive = 0, updatedAt = CURRENT_TIMESTAMP WHERE id IN ($placeholders)");
                    $stmt->execute($selected_users);
                    $success = "$user_count kasutajat deaktiveeritud";
                    break;
                    
                case 'delete':
                    if (in_array($_SESSION['user_id'], $selected_users)) {
                        throw new Exception('Sa ei saa kustutada iseenda kontot');
                    }
                    $stmt = $pdo->prepare("DELETE FROM users WHERE id IN ($placeholders)");
                    $stmt->execute($selected_users);
                    $success = "$user_count kasutajat kustutatud";
                    break;
                    
                case 'reset_password':
                    $new_password = bin2hex(random_bytes(8));
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("UPDATE users SET password = ?, updatedAt = CURRENT_TIMESTAMP WHERE id IN ($placeholders)");
                    $stmt->execute(array_merge([$hashed_password], $selected_users));
                    $success = "$user_count kasutaja parool lähtestatud. Uus parool: $new_password";
                    break;
            }
            
            logActivity($_SESSION['user_id'], 'bulk_action', "Bulk $action for $user_count users");
            
        } catch(Exception $e) {
            $error = 'Mastoiming ebaõnnestus: ' . $e->getMessage();
        }
    }
}

// ===============================
// QUICK ADD USER
// ===============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quick_add_user'])) {
    $email = trim($_POST['email']);
    $firstName = trim($_POST['firstName']);
    $lastName = trim($_POST['lastName']);
    $role = trim($_POST['role']);
    
    if (empty($email) || empty($firstName) || empty($lastName) || empty($role)) {
        $error = 'Kõik väljad on kohustuslikud';
    } else {
        try {
            $username = strtolower($firstName . '.' . $lastName . rand(10, 99));
            $tempPassword = bin2hex(random_bytes(6));
            $hashedPassword = password_hash($tempPassword, PASSWORD_DEFAULT);
            $defaultBirthDate = date('Y-m-d', strtotime('-25 years'));
            
            $stmt = $pdo->prepare("
                INSERT INTO users (firstName, lastName, email, username, password, role, birthDate, isActive)
                VALUES (?, ?, ?, ?, ?, ?, ?, 1)
            ");
            $stmt->execute([$firstName, $lastName, $email, $username, $hashedPassword, $role, $defaultBirthDate]);
            
            $success = "Kasutaja edukalt lisatud! Kasutajanimi: $username, Ajutine parool: $tempPassword";
            logActivity($_SESSION['user_id'], 'user_quick_added', "Quick add: $username");
            
        } catch(PDOException $e) {
            if (strpos($e->getMessage(), 'UNIQUE constraint failed') !== false) {
                $error = 'E-mail on juba kasutusel';
            } else {
                $error = 'Kasutaja lisamine ebaõnnestus: ' . $e->getMessage();
            }
        }
    }
}

// ===============================
// FILTRID
// ===============================
$search_query = getGet('search', '');
$role_filter = getGet('role', '');
$status_filter = getGet('status', '');
$email_filter = getGet('email_status', '');
$registration_from = getGet('reg_from', '');
$registration_to = getGet('reg_to', '');

// ===============================
// KASUTAJATE STATISTIKA
// ===============================
try {
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN isActive = 1 THEN 1 ELSE 0 END) as active,
            SUM(CASE WHEN isActive = 0 THEN 1 ELSE 0 END) as inactive,
            SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admins,
            SUM(CASE WHEN role = 'athlete' THEN 1 ELSE 0 END) as athletes,
            SUM(CASE WHEN email_verified = 1 THEN 1 ELSE 0 END) as email_verified,
            SUM(CASE WHEN email_verified = 0 THEN 1 ELSE 0 END) as email_unverified
        FROM users
    ");
    $stmt->execute();
    $user_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch(Exception $e) {
    error_log('User stats error: ' . $e->getMessage());
    $user_stats = ['total' => 0, 'active' => 0, 'inactive' => 0, 'admins' => 0, 'athletes' => 0, 'email_verified' => 0, 'email_unverified' => 0];
}

// ===============================
// KASUTAJATE LAADIMINE
// ===============================
$where_conditions = ['1=1'];
$params = [];

if (!empty($search_query)) {
    $where_conditions[] = "(firstName LIKE ? OR lastName LIKE ? OR email LIKE ? OR username LIKE ?)";
    $search_param = "%$search_query%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
}

if (!empty($role_filter)) {
    $where_conditions[] = "role = ?";
    $params[] = $role_filter;
}

if (!empty($status_filter)) {
    $where_conditions[] = "isActive = ?";
    $params[] = ($status_filter === 'active') ? 1 : 0;
}

if (!empty($email_filter)) {
    $where_conditions[] = "email_verified = ?";
    $params[] = ($email_filter === 'verified') ? 1 : 0;
}

if (!empty($registration_from)) {
    $where_conditions[] = "DATE(createdAt) >= ?";
    $params[] = $registration_from;
}

if (!empty($registration_to)) {
    $where_conditions[] = "DATE(createdAt) <= ?";
    $params[] = $registration_to;
}

$where_clause = implode(' AND ', $where_conditions);

try {
    $stmt = $pdo->prepare("
        SELECT DISTINCT
            u.id, u.firstName, u.lastName, u.email, u.username,
            u.role, u.isActive, u.email_verified, u.birthDate, u.createdAt, u.updatedAt,
            COALESCE(JULIANDAY('now') - JULIANDAY(u.createdAt), 0) as days_since_registration,
            COUNT(r.id) as total_results
        FROM users u
        LEFT JOIN results r ON u.id = r.userId
        WHERE $where_clause
        GROUP BY u.id
        ORDER BY u.createdAt DESC
    ");
    $stmt->execute($params);
    $users_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    $error = 'Kasutajate laadimine ebaõnnestus: ' . $e->getMessage();
    error_log('Users load error: ' . $e->getMessage());
    $users_list = [];
}

$page_title = 'Admin - Kasutajate haldamine';
$page_description = 'Kasutajate haldamise süsteem.';

$extra_head_content = '<link rel="stylesheet" href="' . url('assets/css/admin-users.css') . '">';

include '../includes/header.php';

?>

<main class="admin-users-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">
                    <i class="icon-users"></i>
                    Kasutajate haldamine
                </h1>
                <p class="page-subtitle">Halda kasutajaid ja nende õigusi</p>
            </div>
            <div class="page-actions">
                <a href="?export=csv" class="btn btn-outline" title="Ekspordi kasutajad CSV-na">
                    <i class="icon-download"></i>
                    <span>Eksport</span>
                </a>
                <button onclick="openUserModal()" class="btn btn-primary" title="Lisa uus kasutaja">
                    <i class="icon-user-plus"></i>
                    <span>Lisa kasutaja</span>
                </button>
            </div>
        </div>

        <!-- Alerts -->
        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="icon-alert-circle"></i>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="icon-check-circle"></i>
                <span><?php echo htmlspecialchars($success); ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistics Dashboard -->
        <div class="stats-dashboard">
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon primary">
                        <i class="icon-users"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $user_stats['total']; ?></div>
                        <div class="stat-label">Kokku kasutajaid</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon success">
                        <i class="icon-user-check"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $user_stats['active']; ?></div>
                        <div class="stat-label">Aktiivsed</div>
                        <div class="stat-percentage">
                            <?php echo $user_stats['total'] > 0 ? round(($user_stats['active'] / $user_stats['total']) * 100) : 0; ?>%
                        </div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon warning">
                        <i class="icon-award"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $user_stats['athletes']; ?></div>
                        <div class="stat-label">Sportlased</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon info">
                        <i class="icon-shield"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $user_stats['admins']; ?></div>
                        <div class="stat-label">Administraatorid</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon success">
                        <i class="icon-mail-check"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $user_stats['email_verified']; ?></div>
                        <div class="stat-label">Email kinnitatud</div>
                        <div class="stat-percentage">
                            <?php echo $user_stats['total'] > 0 ? round(($user_stats['email_verified'] / $user_stats['total']) * 100) : 0; ?>%
                        </div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon danger">
                        <i class="icon-mail-x"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $user_stats['email_unverified']; ?></div>
                        <div class="stat-label">Email kinnitamata</div>
                        <div class="stat-percentage">
                            <?php echo $user_stats['total'] > 0 ? round(($user_stats['email_unverified'] / $user_stats['total']) * 100) : 0; ?>%
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Advanced Search & Filters -->
        <div class="advanced-filters">
            <div class="filters-header">
                <h3>
                    <i class="icon-filter"></i>
                    Otsing ja filtrid
                </h3>
                <button onclick="toggleAdvancedFilters()" class="btn-toggle" id="filterToggle">
                    <i class="icon-chevron-down"></i>
                </button>
            </div>
            
            <form method="GET" class="filters-form" id="advancedFilters">
                <div class="filters-row">
                    <div class="filter-group">
                        <label>Üldine otsing</label>
                        <input type="text" name="search" placeholder="Nimi, email, kasutajanimi..." 
                               value="<?php echo htmlspecialchars($search_query); ?>" class="filter-input">
                    </div>
                    
                    <div class="filter-group">
                        <label>Roll</label>
                        <select name="role" class="filter-select">
                            <option value="">Kõik rollid</option>
                            <option value="athlete" <?php echo $role_filter === 'athlete' ? 'selected' : ''; ?>>Sportlane</option>
                            <option value="admin" <?php echo $role_filter === 'admin' ? 'selected' : ''; ?>>Admin</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label>Staatus</label>
                        <select name="status" class="filter-select">
                            <option value="">Kõik staatused</option>
                            <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Aktiivne</option>
                            <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Mitteaktiivne</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label>Email kinnitamine</label>
                        <select name="email_status" class="filter-select">
                            <option value="">Kõik emailid</option>
                            <option value="verified" <?php echo $email_filter === 'verified' ? 'selected' : ''; ?>>Kinnitatud</option>
                            <option value="unverified" <?php echo $email_filter === 'unverified' ? 'selected' : ''; ?>>Kinnitamata</option>
                        </select>
                    </div>
                </div>
                
                <div class="filters-row advanced">
                    <div class="filter-group">
                        <label>Registreeritud alates</label>
                        <input type="date" name="reg_from" value="<?php echo $registration_from; ?>" class="filter-input">
                    </div>
                    
                    <div class="filter-group">
                        <label>Registreeritud kuni</label>
                        <input type="date" name="reg_to" value="<?php echo $registration_to; ?>" class="filter-input">
                    </div>
                    
                    <div class="filter-group">
                        <label>&nbsp;</label>
                        <a href="<?php echo url('admin/users.php'); ?>" class="btn btn-outline">
                            <i class="icon-x"></i>
                            Lähtesta
                        </a>
                    </div>
                </div>
                
                <div class="filters-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="icon-search"></i>
                        Otsi
                    </button>
                </div>
            </form>
        </div>

        <!-- Users Table -->
        <div class="users-table-container">
            <div class="table-header">
                <div class="table-title">
                    <h3>Kasutajate nimekiri (<?php echo count($users_list); ?>)</h3>
                </div>
            </div>
            
            <?php if (empty($users_list)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="icon-users"></i>
                    </div>
                    <h3>Kasutajaid ei leitud</h3>
                    <p>Proovi muuta otsingukriteeriumeid või lisa uus kasutaja.</p>
                </div>
            <?php else: ?>
                <div class="table-wrapper">
                    <table class="users-table">
                        <thead>
                            <tr>
                                <th>Kasutaja</th>
                                <th>Roll & Staatus</th>
                                <th>Email</th>
                                <th>Tulemused</th>
                                <th>Registreeritud</th>
                                <th>Toimingud</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users_list as $user): ?>
                                <tr class="user-row <?php echo !$user['isActive'] ? 'inactive' : ''; ?>"
                                    onclick="editUserDirectly(this)"
                                    data-user-id="<?php echo $user['id']; ?>"
                                    data-first-name="<?php echo htmlspecialchars($user['firstName']); ?>"
                                    data-last-name="<?php echo htmlspecialchars($user['lastName']); ?>"
                                    data-email="<?php echo htmlspecialchars($user['email']); ?>"
                                    data-phone="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                    data-birth-date="<?php echo $user['birthDate']; ?>"
                                    data-username="<?php echo htmlspecialchars($user['username']); ?>"
                                    data-role="<?php echo $user['role']; ?>"
                                    data-is-active="<?php echo $user['isActive']; ?>">
                                    
                                    <td class="user-info">
                                        <div class="user-details" data-initial="<?php echo strtoupper(substr($user['firstName'], 0, 1)); ?>">
                                            <div class="user-name mobile-clickable">
                                                <?php echo htmlspecialchars($user['firstName'] . ' ' . $user['lastName']); ?>
                                            </div>
                                            <div class="user-meta">
                                                <span class="email"><?php echo htmlspecialchars($user['email']); ?></span>
                                                <span class="username">@<?php echo htmlspecialchars($user['username']); ?></span>
                                            </div>
                                        </div>
                                    </td>
                                    
                                    <td class="role-status">
                                        <div class="role-badge <?php echo $user['role']; ?>">
                                            <?php echo $user['role'] === 'admin' ? 'Admin' : 'Sportlane'; ?>
                                        </div>
                                        <div class="status-badge <?php echo $user['isActive'] ? 'active' : 'inactive'; ?>">
                                            <?php echo $user['isActive'] ? 'Aktiivne' : 'Mitteaktiivne'; ?>
                                        </div>
                                    </td>
                                    
                                    <td class="email-status">
                                        <div class="email-verification <?php echo $user['email_verified'] ? 'verified' : 'unverified'; ?>">
                                            <i class="icon-<?php echo $user['email_verified'] ? 'mail-check' : 'mail-x'; ?>"></i>
                                            <?php echo $user['email_verified'] ? 'Kinnitatud' : 'Kinnitamata'; ?>
                                        </div>
                                    </td>
                                    
                                    <td class="results-summary">
                                        <div class="results-total"><?php echo $user['total_results']; ?> tulemust</div>
                                    </td>
                                    
                                    <td class="registration-date">
                                        <?php echo formatDate($user['createdAt']); ?>
                                        <div class="days-ago"><?php echo round($user['days_since_registration']); ?> päeva tagasi</div>
                                    </td>
                                    
                                    <td class="actions">
                                        <div class="action-buttons">
                                            <button type="button" 
                                                    onclick="event.stopPropagation(); editUserDirectly(this);" 
                                                    class="btn-icon btn-primary" 
                                                    title="Muuda kasutajat"
                                                    data-user-id="<?php echo $user['id']; ?>"
                                                    data-first-name="<?php echo htmlspecialchars($user['firstName']); ?>"
                                                    data-last-name="<?php echo htmlspecialchars($user['lastName']); ?>"
                                                    data-email="<?php echo htmlspecialchars($user['email']); ?>"
                                                    data-phone="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                                    data-birth-date="<?php echo $user['birthDate']; ?>"
                                                    data-username="<?php echo htmlspecialchars($user['username']); ?>"
                                                    data-role="<?php echo $user['role']; ?>"
                                                    data-is-active="<?php echo $user['isActive']; ?>">
                                                <i class="icon-edit"></i>
                                            </button>
                                            
                                            <?php if (!$user['email_verified']): ?>
                                                <button type="button"
                                                        onclick="event.stopPropagation(); verifyUserEmail(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['firstName'] . ' ' . $user['lastName']); ?>');" 
                                                        class="btn-icon btn-success" 
                                                        title="Kinnita email">
                                                    <i class="icon-mail-check"></i>
                                                </button>
                                            <?php endif; ?>
                                            
                                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                <button type="button"
                                                        onclick="event.stopPropagation(); toggleUserStatus(<?php echo $user['id']; ?>, <?php echo $user['isActive'] ? 'false' : 'true'; ?>);" 
                                                        class="btn-icon <?php echo $user['isActive'] ? 'btn-warning' : 'btn-success'; ?>" 
                                                        title="<?php echo $user['isActive'] ? 'Deaktiveeri' : 'Aktiveeri'; ?>">
                                                    <i class="icon-<?php echo $user['isActive'] ? 'eye-off' : 'eye'; ?>"></i>
                                                </button>
                                                
                                                <button type="button"
                                                        onclick="event.stopPropagation(); deleteUser(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['firstName'] . ' ' . $user['lastName']); ?>');" 
                                                        class="btn-icon btn-danger" title="Kustuta kasutaja">
                                                    <i class="icon-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- 🔧 PARANDATUD: User Modal - MOBILE OPTIMIZED -->
        <div id="userModal" class="modal">
            <div class="modal-overlay">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 id="modalTitle">Lisa kasutaja</h3>
                        <button class="modal-close" onclick="closeModal('userModal')">
                            <i class="icon-x"></i>
                        </button>
                    </div>
                    
                    <form method="POST" class="modal-form" id="userForm">
                        <input type="hidden" name="user_id" id="user_id">
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label>Eesnimi *</label>
                                <input type="text" name="firstName" id="firstName" required class="form-input">
                            </div>
                            <div class="form-group">
                                <label>Perenimi *</label>
                                <input type="text" name="lastName" id="lastName" required class="form-input">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>E-mail *</label>
                            <input type="email" name="email" id="email" required class="form-input">
                        </div>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label>Telefon</label>
                                <input type="text" name="phone" id="phone" class="form-input">
                            </div>
                            <div class="form-group">
                                <label>Sünniaeg *</label>
                                <input type="date" name="birthDate" id="birthDate" required class="form-input">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Kasutajanimi *</label>
                            <input type="text" name="username" id="username" required class="form-input">
                        </div>
                        
                        <div class="form-group">
                            <label>Parool <span id="passwordRequired">*</span></label>
                            <input type="password" name="password" id="password" required class="form-input">
                            <div class="form-help" id="passwordHelp">Vähemalt 6 tähemärki</div>
                        </div>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label>Roll *</label>
                                <select name="role" id="role" required class="form-select">
                                    <option value="">Vali roll</option>
                                    <option value="athlete">Sportlane</option>
                                    <option value="admin">Administraator</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" name="isActive" id="isActive" class="checkbox-input" checked>
                                    <span class="checkbox-custom"></span>
                                    <span class="checkbox-text">Kasutaja on aktiivne</span>
                                </label>
                            </div>
                        </div>
                        
                        <!-- 🔧 MOBILE ACTION BUTTONS SECTION -->
                        <div class="modal-actions">
                            <!-- Main actions -->
                            <div class="primary-actions">
                                <button type="button" onclick="closeModal('userModal')" class="btn btn-secondary">
                                    Tühista
                                </button>
                                <button type="submit" name="save_user" class="btn btn-primary">
                                    <i class="icon-save"></i>
                                    <span id="saveButtonText">Lisa kasutaja</span>
                                </button>
                            </div>
                            
                            <!-- Danger actions (only show when editing existing user) -->
                            <div class="danger-actions" id="dangerActions" style="display: none;">
                                <button type="button" onclick="toggleUserStatusFromModal()" class="btn btn-warning" id="toggleStatusBtn">
                                    <i class="icon-eye-off"></i>
                                    <span id="toggleStatusText">Deaktiveeri kasutaja</span>
                                </button>
                                <button type="button" onclick="deleteUserFromModal()" class="btn btn-danger" id="deleteUserBtn">
                                    <i class="icon-trash"></i>
                                    <span>Kustuta kasutaja</span>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Quick User Add Modal - COMPACT MOBILE VERSION -->
        <div id="quickAddModal" class="modal">
            <div class="modal-overlay">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>Kiire lisamine</h3>
                        <button class="modal-close" onclick="closeModal('quickAddModal')">
                            <i class="icon-x"></i>
                        </button>
                    </div>
                    
                    <form method="POST" class="modal-form">
                        <div class="form-group">
                            <label>E-mail *</label>
                            <input type="email" name="email" required class="form-input" placeholder="kasutaja@email.ee">
                        </div>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label>Eesnimi *</label>
                                <input type="text" name="firstName" required class="form-input">
                            </div>
                            <div class="form-group">
                                <label>Perenimi *</label>
                                <input type="text" name="lastName" required class="form-input">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Roll *</label>
                            <select name="role" required class="form-select">
                                <option value="">Vali roll</option>
                                <option value="athlete">Sportlane</option>
                                <option value="admin">Administraator</option>
                            </select>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="icon-info"></i>
                            <span>Kasutajanimi ja parool genereeritakse automaatselt</span>
                        </div>
                        
                        <div class="modal-actions">
                            <div class="primary-actions">
                                <button type="button" onclick="closeModal('quickAddModal')" class="btn btn-secondary">
                                    Tühista
                                </button>
                                <button type="submit" name="quick_add_user" class="btn btn-primary">
                                    <i class="icon-user-plus"></i>
                                    Lisa kasutaja
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>


<script>
console.log('🔧 PARANDATUD: Loading User Management System...');

// Global state
let selectedUsers = new Set();

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM Content Loaded');
    initializeAdvancedFilters();
    console.log('✅ Simplified User Management System loaded successfully');
});

// Advanced Filters Toggle
function toggleAdvancedFilters() {
    const advancedRow = document.querySelector('.filters-row.advanced');
    const toggleIcon = document.querySelector('#filterToggle i');
    
    if (advancedRow.classList.contains('show')) {
        advancedRow.classList.remove('show');
        toggleIcon.style.transform = 'rotate(0deg)';
    } else {
        advancedRow.classList.add('show');
        toggleIcon.style.transform = 'rotate(180deg)';
    }
}

function initializeAdvancedFilters() {
    const filterInputs = document.querySelectorAll('.filter-input, .filter-select');
    filterInputs.forEach(input => {
        input.addEventListener('change', function() {
            setTimeout(() => {
                this.closest('form').submit();
            }, 300);
        });
    });
}

// Bulk Actions Management
function initializeBulkActions() {
    updateBulkActions();
}

function toggleAllUsers(selectAllCheckbox) {
    const userCheckboxes = document.querySelectorAll('.user-checkbox');
    userCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
        if (selectAllCheckbox.checked) {
            selectedUsers.add(checkbox.value);
        } else {
            selectedUsers.delete(checkbox.value);
        }
    });
    updateBulkActions();
}

function selectAllUsers() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const userCheckboxes = document.querySelectorAll('.user-checkbox');
    
    selectAllCheckbox.checked = true;
    userCheckboxes.forEach(checkbox => {
        checkbox.checked = true;
        selectedUsers.add(checkbox.value);
    });
    updateBulkActions();
}

function deselectAllUsers() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const userCheckboxes = document.querySelectorAll('.user-checkbox');
    
    selectAllCheckbox.checked = false;
    userCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    selectedUsers.clear();
    updateBulkActions();
}

function updateBulkActions() {
    const checkedBoxes = document.querySelectorAll('.user-checkbox:checked');
    const bulkBar = document.getElementById('bulkActionsBar');
    const selectedCount = document.getElementById('selectedCount');
    
    if (checkedBoxes.length > 0) {
        bulkBar.style.display = 'flex';
        selectedCount.textContent = checkedBoxes.length;
        
        selectedUsers.clear();
        checkedBoxes.forEach(checkbox => {
            selectedUsers.add(checkbox.value);
        });
    } else {
        bulkBar.style.display = 'none';
        selectedUsers.clear();
    }
    
    const selectAllCheckbox = document.getElementById('selectAll');
    const totalCheckboxes = document.querySelectorAll('.user-checkbox');
    
    if (checkedBoxes.length === 0) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = false;
    } else if (checkedBoxes.length === totalCheckboxes.length) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = true;
    } else {
        selectAllCheckbox.indeterminate = true;
    }
}

function confirmBulkAction() {
    const action = document.querySelector('select[name="bulk_action"]').value;
    const count = selectedUsers.size;
    
    if (!action) {
        alert('Palun vali toiming');
        return false;
    }
    
    const actionTexts = {
        'activate': 'aktiveerida',
        'deactivate': 'deaktiveerida',
        'reset_password': 'lähtestada parool',
        'delete': 'kustutada'
    };
    
    const actionText = actionTexts[action] || action;
    
    return confirm(`Kas oled kindel, et tahad ${count} kasutajat ${actionText}?`);
}

// 🔧 PARANDATUD: Modal Functions with modal-open class
function openUserQuickAddModal() {
    // Close any existing modals first
    const openModals = document.querySelectorAll('.modal.show');
    openModals.forEach(modal => {
        modal.classList.remove('show');
    });
    
    setTimeout(() => {
        openModal('quickAddModal');
    }, 100);
}

function openUserModal() {
    // Close any existing modals first
    const openModals = document.querySelectorAll('.modal.show');
    openModals.forEach(modal => {
        modal.classList.remove('show');
    });
    
    // Small delay then open
    setTimeout(() => {
        resetUserForm();
        openModal('userModal');
    }, 100);
}

// 🔧 PARANDATUD: Modal functions with body.modal-open class
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        // Remove any existing show classes first
        modal.classList.remove('show');
        
        // Force reflow
        modal.offsetHeight;
        
        // Add show class
        modal.classList.add('show');
        document.body.classList.add('modal-open'); // 🔧 LISA SEE RIDA
        document.body.style.overflow = 'hidden';
        
        // Focus first input after animation
        setTimeout(() => {
            const firstInput = modal.querySelector('input:not([type="hidden"]), select');
            if (firstInput) {
                firstInput.focus();
            }
        }, 150);
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('show');
        document.body.classList.remove('modal-open'); // 🔧 LISA SEE RIDA
        document.body.style.overflow = '';
    }
}

// 🔧 PARANDATUD: Direct user edit function - no conflicts with bulk actions
function editUserDirectly(buttonElement) {
    console.log('🎯 Direct edit user clicked');
    
    // Prevent event bubbling to avoid bulk action triggers
    event.stopPropagation();
    event.preventDefault();
    
    // Get user data from button attributes
    const userData = {
        id: buttonElement.getAttribute('data-user-id'),
        firstName: buttonElement.getAttribute('data-first-name'),
        lastName: buttonElement.getAttribute('data-last-name'),
        email: buttonElement.getAttribute('data-email'),
        phone: buttonElement.getAttribute('data-phone'),
        birthDate: buttonElement.getAttribute('data-birth-date'),
        username: buttonElement.getAttribute('data-username'),
        role: buttonElement.getAttribute('data-role'),
        isActive: buttonElement.getAttribute('data-is-active')
    };
    
    console.log('📝 User data for edit:', userData);
    
    // Close any open modals first
    const openModals = document.querySelectorAll('.modal.show');
    openModals.forEach(modal => {
        modal.classList.remove('show');
    });
    
    // Small delay to avoid conflicts
    setTimeout(() => {
        editUserWithData(userData);
    }, 100);
}

function editUserWithData(userData) {
    console.log('🔧 Edit user with data:', userData);
    
    try {
        // Reset form first
        resetUserForm();
        
        // Small delay to ensure form is reset
        setTimeout(() => {
            // Fill form with user data
            document.getElementById('user_id').value = userData.id;
            document.getElementById('firstName').value = userData.firstName;
            document.getElementById('lastName').value = userData.lastName;
            document.getElementById('email').value = userData.email;
            document.getElementById('phone').value = userData.phone || '';
            document.getElementById('birthDate').value = userData.birthDate;
            document.getElementById('username').value = userData.username;
            document.getElementById('role').value = userData.role;
            document.getElementById('isActive').checked = userData.isActive == 1;
            
            // Update modal for editing
            document.getElementById('modalTitle').textContent = 'Muuda kasutajat';
            document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
            document.getElementById('passwordRequired').textContent = '';
            document.getElementById('passwordHelp').textContent = 'Jäta tühjaks kui ei taha muuta';
            document.getElementById('password').removeAttribute('required');
            
            // Show/hide danger actions and update their text
            const dangerActions = document.getElementById('dangerActions');
            const toggleStatusBtn = document.getElementById('toggleStatusBtn');
            const toggleStatusText = document.getElementById('toggleStatusText');
            
            if (dangerActions && toggleStatusBtn && toggleStatusText) {
                dangerActions.style.display = 'flex';
                
                // Update toggle status button
                if (userData.isActive == 1) {
                    toggleStatusBtn.className = 'btn btn-warning';
                    toggleStatusBtn.innerHTML = '<i class="icon-eye-off"></i><span>Deaktiveeri kasutaja</span>';
                } else {
                    toggleStatusBtn.className = 'btn btn-success';  
                    toggleStatusBtn.innerHTML = '<i class="icon-eye"></i><span>Aktiveeri kasutaja</span>';
                }
                
                // Store user data for modal actions
                window.currentEditingUser = userData;
            }
            
            // Open modal
            openModal('userModal');
            
            console.log('✅ User edit modal opened successfully');
        }, 50);
        
    } catch (error) {
        console.error('❌ Error editing user:', error);
        alert('Viga kasutaja muutmisel: ' + error.message);
    }
}

function editUser(userData) {
    console.log('🔧 Edit user:', userData);
    
    // Prevent multiple modal opens
    const existingModal = document.querySelector('#userModal.show');
    if (existingModal) {
        console.log('Modal already open, closing first');
        closeModal('userModal');
        setTimeout(() => editUser(userData), 100);
        return;
    }
    
    // Reset form first
    resetUserForm();
    
    // Small delay to ensure form is reset
    setTimeout(() => {
        // Fill form with user data
        document.getElementById('user_id').value = userData.id;
        document.getElementById('firstName').value = userData.firstName;
        document.getElementById('lastName').value = userData.lastName;
        document.getElementById('email').value = userData.email;
        document.getElementById('phone').value = userData.phone || '';
        document.getElementById('birthDate').value = userData.birthDate;
        document.getElementById('username').value = userData.username;
        document.getElementById('role').value = userData.role;
        document.getElementById('isActive').checked = userData.isActive == 1;
        
        // Update modal for editing
        document.getElementById('modalTitle').textContent = 'Muuda kasutajat';
        document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
        document.getElementById('passwordRequired').textContent = '';
        document.getElementById('passwordHelp').textContent = 'Jäta tühjaks kui ei taha muuta';
        document.getElementById('password').removeAttribute('required');
        
        // Open modal
        openModal('userModal');
    }, 50);
}

// Stop event propagation on buttons to prevent conflicts
document.addEventListener('DOMContentLoaded', function() {
    console.log('🎬 DOM loaded - setting up event handlers');
    
    // Add event listeners to prevent conflicts
    document.addEventListener('click', function(e) {
        // Prevent conflicts with action buttons
        if (e.target.closest('.btn-icon')) {
            // Don't stop propagation here - let the onclick handlers work
            console.log('🎯 Action button clicked:', e.target.closest('.btn-icon'));
        }
        
        // Close modals when clicking outside
        if (e.target.classList.contains('modal-overlay')) {
            const modal = e.target.closest('.modal');
            if (modal) {
                closeModal(modal.id);
            }
        }
    });
    
    // Prevent ESC key conflicts
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal.show');
            if (openModal) {
                closeModal(openModal.id);
            }
        }
    });
    
    console.log('✅ Event handlers initialized');
});

// Update global function assignments
window.editUserDirectly = editUserDirectly;
window.editUserWithData = editUserWithData;

function resetUserForm() {
    const form = document.getElementById('userForm');
    if (form) {
        form.reset();
        document.getElementById('user_id').value = '';
        document.getElementById('modalTitle').textContent = 'Lisa kasutaja';
        document.getElementById('saveButtonText').textContent = 'Lisa kasutaja';
        document.getElementById('passwordRequired').textContent = '*';
        document.getElementById('passwordHelp').textContent = 'Vähemalt 6 tähemärki';
        document.getElementById('password').setAttribute('required', 'required');
        document.getElementById('isActive').checked = true;
        
        // Hide danger actions for new user
        const dangerActions = document.getElementById('dangerActions');
        if (dangerActions) {
            dangerActions.style.display = 'none';
        }
        
        // Clear stored user data
        window.currentEditingUser = null;
    }
}

// 📱 MOBILE MODAL ACTION FUNCTIONS
function toggleUserStatusFromModal() {
    if (window.currentEditingUser) {
        const userId = window.currentEditingUser.id;
        const newStatus = window.currentEditingUser.isActive == 1 ? 'false' : 'true';
        const statusText = newStatus === 'true' ? 'aktiveerida' : 'deaktiveerida';
        
        if (confirm(`Kas oled kindel, et tahad seda kasutajat ${statusText}?`)) {
            closeModal('userModal');
            toggleUserStatus(userId, newStatus);
        }
    }
}

function deleteUserFromModal() {
    if (window.currentEditingUser) {
        const userId = window.currentEditingUser.id;
        const userName = window.currentEditingUser.firstName + ' ' + window.currentEditingUser.lastName;
        
        const confirmMessage = `Kas oled kindel, et tahad kustutada kasutaja "${userName}"?\n\nSee tegevus on pöördumatu!`;
        
        if (confirm(confirmMessage)) {
            closeModal('userModal');
            deleteUser(userId, userName);
        }
    }
}

function verifyUserEmail(userId, userName) {
    if (confirm(`Kas oled kindel, et tahad kinnitada kasutaja "${userName}" e-maili aadressi?`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'verify_user_email';
        actionInput.value = '1';
        
        const userInput = document.createElement('input');
        userInput.type = 'hidden';
        userInput.name = 'user_id';
        userInput.value = userId;
        
        form.appendChild(actionInput);
        form.appendChild(userInput);
        document.body.appendChild(form);
        form.submit();
    }
}

function toggleUserStatus(userId, newStatus) {
    const statusText = newStatus === 'true' ? 'aktiveerida' : 'deaktiveerida';
    
    if (confirm(`Kas oled kindel, et tahad seda kasutajat ${statusText}?`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'toggle_user_status';
        actionInput.value = '1';
        
        const userInput = document.createElement('input');
        userInput.type = 'hidden';
        userInput.name = 'user_id';
        userInput.value = userId;
        
        const statusInput = document.createElement('input');
        statusInput.type = 'hidden';
        statusInput.name = 'new_status';
        statusInput.value = newStatus;
        
        form.appendChild(actionInput);
        form.appendChild(userInput);
        form.appendChild(statusInput);
        document.body.appendChild(form);
        form.submit();
    }
}

function deleteUser(userId, userName) {
    const confirmMessage = `Kas oled kindel, et tahad kustutada kasutaja "${userName}"?\n\nSee tegevus on pöördumatu!`;
    
    if (confirm(confirmMessage)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'delete_user';
        actionInput.value = '1';
        
        const userInput = document.createElement('input');
        userInput.type = 'hidden';
        userInput.name = 'user_id';
        userInput.value = userId;
        
        form.appendChild(actionInput);
        form.appendChild(userInput);
        document.body.appendChild(form);
        form.submit();
    }
}

// Make functions globally available
window.openUserQuickAddModal = openUserQuickAddModal;
window.openUserModal = openUserModal;
window.openModal = openModal;
window.closeModal = closeModal;
window.editUser = editUser;
window.resetUserForm = resetUserForm;
window.verifyUserEmail = verifyUserEmail;
window.toggleUserStatus = toggleUserStatus;
window.deleteUser = deleteUser;
window.selectAllUsers = selectAllUsers;
window.deselectAllUsers = deselectAllUsers;
window.toggleAllUsers = toggleAllUsers;
window.updateBulkActions = updateBulkActions;
window.confirmBulkAction = confirmBulkAction;
window.toggleAdvancedFilters = toggleAdvancedFilters;
window.toggleUserStatusFromModal = toggleUserStatusFromModal;
window.deleteUserFromModal = deleteUserFromModal;

// Keyboard shortcuts (simplified)
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const openModals = document.querySelectorAll('.modal.show');
        openModals.forEach(modal => closeModal(modal.id));
    }
});

console.log('🔧 ✅ PARANDATUD User Management JavaScript loaded successfully!');
</script>

<?php include '../includes/footer.php'; ?>