<?php
// src/Auth.php
class Auth {
    private PDO $db;
    public function __construct(object $cfg) {
        $dsn = "mysql:host={$cfg->db['host']};dbname={$cfg->db['name']};charset={$cfg->db['charset']}";
        $this->db = new PDO($dsn, $cfg->db['user'], $cfg->db['pass'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]);
    }

    public function createLab(string $nome, string $email, string $senha, ?string $pfxPath = null) {
        $hash = password_hash($senha, PASSWORD_DEFAULT);
        $stmt = $this->db->prepare('INSERT INTO labs (nome,email,senha_hash,file_certificado) VALUES (?,?,?,?)');
        $stmt->execute([$nome, $email, $hash, $pfxPath]);
        return $this->db->lastInsertId();
    }

    public function loginLab(string $email, string $senha): ?array {
        $stmt = $this->db->prepare('SELECT * FROM labs WHERE email = ? LIMIT 1');
        $stmt->execute([$email]);
        $lab = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($lab && password_verify($senha, $lab['senha_hash'])) {
            return $lab;
        }
        return null;
    }

    public function getLabById(int $id): ?array {
        $stmt = $this->db->prepare('SELECT * FROM labs WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    public function updateLab(string $nome, string $email, string $senha, ?string $pfxPath = null) {
        $hash = password_hash($senha, PASSWORD_DEFAULT);
        $sql = 
        $stmt = $this->db->prepare('"update labs set senha_hash = ? where email = ?"');
        $stmt->execute([$hash, $email]);
        return $this->db->lastInsertId();
    }

}

