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47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
<?php

namespace SoftEdge;

use PDO;
use PDOException;

/**

 * User Management Class

 * Handles user registration, authentication, and profile management

 */
class User

{
    private PDO $db;
    private array $config;

    public function __construct(PDO $db = null)

    {
        $this->config = $this->loadConfig();
        $this->db = $db ?? $this->getDatabaseConnection();
    }

    /**

     * Load configuration

     */
    private function loadConfig(): array

    {
        return [
            'db_host' => $_ENV['DB_HOST'] ?? 'localhost',
            'db_name' => $_ENV['DB_NAME'] ?? 'softedge_db',
            'db_user' => $_ENV['DB_USER'] ?? 'root',
            'db_pass' => $_ENV['DB_PASS'] ?? '',
            'jwt_secret' => $_ENV['JWT_SECRET'] ?? 'your-jwt-secret-key',
            'google_client_id' => $_ENV['GOOGLE_CLIENT_ID'] ?? '',
            'google_client_secret' => $_ENV['GOOGLE_CLIENT_SECRET'] ?? '',
            'github_client_id' => $_ENV['GITHUB_CLIENT_ID'] ?? '',
            'github_client_secret' => $_ENV['GITHUB_CLIENT_SECRET'] ?? ''
        ];
    }

    /**

     * Get database connection

     */
    private function getDatabaseConnection(): PDO

    {
        try {
            $dsn = "mysql:host={$this->config['db_host']};dbname={$this->config['db_name']};charset=utf8mb4";
            $pdo = new PDO($dsn, $this->config['db_user'], $this->config['db_pass']);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            return $pdo;
        } catch (PDOException $e) {
            error_log("Database connection failed: " . $e->getMessage());
            throw new \RuntimeException('Database connection failed');
        }
    }

    /**

     * Create users table if it doesn't exist

     */
    public function createTables(): void

