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

class MailSenderProfile extends Model
{
    public function all(): array
    {
        $stmt = $this->db->query('SELECT msp.*, u.name AS created_by_name FROM mail_sender_profiles msp LEFT JOIN users u ON u.id = msp.created_by ORDER BY msp.is_active DESC, msp.display_name ASC');
        return $stmt->fetchAll();
    }

    public function active(): array
    {
        $stmt = $this->db->query('SELECT * FROM mail_sender_profiles WHERE is_active = 1 ORDER BY display_name ASC');
        return $stmt->fetchAll();
    }

    public function save(array $data): int
    {
        $displayName = trim((string)($data['display_name'] ?? ''));
        $aliasEmail = trim((string)($data['alias_email'] ?? ''));
        if ($displayName === '' || $aliasEmail === '') {
            throw new RuntimeException('Display name and alias email are required.');
        }
        $stmt = $this->db->prepare('INSERT INTO mail_sender_profiles (display_name, alias_email, reply_to_email, signature_html, is_active, created_by) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $displayName,
            $aliasEmail,
            trim((string)($data['reply_to_email'] ?? '')) ?: null,
            trim((string)($data['signature_html'] ?? '')) ?: null,
            !empty($data['is_active']) ? 1 : 0,
            (int)(current_user()['id'] ?? 0) ?: null,
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM mail_sender_profiles WHERE id = ?');
        $stmt->execute([$id]);
    }
}
