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

class SharedMailbox extends Model
{
    public function allActive(): array
    {
        return $this->db->query('SELECT * FROM shared_mailboxes WHERE is_active = 1 ORDER BY name ASC')->fetchAll();
    }

    public function create(array $data): array
    {
        $name = trim((string)($data['name'] ?? ''));
        $email = normalize_address((string)($data['email_address'] ?? ''));
        if ($name === '' || $email === '') {
            throw new RuntimeException('Shared mailbox name and email are required.');
        }
        $stmt = $this->db->prepare('INSERT INTO shared_mailboxes (name, email_address, description, created_by) VALUES (?, ?, ?, ?)');
        $stmt->execute([$name, $email, trim((string)($data['description'] ?? '')) ?: null, (int)(current_user()['id'] ?? 0) ?: null]);
        $id = (int)$this->db->lastInsertId();
        $fetch = $this->db->prepare('SELECT * FROM shared_mailboxes WHERE id = ? LIMIT 1');
        $fetch->execute([$id]);
        return $fetch->fetch() ?: ['id' => $id, 'name' => $name, 'email_address' => $email];
    }
}
