<?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((string)($data['name'] ?? '')),
            trim((string)($data['field_key'] ?? '')),
            trim((string)($data['field_type'] ?? 'text')) ?: 'text',
            (int)($data['sort_order'] ?? 0),
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM custom_fields WHERE id = ?');
        $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.field_key = cf.field_key
               AND ccv.contact_id = ?
            ORDER BY cf.sort_order ASC, cf.name ASC');
        $stmt->execute([$contactId]);
        $values = [];
        foreach ($stmt->fetchAll() as $row) {
            $values[(string)$row['field_key']] = $row['field_value'];
        }
        return $values;
    }

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