<?php

class FormModel {
    private $db;

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

    public function getAll() {
        return $this->db->fetchAll("
            SELECT f.*, 
                   COUNT(DISTINCT fi.id) as field_count,
                   COUNT(DISTINCT r.id) as response_count
            FROM forms f
            LEFT JOIN fields fi ON fi.form_id = f.id
            LEFT JOIN responses r ON r.form_id = f.id
            GROUP BY f.id
            ORDER BY f.created_at DESC
        ");
    }

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

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

    public function create($data) {
        return $this->db->insert("
            INSERT INTO forms (name, description, slug, whatsapp_number, thank_you_message, redirect_url, settings, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        ", [
            $data['name'],
            $data['description'] ?? '',
            $data['slug'],
            $data['whatsapp_number'] ?? '',
            $data['thank_you_message'] ?? 'Thank you for your submission!',
            $data['redirect_url'] ?? '',
            $data['settings'] ?? '{}',
        ]);
    }

    public function update($id, $data) {
        return $this->db->execute("
            UPDATE forms SET name=?, description=?, whatsapp_number=?, thank_you_message=?, redirect_url=?, settings=?, updated_at=NOW()
            WHERE id=?
        ", [
            $data['name'],
            $data['description'] ?? '',
            $data['whatsapp_number'] ?? '',
            $data['thank_you_message'] ?? 'Thank you for your submission!',
            $data['redirect_url'] ?? '',
            $data['settings'] ?? '{}',
            $id
        ]);
    }

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

    public function getStats() {
        return $this->db->fetch("
            SELECT 
                COUNT(*) as total_forms,
                (SELECT COUNT(*) FROM responses) as total_responses,
                (SELECT COUNT(*) FROM funnels) as total_funnels,
                (SELECT COUNT(*) FROM fields) as total_fields
            FROM forms
        ");
    }

    public function getRecentResponses($limit = 5) {
        return $this->db->fetchAll("
            SELECT r.*, f.name as form_name
            FROM responses r
            JOIN forms f ON f.id = r.form_id
            ORDER BY r.created_at DESC
            LIMIT ?
        ", [$limit]);
    }
}