    {
        try {
            // Users table
            $this->db->exec("

                CREATE TABLE IF NOT EXISTS users (

                    id INT AUTO_INCREMENT PRIMARY KEY,

                    name VARCHAR(255) NOT NULL,

                    email VARCHAR(255) UNIQUE NOT NULL,

                    password VARCHAR(255),

                    avatar VARCHAR(500),

                    provider VARCHAR(50) DEFAULT 'local',

                    provider_id VARCHAR(255),

                    role ENUM('user', 'admin') DEFAULT 'user',

                    email_verified BOOLEAN DEFAULT FALSE,

                    verification_token VARCHAR(255),

                    reset_token VARCHAR(255),

                    reset_expires DATETIME,

                    last_login DATETIME,

                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

            ");

            // Page visits table
            $this->db->exec("

                CREATE TABLE IF NOT EXISTS page_visits (

                    id INT AUTO_INCREMENT PRIMARY KEY,

                    user_id INT,

                    page VARCHAR(255) NOT NULL,

                    ip_address VARCHAR(45),

                    user_agent TEXT,

                    referrer VARCHAR(500),

                    session_id VARCHAR(255),

                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

                    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL

                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

            ");

            // User sessions table
            $this->db->exec("

                CREATE TABLE IF NOT EXISTS user_sessions (

                    id INT AUTO_INCREMENT PRIMARY KEY,

                    user_id INT NOT NULL,

                    session_token VARCHAR(255) UNIQUE NOT NULL,

                    ip_address VARCHAR(45),

                    user_agent TEXT,

                    expires_at DATETIME NOT NULL,

                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

                    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

            ");

        } catch (PDOException $e) {
            error_log("Table creation failed: " . $e->getMessage());
            throw new \RuntimeException('Failed to create database tables');
        }
    }

    /**

     * Register a new user

     */
    public function register(array $data): array

    {
        $this->validateRegistrationData($data);

        try {
            $this->db->beginTransaction();

            // Check if email already exists
            $stmt = $this->db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$data['email']]);
            if ($stmt->fetch()) {
                throw new \InvalidArgumentException('Email já cadastrado');
            }

            // Hash password
            $hashedPassword = password_hash($data['password'], PASSWORD_ARGON2ID);

            // Generate verification token
            $verificationToken = bin2hex(random_bytes(32));

            // Insert user
            $stmt = $this->db->prepare("

                INSERT INTO users (name, email, password, verification_token, created_at)

                VALUES (?, ?, ?, ?, NOW())

            ");
            $stmt->execute([
                $data['name'],
                $data['email'],
                $hashedPassword,
                $verificationToken
            ]);

            $userId = $this->db->lastInsertId();

            $this->db->commit();

            return [
                'success' => true,
                'user_id' => $userId,
                'verification_token' => $verificationToken,
                'message' => 'Usuário registrado com sucesso. Verifique seu email.'
            ];

        } catch (PDOException $e) {
            $this->db->rollBack();
            error_log("Registration failed: " . $e->getMessage());
            throw new \RuntimeException('Erro ao registrar usuário');
        }
    }

    /**

     * Authenticate user

     */
    public function login(string $email, string $password): array

    {
        try {
            $stmt = $this->db->prepare("

                SELECT id, name, email, password, role, email_verified

                FROM users

                WHERE email = ? AND provider = 'local'

            ");
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            if (!$user || !password_verify($password, $user['password'])) {
                throw new \InvalidArgumentException('Email ou senha incorretos');
            }

            if (!$user['email_verified']) {
                throw new \InvalidArgumentException('Email não verificado. Verifique sua caixa de entrada.');
            }

            // Update last login
            $stmt = $this->db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
            $stmt->execute([$user['id']]);

            // Create session
            $sessionToken = $this->createSession($user['id']);

            // Log page visit
            $this->logPageVisit($user['id'], 'login', $_SERVER['HTTP_USER_AGENT'] ?? '');

            return [
                'success' => true,
                'user' => [
                    'id' => $user['id'],
                    'name' => $user['name'],
                    'email' => $user['email'],
                    'role' => $user['role']
                ],
                'session_token' => $sessionToken
            ];

        } catch (PDOException $e) {
            error_log("Login failed: " . $e->getMessage());
            throw new \RuntimeException('Erro ao fazer login');
        }
    }

    /**

     * Social login (Google, GitHub)

     */
    public function socialLogin(string $provider, array $profile): array

    {
        try {
            $this->db->beginTransaction();

            // Check if user exists
            $stmt = $this->db->prepare("

                SELECT id, name, email, role, email_verified

                FROM users

                WHERE provider = ? AND provider_id = ?

            ");
            $stmt->execute([$provider, $profile['id']]);
            $user = $stmt->fetch();

            if (!$user) {
                // Create new user
                $stmt = $this->db->prepare("

                    INSERT INTO users (name, email, avatar, provider, provider_id, email_verified, created_at)

                    VALUES (?, ?, ?, ?, ?, TRUE, NOW())

                ");
                $stmt->execute([
                    $profile['name'],
                    $profile['email'],
                    $profile['avatar'] ?? null,
                    $provider,
                    $profile['id']
                ]);

                $userId = $this->db->lastInsertId();

                $user = [
                    'id' => $userId,
                    'name' => $profile['name'],
                    'email' => $profile['email'],
                    'role' => 'user',
                    'email_verified' => true
                ];
            }

            // Update last login
            $stmt = $this->db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
            $stmt->execute([$user['id']]);

            // Create session
            $sessionToken = $this->createSession($user['id']);

            // Log page visit
            $this->logPageVisit($user['id'], 'social_login', $_SERVER['HTTP_USER_AGENT'] ?? '');

            $this->db->commit();

            return [
                'success' => true,
                'user' => $user,
                'session_token' => $sessionToken
            ];

        } catch (PDOException $e) {
            $this->db->rollBack();
            error_log("Social login failed: " . $e->getMessage());
            throw new \RuntimeException('Erro ao fazer login social');
        }
    }

    /**

     * Create user session

     */
    private function createSession(int $userId): string

    {
        $sessionToken = bin2hex(random_bytes(32));
        $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));

        $stmt = $this->db->prepare("

            INSERT INTO user_sessions (user_id, session_token, ip_address, user_agent, expires_at, created_at)

            VALUES (?, ?, ?, ?, ?, NOW())

        ");
        $stmt->execute([
            $userId,
            $sessionToken,
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? '',
            $expiresAt
        ]);

        return $sessionToken;
    }

    /**

     * Validate session

     */
    public function validateSession(string $sessionToken): ?array

    {
        try {
            $stmt = $this->db->prepare("

                SELECT u.id, u.name, u.email, u.role, u.email_verified, s.expires_at

                FROM user_sessions s

                JOIN users u ON s.user_id = u.id

                WHERE s.session_token = ? AND s.expires_at > NOW()

            ");
            $stmt->execute([$sessionToken]);
            $result = $stmt->fetch();

            return $result ?: null;

        } catch (PDOException $e) {
            error_log("Session validation failed: " . $e->getMessage());
            return null;
        }
    }

    /**

     * Log page visit

     */
    public function logPageVisit(?int $userId, string $page, string $userAgent = ''): void

    {
        try {
            $stmt = $this->db->prepare("

                INSERT INTO page_visits (user_id, page, ip_address, user_agent, referrer, session_id, created_at)

                VALUES (?, ?, ?, ?, ?, ?, NOW())

            ");
            $stmt->execute([
                $userId,
                $page,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $userAgent,
                $_SERVER['HTTP_REFERER'] ?? '',
                session_id()
            ]);
        } catch (PDOException $e) {
            error_log("Page visit logging failed: " . $e->getMessage());
        }
    }

    /**

     * Get admin statistics

     */
    public function getAdminStats(): array

    {
        try {
            // Total users
            $stmt = $this->db->query("SELECT COUNT(*) as total FROM users");
            $totalUsers = $stmt->fetch()['total'];

            // Total page visits
            $stmt = $this->db->query("SELECT COUNT(*) as total FROM page_visits");
            $totalVisits = $stmt->fetch()['total'];

            // Recent visits (last 30 days)
            $stmt = $this->db->prepare("

                SELECT COUNT(*) as total

                FROM page_visits

                WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)

            ");
            $stmt->execute();
            $recentVisits = $stmt->fetch()['total'];

            // Top pages
            $stmt = $this->db->prepare("

                SELECT page, COUNT(*) as visits

                FROM page_visits

                GROUP BY page

                ORDER BY visits DESC

                LIMIT 10

            ");
            $stmt->execute();
            $topPages = $stmt->fetchAll();

            // Recent users
            $stmt = $this->db->prepare("

                SELECT id, name, email, created_at

                FROM users

                ORDER BY created_at DESC

                LIMIT 10

            ");
            $stmt->execute();
            $recentUsers = $stmt->fetchAll();

            return [
                'total_users' => $totalUsers,
                'total_visits' => $totalVisits,
                'recent_visits' => $recentVisits,
                'top_pages' => $topPages,
                'recent_users' => $recentUsers
            ];

        } catch (PDOException $e) {
            error_log("Admin stats failed: " . $e->getMessage());
            return [];
        }
    }

    /**

     * Validate registration data

     */
    private function validateRegistrationData(array $data): void

    {
        $required = ['name', 'email', 'password'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                throw new \InvalidArgumentException("Campo {$field} é obrigatório");
            }
        }

        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Email inválido');
        }

        if (strlen($data['name']) < 2) {
            throw new \InvalidArgumentException('Nome deve ter pelo menos 2 caracteres');
        }

        if (strlen($data['password']) < 8) {
            throw new \InvalidArgumentException('Senha deve ter pelo menos 8 caracteres');
        }
    }

    /**

     * Check if user is admin

     */
    public function isAdmin(int $userId): bool

    {
        try {
            $stmt = $this->db->prepare("SELECT role FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();

            return $user && $user['role'] === 'admin';

        } catch (PDOException $e) {
            error_log("Admin check failed: " . $e->getMessage());
            return false;
        }
    }
}