<?php
require_once __DIR__ . '/../Core.php';

class User extends Model
{
    public function findByEmail(string $email): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE email = ? LIMIT 1');
        $stmt->execute([$email]);
        $row = $stmt->fetch() ?: null;
        if ($row && !empty($row['two_factor_secret'])) {
            $row['two_factor_secret'] = decrypt_value($row['two_factor_secret']);
        }
        return $row;
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
        $stmt->execute([$id]);
        $row = $stmt->fetch() ?: null;
        if ($row && !empty($row['two_factor_secret'])) {
            $row['two_factor_secret'] = decrypt_value($row['two_factor_secret']);
        }
        return $row;
    }

    public function verify(string $email, string $password): ?array
    {
        $user = $this->findByEmail($email);
        if ($user && password_verify($password, $user['password_hash'])) {
            return $user;
        }
        return null;
    }

    public function all(): array
    {
        return $this->db->query('SELECT id, name, email, role, is_active, two_factor_enabled, created_at FROM users ORDER BY created_at DESC')->fetchAll();
    }

    public function create(array $data): bool
    {
        $stmt = $this->db->prepare('INSERT INTO users (name, email, password_hash, role, is_active) VALUES (?, ?, ?, ?, 1)');
        return $stmt->execute([
            $data['name'],
            $data['email'],
            password_hash($data['password'], PASSWORD_DEFAULT),
            $data['role'] ?? 'manager',
        ]);
    }

    public function updatePassword(int $id, string $password): bool
    {
        $stmt = $this->db->prepare('UPDATE users SET password_hash = ?, updated_at = NOW() WHERE id = ?');
        return $stmt->execute([password_hash($password, PASSWORD_DEFAULT), $id]);
    }

    public function enableTwoFactor(int $id, string $secret): bool
    {
        $stmt = $this->db->prepare('UPDATE users SET two_factor_enabled = 1, two_factor_secret = ?, two_factor_confirmed_at = NOW(), updated_at = NOW() WHERE id = ?');
        return $stmt->execute([encrypt_value($secret), $id]);
    }

    public function disableTwoFactor(int $id): bool
    {
        $stmt = $this->db->prepare('UPDATE users SET two_factor_enabled = 0, two_factor_secret = NULL, two_factor_confirmed_at = NULL, updated_at = NOW() WHERE id = ?');
        return $stmt->execute([$id]);
    }
}
