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

class CustomField extends Model
{
    public function all(): array
    {
        return $this->db->query('SELECT * FROM custom_fields ORDER BY sort_order ASC, name ASC')->fetchAll();
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO custom_fields (name, field_key, field_type, sort_order) VALUES (?, ?, ?, ?)');
        $stmt->execute([
            trim($data['name'] ?? 'Field'),
            trim($data['field_key'] ?? ''),
            trim($data['field_type'] ?? 'text') ?: 'text',
            (int)($data['sort_order'] ?? 0),
        ]);
        return (int)$this->db->lastInsertId();
    }

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

    public function valuesForContact(int $contactId): array
    {
        $stmt = $this->db->prepare('SELECT cf.field_key, ccv.field_value FROM custom_fields cf LEFT JOIN contact_custom_values ccv ON ccv.custom_field_id = cf.id AND ccv.contact_id = ? ORDER BY cf.sort_order ASC, cf.name ASC');
        $stmt->execute([$contactId]);
        return $stmt->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    }

    public function saveValuesForContact(int $contactId, array $values): void
    {
        foreach ($this->all() as $field) {
            $fieldId = (int)$field['id'];
            $fieldKey = $field['field_key'];
            $value = trim((string)($values[$fieldKey] ?? ''));
            if ($value === '') {
                $stmt = $this->db->prepare('DELETE FROM contact_custom_values WHERE contact_id = ? AND custom_field_id = ?');
                $stmt->execute([$contactId, $fieldId]);
                continue;
            }
            $stmt = $this->db->prepare('INSERT INTO contact_custom_values (contact_id, custom_field_id, field_value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE field_value = VALUES(field_value), updated_at = NOW()');
            $stmt->execute([$contactId, $fieldId, $value]);
        }
    }
}
