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

class Segment extends Model
{
    public function all(): array
    {
        return $this->db->query('SELECT * FROM segments ORDER BY created_at DESC')->fetchAll();
    }

    public function create(array $data): int
    {
        $rules = [
            'lifecycle_stage' => trim((string)($data['lifecycle_stage'] ?? '')),
            'minimum_score' => (int)($data['minimum_score'] ?? 0),
        ];
        $stmt = $this->db->prepare('INSERT INTO segments (name, channel, tag_filter, company_filter, rule_json, created_by) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            trim((string)($data['name'] ?? 'Untitled Segment')),
            $data['channel'] ?? 'all',
            trim((string)($data['tag_filter'] ?? '')) ?: null,
            trim((string)($data['company_filter'] ?? '')) ?: null,
            json_encode($rules),
            current_user()['id'] ?? null,
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM segments WHERE id = ? LIMIT 1');
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

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

    public function countMembers(int $id): int
    {
        $segment = $this->find($id);
        if (!$segment) {
            return 0;
        }
        $where = [];
        $params = [];
        if (!empty($segment['tag_filter'])) {
            $where[] = 'tags LIKE ?';
            $params[] = '%' . $segment['tag_filter'] . '%';
        }
        if (!empty($segment['company_filter'])) {
            $where[] = 'company LIKE ?';
            $params[] = '%' . $segment['company_filter'] . '%';
        }
        $rules = json_decode((string)($segment['rule_json'] ?? '{}'), true) ?: [];
        if (!empty($rules['lifecycle_stage'])) {
            $where[] = 'lifecycle_stage = ?';
            $params[] = $rules['lifecycle_stage'];
        }
        if (!empty($rules['minimum_score'])) {
            $where[] = 'score >= ?';
            $params[] = (int)$rules['minimum_score'];
        }
        if (($segment['channel'] ?? 'all') === 'sms') {
            $where[] = 'phone IS NOT NULL AND phone != "" AND unsubscribed_sms = 0';
        } elseif (($segment['channel'] ?? 'all') === 'email') {
            $where[] = 'email IS NOT NULL AND email != "" AND unsubscribed_email = 0';
        }
        $sql = 'SELECT COUNT(*) FROM contacts' . ($where ? ' WHERE ' . implode(' AND ', $where) : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return (int)$stmt->fetchColumn();
    }
}
