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

class Workflow extends Model
{
    public function all(): array
    {
        return $this->db->query('SELECT w.*, s.name AS segment_name, t.name AS template_name, u.name AS created_by_name FROM workflows w LEFT JOIN segments s ON s.id = w.target_segment_id LEFT JOIN templates t ON t.id = w.template_id LEFT JOIN users u ON u.id = w.created_by ORDER BY w.created_at DESC')->fetchAll();
    }

    public function create(array $data): int
    {
        $filters = [
            'tag_filter' => trim((string)($data['tag_filter'] ?? '')),
            'company_filter' => trim((string)($data['company_filter'] ?? '')),
            'lifecycle_stage' => trim((string)($data['lifecycle_stage'] ?? '')),
            'minimum_score' => (int)($data['minimum_score'] ?? 0),
        ];
        $action = [
            'subject_override' => trim((string)($data['subject_override'] ?? '')),
            'body_override' => trim((string)($data['body_override'] ?? '')),
        ];
        $stmt = $this->db->prepare('INSERT INTO workflows (name, is_active, trigger_event, channel, template_id, delay_minutes, target_segment_id, filters_json, action_json, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            trim((string)($data['name'] ?? 'Untitled Workflow')),
            !empty($data['is_active']) ? 1 : 0,
            $data['trigger_event'] ?? 'contact_created',
            $data['channel'] ?? 'email',
            (int)($data['template_id'] ?? 0) ?: null,
            max(0, (int)($data['delay_minutes'] ?? 0)),
            (int)($data['target_segment_id'] ?? 0) ?: null,
            json_encode($filters),
            json_encode($action),
            current_user()['id'] ?? null,
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function toggle(int $id): void
    {
        $stmt = $this->db->prepare('UPDATE workflows SET is_active = IF(is_active = 1, 0, 1) WHERE id = ?');
        $stmt->execute([$id]);
    }

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

    public function stats(): array
    {
        return $this->db->query('SELECT COUNT(*) total, SUM(is_active = 1) active_count, SUM(trigger_event = "contact_created") created_triggers, SUM(trigger_event = "tag_added") tag_triggers FROM workflows')->fetch() ?: ['total' => 0, 'active_count' => 0, 'created_triggers' => 0, 'tag_triggers' => 0];
    }
}
