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

class Pipeline extends Model
{
    public function all(): array
    {
        return $this->db->query('SELECT p.*, (SELECT COUNT(*) FROM contacts c WHERE c.pipeline_id = p.id) contact_count FROM pipelines p ORDER BY p.sort_order ASC, p.name ASC')->fetchAll();
    }

    public function create(array $data): int
    {
        $stages = trim((string)($data['stage_order_csv'] ?? ''));
        $stageJson = json_encode($stages !== '' ? array_values(array_filter(array_map('trim', explode(',', $stages)))) : ['lead','qualified','proposal','customer']);
        $stmt = $this->db->prepare('INSERT INTO pipelines (name, stage_order_json, sort_order, is_active) VALUES (?, ?, ?, ?)');
        $stmt->execute([
            trim((string)($data['name'] ?? 'New Pipeline')),
            $stageJson,
            (int)($data['sort_order'] ?? 0),
            !empty($data['is_active']) ? 1 : 0,
        ]);
        return (int)$this->db->lastInsertId();
    }
}
