<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\ContactSubmission;

class ContactFormController extends Controller
{
    // ── Default fields if none configured ──────────────────────────────
    private const DEFAULT_FIELDS = [
        ['id' => 'field_name',    'type' => 'text',     'label' => 'Name',      'placeholder' => '',  'required' => true,  'width' => 'half'],
        ['id' => 'field_email',   'type' => 'email',    'label' => 'E-Mail',    'placeholder' => '',  'required' => true,  'width' => 'half'],
        ['id' => 'field_subject', 'type' => 'text',     'label' => 'Betreff',   'placeholder' => '',  'required' => true,  'width' => 'full'],
        ['id' => 'field_message', 'type' => 'textarea', 'label' => 'Nachricht', 'placeholder' => '…', 'required' => true,  'width' => 'full'],
    ];

    private const ALLOWED_TYPES = ['text', 'email', 'tel', 'textarea', 'select', 'checkbox', 'hidden'];

    // ── GET /admin/contact-form ─────────────────────────────────────────
    public function index(Request $request, array $params = []): void
    {
        $tab        = $request->query('tab', 'builder');
        $page       = max(1, (int) $request->query('page', 1));
        $paginated  = ContactSubmission::paginated($page, 20);
        $unread     = ContactSubmission::countUnread();
        $fields     = $this->loadFields();

        $this->renderAdmin('contact-form/index', [
            'pageTitle'  => __('admin.contact_form.title'),
            'tab'        => $tab,
            'fields'     => $fields,
            'enabled'    => (bool) setting('contact_form_enabled', '1'),
            'saveToDb'   => (bool) setting('contact_form_save_to_db', '1'),
            'paginated'  => $paginated,
            'unread'     => $unread,
            'auth'       => $this->auth(),
            'csrf'       => $this->csrf(),
        ]);
    }

    // ── POST /admin/contact-form/save ───────────────────────────────────
    public function save(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $enabled   = $request->input('enabled', '0') === '1' ? '1' : '0';
        $saveToDb  = $request->input('save_to_db', '0') === '1' ? '1' : '0';
        $rawFields = $request->input('fields', '[]');

        // Parse and validate fields JSON
        $fields = json_decode($rawFields, true);
        if (!is_array($fields)) {
            $fields = self::DEFAULT_FIELDS;
        }

        $sanitized = [];
        foreach ($fields as $f) {
            if (!is_array($f)) {
                continue;
            }
            $type = in_array($f['type'] ?? '', self::ALLOWED_TYPES, true) ? $f['type'] : 'text';
            $id   = preg_replace('/[^a-z0-9_]/', '', strtolower($f['id'] ?? ''));
            if ($id === '') {
                continue;
            }
            $entry = [
                'id'          => $id,
                'type'        => $type,
                'label'       => mb_substr(trim($f['label'] ?? ''), 0, 100),
                'placeholder' => mb_substr(trim($f['placeholder'] ?? ''), 0, 100),
                'required'    => !empty($f['required']),
                'width'       => ($f['width'] ?? 'full') === 'half' ? 'half' : 'full',
            ];
            if ($type === 'select') {
                $entry['options'] = mb_substr(trim($f['options'] ?? ''), 0, 500);
            }
            if ($type === 'hidden') {
                $entry['value'] = mb_substr(trim($f['value'] ?? ''), 0, 200);
            }
            $sanitized[] = $entry;
        }

        $db = $this->db();
        $this->saveSetting($db, 'contact_form_enabled',  $enabled,   'contact_form');
        $this->saveSetting($db, 'contact_form_save_to_db', $saveToDb, 'contact_form');
        $this->saveSetting($db, 'contact_form_fields',
            json_encode($sanitized, JSON_UNESCAPED_UNICODE),
            'contact_form'
        );

        set_flash('success', __('admin.contact_form.config_saved'));
        Response::redirect('/admin/contact-form?tab=builder');
    }

    // ── GET /admin/contact-form/submission/{id} ─────────────────────────
    public function viewSubmission(Request $request, array $params = []): void
    {
        $id         = (int) ($params['id'] ?? 0);
        $submission = ContactSubmission::findById($id);

        if (!$submission) {
            set_flash('error', __('messages.not_found', ['item' => 'Eingang']));
            Response::redirect('/admin/contact-form?tab=submissions');
            return;
        }

        // Auto-mark as read
        if (!$submission['is_read']) {
            ContactSubmission::markRead($id);
        }

        $formData = json_decode($submission['form_data'], true) ?: [];

        $this->renderAdmin('contact-form/submission', [
            'pageTitle'  => __('admin.contact_form.title'),
            'submission' => $submission,
            'formData'   => $formData,
            'auth'       => $this->auth(),
            'csrf'       => $this->csrf(),
        ]);
    }

