<?php
namespace admin\Controllers;

use Domain\Newsletter\NewsletterRepository;
use Domain\Newsletter\NewsletterPreviewRenderer;
use admin\ViewModels\Common\PaginatedTableViewModel;
use admin\ViewModels\Forms\FormAction;
use admin\ViewModels\Forms\FormEditViewModel;
use admin\ViewModels\Forms\FormField;
use admin\Support\Forms\FormRequestHandler;

class NewsletterController
{
    private NewsletterRepository $repository;
    private NewsletterPreviewRenderer $previewRenderer;
    private FormRequestHandler $formHandler;

    public function __construct(NewsletterRepository $repository, NewsletterPreviewRenderer $previewRenderer)
    {
        $this->repository = $repository;
        $this->previewRenderer = $previewRenderer;
        $this->formHandler = new FormRequestHandler();
    }

    public function list(): string
    {
        return $this->emails_list();
    }

    public function view_list(): string
    {
        return $this->list();
    }

    public function emails_list(): string
    {
        $sortableColumns = ['email', 'status'];
        $filterDefinitions = [
            [
                'key' => 'email',
                'label' => 'Email',
                'type' => 'text',
            ],
            [
                'key' => 'status',
                'label' => 'Potwierdzony',
                'type' => 'select',
                'options' => [
                    '' => '- potwierdzony -',
                    '1' => 'tak',
                    '0' => 'nie',
                ],
            ],
        ];

        $listRequest = \admin\Support\TableListRequestFactory::fromRequest(
            $filterDefinitions,
            $sortableColumns,
            'email'
        );

        $sortDir = $listRequest['sortDir'];
        if (trim((string)\Shared\Helpers\Helpers::get('sort')) === '') {
            $sortDir = 'ASC';
        }

        $result = $this->repository->listSubscribersForAdmin(
            $listRequest['filters'],
            $listRequest['sortColumn'],
            $sortDir,
            $listRequest['page'],
            $listRequest['perPage']
        );

        $rows = [];
        $lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
        foreach ($result['items'] as $item) {
            $id = (int)($item['id'] ?? 0);
            $email = trim((string)($item['email'] ?? ''));
            $status = (int)($item['status'] ?? 0);

            $rows[] = [
                'lp' => $lp++ . '.',
                'email' => htmlspecialchars($email, ENT_QUOTES, 'UTF-8'),
                'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                '_actions' => [
                    [
                        'label' => 'Usun',
                        'url' => '/admin/newsletter/email_delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrany adres email?',
                    ],
                ],
            ];
        }

        $total = (int)$result['total'];
        $totalPages = max(1, (int)ceil($total / $listRequest['perPage']));

