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

class Account extends Model
{
    public function all(): array
    {
        return $this->db->query('SELECT a.*, u.name AS owner_name, (SELECT COUNT(*) FROM contacts c WHERE c.account_id = a.id) contact_count FROM accounts a LEFT JOIN users u ON u.id = a.owner_user_id ORDER BY a.name ASC')->fetchAll();
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO accounts (name, industry, website, owner_user_id) VALUES (?, ?, ?, ?)');
        $stmt->execute([
            trim((string)($data['name'] ?? 'New Account')),
            trim((string)($data['industry'] ?? '')) ?: null,
            trim((string)($data['website'] ?? '')) ?: null,
            (int)($data['owner_user_id'] ?? 0) ?: null,
        ]);
        return (int)$this->db->lastInsertId();
    }
}
