<?php

class ResponseController {
    private $responseModel;
    private $formModel;

    public function __construct() {
        $this->responseModel = new ResponseModel();
        $this->formModel = new FormModel();
    }

    public function index($formId) {
        $form = $this->formModel->getById($formId);
        if (!$form) { redirect('/forms'); }

        $responses = $this->responseModel->getFullByFormId($formId);
        $fieldModel = new FieldModel();
        $fields = $fieldModel->getByFormId($formId);

        require_once APP_PATH . '/views/responses/index.php';
    }

    public function export($formId) {
        $form = $this->formModel->getById($formId);
        if (!$form) { redirect('/forms'); }

        $fieldModel = new FieldModel();
        $fields = $fieldModel->getByFormId($formId);
        $responses = $this->responseModel->getFullByFormId($formId);

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="responses_' . $form['slug'] . '_' . date('Ymd') . '.csv"');

        $output = fopen('php://output', 'w');
        fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // BOM for Excel UTF-8

        // Header row
        $headers = ['#', 'Submitted At', 'IP Address'];
        foreach ($fields as $field) {
            $headers[] = $field['label'];
        }
        fputcsv($output, $headers);

        // Data rows
        foreach ($responses as $index => $response) {
            $row = [$index + 1, $response['created_at'], $response['ip_address']];

            // Index values by field_id
            $valueMap = [];
            foreach ($response['values'] as $val) {
                $valueMap[$val['field_id']] = $val['value'];
            }

            foreach ($fields as $field) {
                $value = $valueMap[$field['id']] ?? '';
                // For image fields, output filename only
                if ($field['field_type'] === 'image' || $field['field_type'] === 'file') {
                    $row[] = $value ? '[File: ' . $value . ']' : '';
                } else {
                    $row[] = $value;
                }
            }
            fputcsv($output, $row);
        }

        fclose($output);
        exit();
    }

    public function delete($id) {
        $formId = $this->responseModel->getFormIdByResponseId($id);
        if (!$formId) {
            jsonResponse(['success' => false, 'message' => 'Response not found.'], 404);
        }

        // Delete uploaded files for this response
        $db = Database::getInstance();
        $files = $db->fetchAll("
            SELECT rv.value, f.field_type
            FROM response_values rv
            JOIN fields f ON f.id = rv.field_id
            WHERE rv.response_id = ? AND f.field_type IN ('image','file')
        ", [$id]);

        foreach ($files as $file) {
            if (!empty($file['value'])) {
                deleteFile($file['value']);
            }
        }

        $this->responseModel->delete($id);
        jsonResponse(['success' => true, 'message' => 'Response deleted.']);
    }
}
