<?php

require_once __DIR__ . '/../../src/Database/Database.php';
require_once __DIR__ . '/../../src/System/SaveManager.php';

class User
{
    private $id;
    private $email;

    public function __construct($id, $email)
    {
        $this->id = $id;
        $this->email = $email;
    }

    public static function register($email, $password)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \Exception('Invalid email format');
        }

        $passwordHash = password_hash($password, PASSWORD_BCRYPT);

        try {
            $db = Database::getInstance();
            $pdo = $db->getPDO();
            $stmt = $pdo->prepare("INSERT INTO users (email, password_hash) VALUES (?, ?)");
            $stmt->execute([$email, $passwordHash]);

            return new self($pdo->lastInsertId(), $email);
        } catch (\PDOException $e) {
            if (strpos($e->getMessage(), 'UNIQUE constraint failed') !== false) {
                throw new \Exception('Email already registered');
            }
            throw $e;
        }
    }

    public static function login($email, $password)
    {
        $db = Database::getInstance();
        $pdo = $db->getPDO();

        $stmt = $pdo->prepare("SELECT id, email, password_hash FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $row = $stmt->fetch();

        if (!$row || !password_verify($password, $row['password_hash'])) {
            throw new \Exception('Invalid email or password');
        }

        return new self($row['id'], $row['email']);
    }

    public function getId()
    {
        return $this->id;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getSaves()
    {
        $saveManager = new SaveManager();
        return $saveManager->listUserSaves($this->id);
    }
}
