| 1 | <?php |
| 2 | |
| 3 | namespace TribeGen\Classes; |
| 4 | |
| 5 | use TribeGen\Database\Database; |
| 6 | use TribeGen\System\SaveManager; |
| 7 | |
| 8 | class User |
| 9 | { |
| 10 | private $id; |
| 11 | private $email; |
| 12 | |
| 13 | public function __construct($id, $email) |
| 14 | { |
| 15 | $this->id = $id; |
| 16 | $this->email = $email; |
| 17 | } |
| 18 | |
| 19 | public static function register($email, $password) |
| 20 | { |
| 21 | if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { |
| 22 | throw new \Exception('Invalid email format'); |
| 23 | } |
| 24 | |
| 25 | $passwordHash = password_hash($password, PASSWORD_BCRYPT); |
| 26 | |
| 27 | try { |
| 28 | $db = Database::getInstance(); |
| 29 | $pdo = $db->getPDO(); |
| 30 | $stmt = $pdo->prepare("INSERT INTO users (email, password_hash) VALUES (?, ?)"); |
| 31 | $stmt->execute([$email, $passwordHash]); |
| 32 | |
| 33 | return new self($pdo->lastInsertId(), $email); |
| 34 | } catch (\PDOException $e) { |
| 35 | if (strpos($e->getMessage(), 'UNIQUE constraint failed') !== false) { |
| 36 | throw new \Exception('Email already registered'); |
| 37 | } |
| 38 | throw $e; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | public static function login($email, $password) |
| 43 | { |
| 44 | $db = Database::getInstance(); |
| 45 | $pdo = $db->getPDO(); |
| 46 | |
| 47 | $stmt = $pdo->prepare("SELECT id, email, password_hash FROM users WHERE email = ?"); |
| 48 | $stmt->execute([$email]); |
| 49 | $row = $stmt->fetch(); |
| 50 | |
| 51 | if (!$row || !password_verify($password, $row['password_hash'])) { |
| 52 | throw new \Exception('Invalid email or password'); |
| 53 | } |
| 54 | |
| 55 | return new self($row['id'], $row['email']); |
| 56 | } |
| 57 | |
| 58 | public function getId() |
| 59 | { |
| 60 | return $this->id; |
| 61 | } |
| 62 | |
| 63 | public function getEmail() |
| 64 | { |
| 65 | return $this->email; |
| 66 | } |
| 67 | |
| 68 | public function getSaves() |
| 69 | { |
| 70 | $saveManager = new SaveManager(); |
| 71 | return $saveManager->listUserSaves($this->id); |
| 72 | } |
| 73 | } |