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

class MailSavedView extends Model
{
    public function allForUser(?int $userId = null): array
    {
        $userId = $userId ?: (int)(current_user()['id'] ?? 0);
        if ($userId <= 0) {
            return [];
        }
        $stmt = $this->db->prepare('SELECT msv.*, u.name AS created_by_name FROM mail_saved_views msv LEFT JOIN users u ON u.id = msv.created_by WHERE msv.is_shared = 1 OR msv.created_by = ? ORDER BY msv.is_shared DESC, msv.name ASC');
        $stmt->execute([$userId]);
        return $stmt->fetchAll();
    }

    public function save(array $data): int
    {
        $name = trim((string)($data['name'] ?? ''));
        if ($name === '') {
            throw new RuntimeException('Saved view name is required.');
        }
        $stmt = $this->db->prepare('INSERT INTO mail_saved_views (name, filter_json, is_shared, created_by) VALUES (?, ?, ?, ?)');
        $stmt->execute([
            $name,
            json_encode($data['filter_json'] ?? [], JSON_UNESCAPED_SLASHES),
            !empty($data['is_shared']) ? 1 : 0,
            (int)(current_user()['id'] ?? 0) ?: null,
        ]);
        return (int)$this->db->lastInsertId();
    }
}
