<?php

class FieldModel {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    public function getByFormId($formId) {
        return $this->db->fetchAll("
            SELECT * FROM fields WHERE form_id = ? ORDER BY sort_order ASC
        ", [$formId]);
    }

    public function getById($id) {
        return $this->db->fetch("SELECT * FROM fields WHERE id = ?", [$id]);
    }

    public function create($data) {
        $maxOrder = $this->db->fetch("SELECT MAX(sort_order) as max_order FROM fields WHERE form_id=?", [$data['form_id']]);
        $sortOrder = ($maxOrder['max_order'] ?? 0) + 1;

        return $this->db->insert("
            INSERT INTO fields (form_id, label, field_type, placeholder, required, options, settings, sort_order, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ", [
            $data['form_id'],
            $data['label'],
            $data['field_type'],
            $data['placeholder'] ?? '',
            isset($data['required']) ? 1 : 0,
            $data['options'] ?? '',
            $data['settings'] ?? '{}',
            $sortOrder,
        ]);
    }

    public function update($id, $data) {
        return $this->db->execute("
            UPDATE fields SET label=?, field_type=?, placeholder=?, required=?, options=?, settings=?
            WHERE id=?
        ", [
            $data['label'],
            $data['field_type'],
            $data['placeholder'] ?? '',
            isset($data['required']) ? 1 : 0,
            $data['options'] ?? '',
            $data['settings'] ?? '{}',
            $id,
        ]);
    }

    public function delete($id) {
        return $this->db->execute("DELETE FROM fields WHERE id=?", [$id]);
    }

    public function reorder($formId, $order) {
        foreach ($order as $index => $fieldId) {
            $this->db->execute("UPDATE fields SET sort_order=? WHERE id=? AND form_id=?", [$index + 1, $fieldId, $formId]);
        }
    }
}