    // ── POST /admin/contact-form/submission/{id}/delete ─────────────────
    public function deleteSubmission(Request $request, array $params = []): void
    {
        $this->validateCsrf();
        $id = (int) ($params['id'] ?? 0);

        ContactSubmission::deleteById($id);

        set_flash('success', __('admin.contact_form.submission_deleted'));
        Response::redirect('/admin/contact-form?tab=submissions');
    }

    // ── POST /admin/contact-form/bulk ───────────────────────────────────
    public function bulk(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $action = $request->input('bulk_action', '');
        $ids    = array_map('intval', (array) $request->input('selected', []));
        $ids    = array_filter($ids, fn($id) => $id > 0);

        if (empty($ids)) {
            set_flash('error', __('messages.error.no_items_selected'));
            Response::redirect('/admin/contact-form?tab=submissions');
            return;
        }

        switch ($action) {
            case 'delete':
                $count = ContactSubmission::bulkDelete($ids);
                set_flash('success', __('admin.contact_form.bulk_deleted', ['count' => $count]));
                break;
            case 'mark_read':
                $count = ContactSubmission::bulkMarkRead($ids);
                set_flash('success', __('admin.contact_form.bulk_read', ['count' => $count]));
                break;
            default:
                set_flash('error', __('messages.generic_error'));
        }

        Response::redirect('/admin/contact-form?tab=submissions');
    }

    // ── GET /admin/contact-form/export ──────────────────────────────────
    public function export(Request $request, array $params = []): void
    {
        $submissions = ContactSubmission::allForExport();
        $fields      = $this->loadFields();

        // Build header row from current field config
        $headers   = ['ID', 'Datum'];
        foreach ($fields as $f) {
            $headers[] = $f['label'];
        }
        $headers[] = 'IP-Adresse';
        $headers[] = 'Gelesen';

        // Build CSV
        $lines = [];
        $lines[] = implode(';', array_map([$this, 'csvEscape'], $headers));

        foreach ($submissions as $sub) {
            $data    = json_decode($sub['form_data'], true) ?: [];
            $dataMap = [];
            foreach ($data as $entry) {
                $dataMap[$entry['id'] ?? ''] = $entry['value'] ?? '';
            }

            $row = [
                $sub['id'],
                $sub['created_at'],
            ];
            foreach ($fields as $f) {
                $row[] = $dataMap[$f['id']] ?? '';
            }
            $row[] = $sub['ip_address'] ?? '';
            $row[] = $sub['is_read'] ? 'Ja' : 'Nein';

            $lines[] = implode(';', array_map([$this, 'csvEscape'], $row));
        }

        $csv = "\xEF\xBB\xBF" . implode("\r\n", $lines); // UTF-8 BOM for Excel

        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="kontaktanfragen-' . date('Y-m-d') . '.csv"');
        header('Content-Length: ' . strlen($csv));
        echo $csv;
        exit;
    }

    // ── Helpers ─────────────────────────────────────────────────────────

    private function loadFields(): array
    {
        $raw = setting('contact_form_fields', '');
        if ($raw === '') {
            return self::DEFAULT_FIELDS;
        }
        $fields = json_decode($raw, true);
        return is_array($fields) && !empty($fields) ? $fields : self::DEFAULT_FIELDS;
    }

    private function saveSetting($db, string $key, string $value, string $group): void
    {
        $existing = $db->fetch("SELECT id FROM iw_settings WHERE setting_key = ?", [$key]);
        if ($existing) {
            $db->query("UPDATE iw_settings SET setting_value = ? WHERE setting_key = ?", [$value, $key]);
        } else {
            $db->query(
                "INSERT INTO iw_settings (setting_key, setting_value, setting_group) VALUES (?, ?, ?)",
                [$key, $value, $group]
            );
        }
    }

    private function csvEscape(mixed $value): string
    {
        $str = (string) $value;
        $str = str_replace('"', '""', $str);
        return '"' . $str . '"';
    }
}
