<?php

namespace Daylight\Core\Modules\FormBuilder\Http\Controllers;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Modules\FormBuilder\Http\Requests\StoreFormRequest;
use Daylight\Core\Modules\FormBuilder\Http\Requests\UpdateFormRequest;
use Daylight\Core\Modules\FormBuilder\Models\Form;
use Daylight\Core\Modules\FormBuilder\Models\FormSubmission;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class FormController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:create:pages', only: ['create', 'store', 'duplicate']),
            new Middleware('can:read:pages', only: ['index', 'show', 'submissions', 'showSubmission']),
            new Middleware('can:update:pages', only: ['edit', 'update']),
            new Middleware('can:delete:pages', only: ['destroy', 'destroySubmission']),
        ];
    }

    public function index(): View
    {
        return view('daylight::content.forms.index');
    }

    public function create(): View
    {
        return view('daylight::content.forms.create');
    }

    public function store(StoreFormRequest $request): RedirectResponse
    {
        $fields = json_decode($request->input('fields_json'), true) ?: [];

        $form = Form::create([
            'name' => $request->input('name'),
            'recipient_email' => $request->input('recipient_email'),
            'cc' => $request->input('cc'),
            'bcc' => $request->input('bcc'),
            'auto_reply_enabled' => $request->boolean('auto_reply_enabled'),
            'auto_reply_subject' => $request->input('auto_reply_subject'),
            'auto_reply_message' => $request->input('auto_reply_message'),
            'is_active' => $request->boolean('is_active'),
            'fields' => $fields,
            'success_type' => $request->input('success_type', 'message'),
            'success_message' => $request->input('success_message'),
            'success_redirect_url' => $request->input('success_redirect_url'),
        ]);

        return redirect()
            ->route('daylight.content.forms.edit', $form)
            ->with('success', __('daylight::forms.form_created'));
    }

    public function edit(Form $form): View
    {
        return view('daylight::content.forms.edit', [
            'form' => $form,
        ]);
    }

    public function update(UpdateFormRequest $request, Form $form): RedirectResponse
    {
        $fields = json_decode($request->input('fields_json'), true) ?: [];

        $form->update([
            'name' => $request->input('name'),
            'recipient_email' => $request->input('recipient_email'),
            'cc' => $request->input('cc'),
            'bcc' => $request->input('bcc'),
            'auto_reply_enabled' => $request->boolean('auto_reply_enabled'),
            'auto_reply_subject' => $request->input('auto_reply_subject'),
            'auto_reply_message' => $request->input('auto_reply_message'),
            'is_active' => $request->boolean('is_active'),
            'fields' => $fields,
            'success_type' => $request->input('success_type', 'message'),
            'success_message' => $request->input('success_message'),
            'success_redirect_url' => $request->input('success_redirect_url'),
        ]);

        return redirect()
            ->route('daylight.content.forms.index')
            ->with('success', __('daylight::forms.form_updated'));
    }

    public function show(Form $form): RedirectResponse
    {
        return redirect()->route('daylight.content.forms.submissions', $form);
    }

    public function submissions(Form $form): View
    {
        return view('daylight::content.forms.submissions', [
            'form' => $form,
        ]);
    }

    public function showSubmission(Form $form, FormSubmission $submission): View
    {
        abort_unless($submission->form_id === $form->id, 404);

        return view('daylight::content.forms.show-submission', [
            'form' => $form,
            'submission' => $submission,
        ]);
    }

    public function duplicate(Form $form): RedirectResponse
    {
        $newForm = $form->replicate();
        $newForm->name = __('daylight::forms.copy_of', ['name' => $form->name]);
        $newForm->save();

        return redirect()
            ->route('daylight.content.forms.edit', $newForm)
            ->with('success', __('daylight::forms.form_duplicated'));
    }

    public function destroySubmission(Form $form, FormSubmission $submission): RedirectResponse
    {
        abort_unless($submission->form_id === $form->id, 404);

        $this->deleteSubmissionFiles($submission);
        $submission->delete();

        return redirect()
            ->route('daylight.content.forms.submissions', $form)
            ->with('success', __('daylight::forms.submission_deleted'));
    }

    public function destroy(Form $form): RedirectResponse
    {
        $form->delete();

        return redirect()
            ->route('daylight.content.forms.index')
            ->with('success', __('daylight::forms.form_deleted'));
    }

    protected function deleteSubmissionFiles(FormSubmission $submission): void
    {
        if (empty($submission->files)) {
            return;
        }

        $disk = Storage::disk('media');

        foreach ($submission->files as $fieldId => $filePaths) {
            foreach ((array) $filePaths as $path) {
                if ($disk->exists($path)) {
                    $disk->delete($path);
                }
            }
        }
    }
}
