<?php

namespace App\Models;

use App\Core\Model;

class DynamicForm extends Model
{
    protected $table = 'dynamic_forms';
    protected $primaryKey = 'id';

    public function getWithFields($id)
    {
        $form = $this->find($id);
        if (!$form) return null;
        $stmt = $this->db->prepare("SELECT * FROM dynamic_form_fields WHERE form_id = ? ORDER BY sort_order ASC");
        $stmt->execute([$id]);
        $form->fields = $stmt->fetchAll(\PDO::FETCH_OBJ);
        return $form;
    }

    public function getActive()
    {
        $stmt = $this->db->query("SELECT f.*, u.name as created_by_name, (SELECT COUNT(*) FROM dynamic_form_submissions WHERE form_id = f.id) as submission_count FROM {$this->table} f LEFT JOIN users u ON f.created_by = u.id WHERE f.is_active = 1 AND f.is_template = 0 ORDER BY f.created_at DESC");
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getTemplates()
    {
        $stmt = $this->db->query("SELECT f.*, u.name as created_by_name FROM {$this->table} f LEFT JOIN users u ON f.created_by = u.id WHERE f.is_template = 1 ORDER BY f.template_name ASC");
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getByShareToken($token)
    {
        $stmt = $this->db->prepare("SELECT f.* FROM {$this->table} f INNER JOIN form_shares s ON f.id = s.form_id WHERE s.token = ? AND (s.expires_at IS NULL OR s.expires_at > NOW()) LIMIT 1");
        $stmt->execute([$token]);
        $form = $stmt->fetch(\PDO::FETCH_OBJ);
        if (!$form) return null;
        return $this->getWithFields($form->id);
    }

    public function duplicate($id, $newTitle, $userId)
    {
        $original = $this->getWithFields($id);
        if (!$original) return null;

        $newId = $this->create([
            'title' => $newTitle,
            'description' => $original->description,
            'table_name' => 'form_' . time(),
            'is_active' => $original->is_active,
            'requires_auth' => $original->requires_auth,
            'source_form_id' => $id,
            'created_by' => $userId,
        ]);

        $fieldModel = new DynamicFormField();
        foreach ($original->fields as $i => $field) {
            $fieldModel->create([
                'form_id' => $newId,
                'label' => $field->label,
                'field_name' => 'field_' . ($i + 1),
                'field_type' => $field->field_type,
                'options' => $field->options,
                'is_required' => $field->is_required,
                'placeholder' => $field->placeholder,
                'validation_rules' => $field->validation_rules ?? null,
                'sort_order' => $i + 1,
            ]);
        }

        return $newId;
    }

    public function getShareUrl($id)
    {
        $stmt = $this->db->prepare("SELECT token FROM form_shares WHERE form_id = ? ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$id]);
        $row = $stmt->fetch(\PDO::FETCH_OBJ);
        return $row ? $row->token : null;
    }
}
