<?php

class ResponseModel {
    private $db;

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

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

    public function getWithValues($responseId) {
        $response = $this->db->fetch("SELECT * FROM responses WHERE id=?", [$responseId]);
        if (!$response) return null;
        $response['values'] = $this->db->fetchAll("
            SELECT rv.*, f.label, f.field_type
            FROM response_values rv
            JOIN fields f ON f.id = rv.field_id
            WHERE rv.response_id=?
            ORDER BY f.sort_order ASC
        ", [$responseId]);
        return $response;
    }

    public function getFullByFormId($formId) {
        $responses = $this->getByFormId($formId);
        foreach ($responses as &$r) {
            $r['values'] = $this->db->fetchAll("
                SELECT rv.*, f.label, f.field_type
                FROM response_values rv
                JOIN fields f ON f.id = rv.field_id
                WHERE rv.response_id=?
                ORDER BY f.sort_order ASC
            ", [$r['id']]);
        }
        return $responses;
    }

    public function create($formId, $ipAddress, $userAgent) {
        return $this->db->insert("
            INSERT INTO responses (form_id, ip_address, user_agent, created_at)
            VALUES (?, ?, ?, NOW())
        ", [$formId, $ipAddress, $userAgent]);
    }

    public function addValue($responseId, $fieldId, $value) {
        return $this->db->insert("
            INSERT INTO response_values (response_id, field_id, value)
            VALUES (?, ?, ?)
        ", [$responseId, $fieldId, $value]);
    }

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

    public function getFormIdByResponseId($id) {
        $r = $this->db->fetch("SELECT form_id FROM responses WHERE id=?", [$id]);
        return $r ? $r['form_id'] : null;
    }
}