        $viewModel = new PaginatedTableViewModel(
            [
                ['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
                ['key' => 'email', 'sort_key' => 'email', 'label' => 'Email', 'sortable' => true],
                ['key' => 'status', 'sort_key' => 'status', 'label' => 'Potwierdzony', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
            ],
            $rows,
            $listRequest['viewFilters'],
            [
                'column' => $listRequest['sortColumn'],
                'dir' => $sortDir,
            ],
            [
                'page' => $listRequest['page'],
                'per_page' => $listRequest['perPage'],
                'total' => $total,
                'total_pages' => $totalPages,
            ],
            array_merge($listRequest['queryFilters'], [
                'sort' => $listRequest['sortColumn'],
                'dir' => $sortDir,
                'per_page' => $listRequest['perPage'],
            ]),
            $listRequest['perPageOptions'],
            $sortableColumns,
            '/admin/newsletter/emails_list/',
            'Brak danych w tabeli.'
        );

        return \Shared\Tpl\Tpl::view('newsletter/emails-list', [
            'viewModel' => $viewModel,
        ]);
    }

    public function email_delete(): void
    {
        if ($this->repository->deleteSubscriber((int)\Shared\Helpers\Helpers::get('id'))) {
            \Shared\Helpers\Helpers::alert('Adres email zostal usuniety.');
        }

        header('Location: /admin/newsletter/emails_list/');
        exit;
    }

    public function delete(): void
    {
        $this->email_delete();
    }

    public function prepare(): string
    {
        \Shared\Helpers\Helpers::alert('Funkcjonalnosc "Wysylka - przygotowanie" jest tymczasowo wylaczona.');
        header('Location: /admin/newsletter/emails_list/');
        exit;
    }

    public function preview(): string
    {
        return '';
    }

    public function send(): void
    {
        \Shared\Helpers\Helpers::alert('Funkcjonalnosc "Wysylka - przygotowanie" jest tymczasowo wylaczona.');
        header('Location: /admin/newsletter/emails_list/');
        exit;
    }

    public function settings(): string
    {
        $settings = $this->repository->getSettings();
        $validationErrors = $_SESSION['form_errors'][$this->settingsFormId()] ?? null;
        if ($validationErrors) {
            unset($_SESSION['form_errors'][$this->settingsFormId()]);
        }

        return \Shared\Tpl\Tpl::view('newsletter/settings', [
            'form' => $this->buildSettingsFormViewModel($settings, $validationErrors),
        ]);
    }

    public function settings_save(): void
    {
        $legacyValues = \Shared\Helpers\Helpers::get('values');
        if ($legacyValues) {
            $values = json_decode((string)$legacyValues, true);
            if (!is_array($values)) {
                echo json_encode(['status' => 'error', 'msg' => 'Nieprawidlowe dane formularza.']);
                exit;
            }

            $this->repository->saveSettings($values);
            \Shared\Helpers\Helpers::alert('Ustawienia zostaly zapisane.');

            echo json_encode(['status' => 'ok', 'msg' => 'Ustawienia zostaly zapisane.']);
            exit;
        }

        $viewModel = $this->buildSettingsFormViewModel($this->repository->getSettings());
        $result = $this->formHandler->handleSubmit($viewModel, $_POST);
        if (!$result['success']) {
            $_SESSION['form_errors'][$this->settingsFormId()] = $result['errors'];
            echo json_encode(['success' => false, 'errors' => $result['errors']]);
            exit;
        }

        $this->repository->saveSettings($result['data']);
        \Shared\Helpers\Helpers::alert('Ustawienia zostaly zapisane.');

        echo json_encode([
            'success' => true,
            'message' => 'Ustawienia zostaly zapisane.',
        ]);
        exit;
    }

    public function email_templates_user(): string
    {
        \Shared\Helpers\Helpers::alert('Funkcjonalnosc "Szablony uzytkownika" jest tymczasowo wylaczona.');
        header('Location: /admin/newsletter/email_templates_admin/');
        exit;
    }

    public function email_templates_admin(): string
    {
        $viewModel = $this->templatesListViewModel();
        return \Shared\Tpl\Tpl::view('newsletter/email-templates-admin', [
            'viewModel' => $viewModel,
        ]);
    }

    public function email_template_edit(): string
    {
        $template = $this->repository->templateDetails((int)\Shared\Helpers\Helpers::get('id'));
        if (!is_array($template) || (int)($template['is_admin'] ?? 0) !== 1) {
            \Shared\Helpers\Helpers::alert('Dostepne sa tylko szablony administracyjne.');
            header('Location: /admin/newsletter/email_templates_admin/');
            exit;
        }

        $formId = $this->templateFormId((int)$template['id']);
        $validationErrors = $_SESSION['form_errors'][$formId] ?? null;
        if ($validationErrors) {
            unset($_SESSION['form_errors'][$formId]);
        }

        return \Shared\Tpl\Tpl::view('newsletter/email-template-edit', [
            'form' => $this->buildTemplateFormViewModel($template, $validationErrors),
        ]);
    }

    public function template_save(): void
    {
        $legacyValues = \Shared\Helpers\Helpers::get('values');
        if ($legacyValues) {
            $values = json_decode((string)$legacyValues, true);
            $response = ['status' => 'error', 'msg' => 'Podczas zapisywania wystapil blad.'];

            if (is_array($values)) {
                $templateId = (int)($values['id'] ?? 0);
                $template = $this->repository->templateDetails($templateId);

                if (is_array($template) && (int)($template['is_admin'] ?? 0) === 1) {
                    $id = $this->repository->saveTemplate(
                        $templateId,
                        (string)($values['name'] ?? ''),
                        (string)($values['text'] ?? '')
                    );
                    if ($id) {
                        $response = ['status' => 'ok', 'msg' => 'Zmiany zostaly zapisane.', 'id' => $id];
                    }
                }
            }

            echo json_encode($response);
            exit;
        }

        $template = $this->repository->templateDetails((int)\Shared\Helpers\Helpers::get('id'));
        if (!is_array($template) || (int)($template['is_admin'] ?? 0) !== 1) {
            echo json_encode([
                'success' => false,
                'errors' => ['general' => 'Dostepne sa tylko szablony administracyjne.'],
            ]);
            exit;
        }

        $form = $this->buildTemplateFormViewModel($template);
        $result = $this->formHandler->handleSubmit($form, $_POST);
        if (!$result['success']) {
            $_SESSION['form_errors'][$this->templateFormId((int)$template['id'])] = $result['errors'];
            echo json_encode(['success' => false, 'errors' => $result['errors']]);
            exit;
        }

        $data = $result['data'];
        $id = $this->repository->saveTemplate(
            (int)($template['id'] ?? 0),
            (string)($data['name'] ?? ''),
            (string)($data['text'] ?? '')
        );

        if ($id) {
            echo json_encode([
                'success' => true,
                'id' => $id,
                'message' => 'Zmiany zostaly zapisane.',
            ]);
            exit;
        }

        echo json_encode([
            'success' => false,
            'errors' => ['general' => 'Podczas zapisywania wystapil blad.'],
        ]);
        exit;
    }

    public function email_template_delete(): void
    {
        \Shared\Helpers\Helpers::alert('Usuwanie szablonow uzytkownika jest tymczasowo wylaczone.');
        header('Location: /admin/newsletter/email_templates_admin/');
        exit;
    }

    private function buildSettingsFormViewModel(array $settings, ?array $errors = null): FormEditViewModel
    {
        $data = [
            'newsletter_header' => (string)($settings['newsletter_header'] ?? ''),
            'newsletter_footer' => (string)($settings['newsletter_footer'] ?? ''),
        ];

        $fields = [
            FormField::editor('newsletter_header', [
                'label' => 'Naglowek',
                'height' => 150,
            ]),
            FormField::editor('newsletter_footer', [
                'label' => 'Stopka',
                'height' => 150,
            ]),
        ];

        $actionUrl = '/admin/newsletter/settings_save/';
        $actions = [
            FormAction::save($actionUrl, '/admin/newsletter/settings/'),
        ];

        return new FormEditViewModel(
            $this->settingsFormId(),
            'Edycja ustawien newslettera',
            $data,
            $fields,
            [],
            $actions,
            'POST',
            $actionUrl,
            '/admin/newsletter/settings/',
            true,
            [],
            null,
            $errors
        );
    }

    private function buildTemplateFormViewModel(array $template, ?array $errors = null): FormEditViewModel
    {
        $templateId = (int)($template['id'] ?? 0);
        $isAdminTemplate = (int)($template['is_admin'] ?? 0) === 1;
        $isNew = $templateId <= 0;

        $data = [
            'id' => $templateId,
            'name' => (string)($template['name'] ?? ''),
            'text' => (string)($template['text'] ?? ''),
        ];

        $nameAttrs = [];
        if ($isAdminTemplate) {
            $nameAttrs['readonly'] = 'readonly';
        }

        $fields = [
            FormField::text('name', [
                'label' => 'Nazwa',
                'required' => true,
                'attributes' => $nameAttrs,
            ]),
            FormField::editor('text', [
                'label' => 'Tresc',
                'required' => true,
                'height' => 350,
            ]),
        ];

        $backUrl = '/admin/newsletter/email_templates_admin/';
        $actionUrl = '/admin/newsletter/template_save/' . ($isNew ? '' : ('id=' . $templateId));
        $actions = [
            FormAction::save($actionUrl, $backUrl),
            FormAction::cancel($backUrl),
        ];

        return new FormEditViewModel(
            $this->templateFormId($templateId),
            'Edycja szablonu newslettera',
            $data,
            $fields,
            [],
            $actions,
            'POST',
            $actionUrl,
            $backUrl,
            true,
            ['id' => $templateId],
            null,
            $errors
        );
    }

    private function templatesListViewModel(): PaginatedTableViewModel
    {
        $sortableColumns = ['name'];
        $filterDefinitions = [
            [
                'key' => 'name',
                'label' => 'Nazwa',
                'type' => 'text',
            ],
        ];

        $basePath = '/admin/newsletter/email_templates_admin/';

        $listRequest = \admin\Support\TableListRequestFactory::fromRequest(
            $filterDefinitions,
            $sortableColumns,
            'name'
        );

        $sortDir = $listRequest['sortDir'];
        if (trim((string)\Shared\Helpers\Helpers::get('sort')) === '') {
            $sortDir = 'ASC';
        }

        $result = $this->repository->listTemplatesForAdmin(
            true,
            $listRequest['filters'],
            $listRequest['sortColumn'],
            $sortDir,
            $listRequest['page'],
            $listRequest['perPage']
        );

        $rows = [];
        $lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
        foreach ($result['items'] as $item) {
            $id = (int)($item['id'] ?? 0);
            $name = trim((string)($item['name'] ?? ''));

            $actions = [
                [
                    'label' => 'Edytuj',
                    'url' => '/admin/newsletter/email_template_edit/id=' . $id,
                    'class' => 'btn btn-xs btn-primary',
                ],
            ];

            $rows[] = [
                'lp' => $lp++ . '.',
                'name' => '<a href="/admin/newsletter/email_template_edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                '_actions' => $actions,
            ];
        }

        $total = (int)$result['total'];
        $totalPages = max(1, (int)ceil($total / $listRequest['perPage']));

        return new PaginatedTableViewModel(
            [
                ['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
                ['key' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
            ],
            $rows,
            $listRequest['viewFilters'],
            [
                'column' => $listRequest['sortColumn'],
                'dir' => $sortDir,
            ],
            [
                'page' => $listRequest['page'],
                'per_page' => $listRequest['perPage'],
                'total' => $total,
                'total_pages' => $totalPages,
            ],
            array_merge($listRequest['queryFilters'], [
                'sort' => $listRequest['sortColumn'],
                'dir' => $sortDir,
                'per_page' => $listRequest['perPage'],
            ]),
            $listRequest['perPageOptions'],
            $sortableColumns,
            $basePath,
            'Brak danych w tabeli.'
        );
    }

    private function settingsFormId(): string
    {
        return 'newsletter-settings-edit';
    }

    private function templateFormId(int $templateId): string
    {
        return 'newsletter-template-edit-' . $templateId;
    }
}
