<?php

// BACKEND CONTROLLER WITH MODEL,EVENT-LISTENER

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
//use Rvsitebuilder\Wysiwyg\Events\AfterFormCreatedEvent;
//use Rvsitebuilder\Wysiwyg\Http\Requests\HtmlFormRequest;
use Lib\Util\RVLog;
use Rvsitebuilder\Core\Models\CoreForm;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;

class FormController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function index(Request $request)
    {
        /*
        $forms = Form::all();

    	if($request->ajax()){
            return view('wysiwyg::backend.form.index',compact('forms'))->renderSections()['content'];
        }else{
            return view('wysiwyg::backend.form.index',compact('forms'));
        }
        */
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $response = [
                'status' => 'fail',
                'msg' => '',
                'debug_msg' => '',
        ];

        $form = new CoreForm;
        $form->form_owner_id = $request->form_owner_id;
        $form->form_mail_content = $request->form_mail_content;
        $form->form_field_data = $request->form_field_data;
        $form->form_design_data = $request->form_design_data;
        $form->action_type = $request->action_type;
        $form->external_url = $request->external_url;
        $form->send_to_user = $request->send_to_user;
        $form->subject = $request->subject;
        $form->sender_email = $request->sender_email;
        $form->sender_name = $request->sender_name;
        $form->reply_to_email = $request->reply_to_email;
        $form->send_to_admin = $request->send_to_admin;
        $form->save();
        $insertedFormId = $form->id;

        $response = [
                'status' => 'success',
                'msg' => 'The item has create.',
                'item_id' => $insertedFormId,
                //'debug_msg' => $debug_msg
        ];

        return response()->json($response);
    }

    public function saveformdata(Request $request)
    {
        $response = [
            'status' => 'fail',
            'msg' => '',
            'debug_msg' => '',
        ];

        $page_id = $request->page_id;

        $formAdd = $request->add;
        $formUpdate = $request->update;
        $formRemove = $request->remove;

        RVLog::debug('saveformdata');

        RVLog::debug('form add '.var_export($formAdd, true));
        RVLog::debug('form update '.var_export($formUpdate, true));
        RVLog::debug('form remove '.var_export($formRemove, true));

        if (null != $formAdd) {
            foreach ($formAdd as $form_attr_id => $val) {
                $coreFormModel = new CoreForm();

                $coreFormModel->form_attr_id = $form_attr_id;
                $coreFormModel->form_owner_id = $page_id;

                //$coreFormModel->form_mail_content = ;
                $coreFormModel->form_mail_content = self::buildMailTemplate($formAdd[$form_attr_id]['data'], $form_attr_id, $formAdd[$form_attr_id]['field_data']);

                $coreFormModel->form_design_data = $formAdd[$form_attr_id]['data'];

                $formAdd[$form_attr_id]['field_data'] = self::updateStructFormFieldData($formAdd[$form_attr_id]['field_data']);
                RVLog::debug('formAdd field_data '.var_export($formAdd[$form_attr_id]['field_data'], true));

                $coreFormModel->form_field_data = json_encode($formAdd[$form_attr_id]['field_data']);

                $coreFormModel->action_type = $formAdd[$form_attr_id]['setting']['form-typeSubmit']['value'];

                $coreFormModel->send_to_user = '0';
                if (isset($formAdd[$form_attr_id]['setting']['form-sendToUser'])) {
                    $coreFormModel->send_to_user = self::booleanStringToNum($formAdd[$form_attr_id]['setting']['form-sendToUser']['value']);
                }

                $coreFormModel->subject = self::nullStringToBlank($formAdd[$form_attr_id]['setting']['form-apform-subject']['value']);

                $coreFormModel->sender_email = self::nullStringToBlank($formAdd[$form_attr_id]['setting']['form-apform-SenderEmail']['value']);
                $coreFormModel->sender_name = self::nullStringToBlank($formAdd[$form_attr_id]['setting']['form-apform-SenderName']['value']);
                $coreFormModel->reply_to_email = self::nullStringToBlank($formAdd[$form_attr_id]['setting']['form-apform-ReplyTo']['value']);

                $coreFormModel->send_to_admin = self::booleanStringToNum($formAdd[$form_attr_id]['setting']['form-sendToAdmin']['value']);
                $coreFormModel->subject_to_admin = self::nullStringToBlank($formAdd[$form_attr_id]['setting']['form-apformadmin-subject']['value']);
                $coreFormModel->admin_recipient = self::nullStringToBlank($formAdd[$form_attr_id]['setting']['form-apformadmin-Recipient']['value']);

                $coreFormModel->external_url = self::nullStringToBlank($formAdd[$form_attr_id]['setting']['form-inputExternal']['value']);

                $coreFormModel->save();
            }

            //$insertedFormId = $form->id;
        }

        if (null != $formUpdate) {
            foreach ($formUpdate as $form_attr_id => $val) {
                $coreFormModel = CoreForm::where('form_attr_id', $form_attr_id)->first();

                if ($coreFormModel) {
                    $formUpdate[$form_attr_id]['field_data'] = self::updateStructFormFieldData($formUpdate[$form_attr_id]['field_data']);
                    RVLog::debug('formUpdate field_data '.var_export($formUpdate[$form_attr_id]['field_data'], true));
                    $coreFormModel->form_field_data = json_encode($formUpdate[$form_attr_id]['field_data']);

                    $coreFormModel->form_mail_content = self::buildMailTemplate($formUpdate[$form_attr_id]['data'], $form_attr_id, $formUpdate[$form_attr_id]['field_data']);

                    $coreFormModel->form_design_data = $formUpdate[$form_attr_id]['data'];

                    $coreFormModel->action_type = $formUpdate[$form_attr_id]['setting']['form-typeSubmit']['value'];

                    if (isset($formUpdate[$form_attr_id]['setting']['form-sendToUser'])) {
                        $coreFormModel->send_to_user = self::booleanStringToNum($formUpdate[$form_attr_id]['setting']['form-sendToUser']['value']);
                    }
                    $coreFormModel->subject = self::nullStringToBlank($formUpdate[$form_attr_id]['setting']['form-apform-subject']['value']);

                    $coreFormModel->sender_email = self::nullStringToBlank($formUpdate[$form_attr_id]['setting']['form-apform-SenderEmail']['value']);
                    $coreFormModel->sender_name = self::nullStringToBlank($formUpdate[$form_attr_id]['setting']['form-apform-SenderName']['value']);
                    $coreFormModel->reply_to_email = self::nullStringToBlank($formUpdate[$form_attr_id]['setting']['form-apform-ReplyTo']['value']);

                    $coreFormModel->send_to_admin = self::booleanStringToNum($formUpdate[$form_attr_id]['setting']['form-sendToAdmin']['value']);
                    $coreFormModel->subject_to_admin = self::nullStringToBlank($formUpdate[$form_attr_id]['setting']['form-apformadmin-subject']['value']);
                    $coreFormModel->admin_recipient = self::nullStringToBlank($formUpdate[$form_attr_id]['setting']['form-apformadmin-Recipient']['value']);

                    $coreFormModel->external_url = self::nullStringToBlank($formUpdate[$form_attr_id]['setting']['form-inputExternal']['value']);

                    $coreFormModel->save();
                }
            }

            //$insertedFormId = $form->id;
        }

        if (null != $formRemove) {
            foreach ($formRemove as $form_attr_id => $val) {
                $coreFormModel = CoreForm::where('form_attr_id', $form_attr_id)->first();
                if ($coreFormModel) {
                    $coreFormModel->delete();
                }
            }
        }

        /*
        $form = new Form;
        $form->form_owner_id = $request->form_owner_id;
        $form->form_mail_content = $request->form_mail_content;
        $form->form_field_data = $request->form_field_data;
        $form->form_design_data = $request->form_design_data;
        $form->action_type = $request->action_type;
        $form->external_url = $request->external_url;
        $form->send_to_user = $request->send_to_user;
        $form->subject = $request->subject;
        $form->sender_email = $request->sender_email;
        $form->sender_name = $request->sender_name;
        $form->reply_to_email = $request->reply_to_email;
        $form->send_to_admin = $request->send_to_admin;
        $form->save();
        $insertedFormId = $form->id;
        */
        $response = [
            'status' => 'success',
            'msg' => 'The item has create.',
            //'item_id' => $insertedFormId
            //'debug_msg' => $debug_msg
        ];

        return response()->json($response);
    }

    public function updateStructFormFieldData($form_field_data)
    {
        //return $form_field_data;
        foreach ($form_field_data as $key => $value) {
            if ('radio' == $form_field_data[$key]['type'] || 'checkbox' == $form_field_data[$key]['type']) {
                $mainName = $form_field_data[$key]['name'];
                $mainName = preg_replace("/\[[0-9]+\]$/", '', $mainName);

                if (!isset($form_field_data[$mainName])) {
                    $form_field_data[$mainName] = [];
                    $form_field_data[$mainName]['validation_rules'] = $form_field_data[$key]['validation_rules'];

                    $form_field_data[$mainName]['value'] = '';
                    $form_field_data[$mainName]['name'] = $mainName;
                    $form_field_data[$mainName]['type'] = $form_field_data[$key]['type'];
                }
                $form_field_data[$mainName]['value'] = $form_field_data[$mainName]['value'].'|'.$form_field_data[$key]['value'];

                unset($form_field_data[$key]);
            }
        }

        return $form_field_data;
    }

    public function buildMailTemplate($form_html, $form_attr_id, $form_field_data)
    {
        //$form_html

        preg_match("/(.*?)(<form.*?>.*?<\/form>)/s", $form_html, $matches);

        $form_css = $matches[1];

        //$form_css = file_get_contents('/var/www/html/vendor/uikit-2.27.4/css/uikit-components-all.min.css') ."\n" . $form_css;
        // vendor/uikit-2.27.4/css/uikit-components-all.min.css
        $form_content = $matches[2];
        //Log::info('$form_css = '. $form_css);
        //Log::info('$form_content = '. $form_content);

        foreach ($form_field_data as $key => $val) {
            $preg_key = str_replace('[', '\[', $key);
            $preg_key = str_replace(']', '\]', $preg_key);
            $form_content = preg_replace("/(id=\"$preg_key\")/", '\1 value="{{'.$preg_key.'}}"', $form_content);
            $form_content = preg_replace("/<textarea.*?id=\"$preg_key\".*?>/s", '\0\1{{'.$preg_key.'}}', $form_content);
            $form_content = preg_replace("/<select.*?id=\"$preg_key\".*?>.*?<\/select>/s",
                '<input name="'.$preg_key.'" type="text" value="{{'.$preg_key.'}}" >',
                $form_content);
        }

        $cssToInlineStyles = new CssToInlineStyles();

        $form_css = '
        input,textarea,select {
            pointer-events: none;
        }
        '.$form_css;

        // output
        $mail_content = $form_content;

        $mail_content = $cssToInlineStyles->convert(
            $form_content,
            $form_css
            );

        return $mail_content;
    }

    public function booleanStringToNum($booleanString)
    {
        $num = $booleanString;
        if ('true' == $booleanString) {
            $num = '1';
        }
        if ('false' == $booleanString) {
            $num = '0';
        }

        return $num;
    }

    public function nullStringToBlank($nullString)
    {
        $str = $nullString;
        if ('null' == $nullString || 'NULL' == $nullString) {
            $str = '';
        }

        return $str;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param mixed   $itemid
     *
     * @return Response
     */
    public function update(Request $request, $itemid)
    {
        $response = [
                'status' => 'fail',
                'msg' => '',
                'debug_msg' => '',
        ];

        $form = Form::find($itemid);

        if ($form) {
            $form->form_owner_id = $request->form_owner_id;
            $form->form_mail_content = $request->form_mail_content;
            $form->form_field_data = $request->form_field_data;
            $form->form_design_data = $request->form_design_data;
            $form->action_type = $request->action_type;
            $form->external_url = $request->external_url;
            $form->send_to_user = $request->send_to_user;
            $form->subject = $request->subject;
            $form->sender_email = $request->sender_email;
            $form->sender_name = $request->sender_name;
            $form->reply_to_email = $request->reply_to_email;
            $form->send_to_admin = $request->send_to_admin;
            $form->save();
        }

        $response = [
                'status' => 'success',
                'msg' => 'The item has update.',
                //'debug_msg' => $debug_msg
        ];

        return response()->json($response);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param mixed $itemid
     *
     * @return Response
     */
    public function destroy($itemid)
    {
        $response = [
                'status' => 'fail',
                'msg' => '',
                'debug_msg' => '',
        ];

        $form = Form::find($itemid);

        if ($form) {
            $form->delete();
        }

        $response = [
                'status' => 'success',
                'msg' => 'The item has delete.'.$itemid,
                //'debug_msg' => $debug_msg
        ];

        return response()->json($response);
    }
}
