<?php
/**
 * This file will create Custom Rest API End Points.
 */
class FWFORMS_Rest_Route {

    public function __construct() {
        add_action( 'rest_api_init', [ $this, 'create_rest_routes' ] );
    }

    public function create_rest_routes() {
        register_rest_route( 'wprk/v1', '/settings', [
            'methods' => 'GET',
            'callback' => [ $this, 'get_settings' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ] );
        register_rest_route( 'wprk/v1', '/settings', [
            'methods' => 'POST',
            'callback' => [ $this, 'save_settings' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ] );
        register_rest_route( 'wprk/v1', '/settings', [
            'methods' => 'DELETE',
            'callback' => [ $this, 'delete_settings' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ] );
        register_rest_route( 'wprk/v1', '/templates/(?P<id>.+)', [
            'methods' => 'GET',
            'callback' => [ $this, 'get_template' ],
            'args' => array(
                'id' => array( 
                    'validate_callback' => function( $param, $request, $key ) {
                        return is_string( $param );
                    }
                ),
            ),
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ] );
        register_rest_route( 'wprk/v1', '/templates', [
            'methods' => 'POST',
            'callback' => [ $this, 'save_template' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ] );
        register_rest_route( 'wprk/v1', '/templates', [
            'methods' => 'PUT',
            'callback' => [ $this, 'update_template' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ] );
        register_rest_route( 'wprk/v1', '/templates', [
            'methods' => 'GET',
            'callback' => [ $this, 'get_templates' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/templates/(?P<id>.+)', [
            'methods' => 'DELETE',
            'callback' => [ $this, 'delete_template' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/templates', [
            'methods' => 'DELETE',
            'callback' => [ $this, 'delete_templates' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/template/bulk_delete', [
            'methods' => 'DELETE',
            'callback' => [ $this, 'bulk_delete_template' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);        
        register_rest_route( 'wprk/v1', '/submission/bulk_delete', [
            'methods' => 'DELETE',
            'callback' => [ $this, 'bulk_delete_submission' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/submissions', [
            'methods' => 'POST',
            'callback' => [ $this, 'save_form_submissions' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/submissions', [
            'methods' => 'GET',
            'callback' => [ $this, 'get_form_submissions' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/submissions/(?P<id>.+)', [
            'methods' => 'GET',
            'callback' => [ $this, 'get_form_submission' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/submissions/(?P<id>.+)', [
            'methods' => 'DELETE',
            'callback' => [ $this, 'delete_form_submission' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/submissions', [
            'methods' => 'DELETE',
            'callback' => [ $this, 'delete_form_submissions' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
        register_rest_route( 'wprk/v1', '/webhooks', [
            'methods' => 'POST',
            'callback' => [ $this, 'handle_webhooks' ],
            'permission_callback' => [ $this, 'admin_permissions_check' ]
        ]);
    }

    public function get_settings() {
        $email     = get_option( 'wprk_settings_email' );
        $response = [
            'data' => array(
                'email' => $email,
                'statusCode' => 200
            ),
        ];

        return rest_ensure_response( $response );
    }


    public function save_settings( $req ) {
        $email     = sanitize_text_field( $req['email'] );
        $country     = sanitize_text_field( $req['countryName'] );
        $body = array(
            'email' => $email,
            'country' => $country,
            'status' => 'subscribed',
        );
         
        $body = wp_json_encode( $body );
         
        $options = array(
            'method'        => "POST",
            'body'        => $body,
            'headers'     => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json', 
            ],
            'timeout'     => 60,
            'redirection' => 5,
            'blocking'    => true,
            'httpversion' => '1.1',
            'sslverify'   => false,
            'data_format' => 'body',
        );

        $response = wp_remote_request( 'https://hooks.zapier.com/hooks/catch/9584469/b99hgoc', $options );
        $responseStatusCode = json_decode(json_encode($response), true)['response']['code'];
        $responseStatusCode = $responseStatusCode == 409 ? 200 : $responseStatusCode;
        if($responseStatusCode == 200){
            update_option( 'wprk_settings_email', $email );
        }
        
        return rest_ensure_response( array(
            'data' => array(
                'email' => $email,
                'statusCode' => $responseStatusCode
            ),
        ), 200 );
    }
    public function delete_settings( $req ) {
        $deleted = delete_option( 'wprk_settings_email', $email );
        return rest_ensure_response( array(
            'success'   => $deleted,
            'value'     => ''
        ) );
    }
     public function get_template( $request ) {
        $template_id = $request->get_param( 'id' );
        // Do some external function call that returns product data or empty array on error
        $template_data = get_option( $template_id );
        if ( empty( $template_data ) ) {
            return new WP_REST_Response( [
                'message' => 'Template was not found',
            ], 400 );
        }
        return new WP_REST_Response( array("data"=> $template_data), 200 );
    }
     
    public function get_templates( $request ) {
        $templates = get_option( "templates" );
        if ( !is_array( $templates ) ) {
            return new WP_REST_Response( array(
                'data'   => [],
            ), 200 );
        }
        return new WP_REST_Response( array(
            'data'   => $templates,
        ), 200 );
    }
    


    public function save_template( $req ) {
        $template = sanitize_post($req['template']);
        $template["created"] = date('d-m-y h:i:s');
        $created = update_option( $template["id"], $template );
        $get_stored_templates = get_option( 'templates');
        $templateObject = new stdClass();
        $templateObject->id = $template["id"];
        $templateObject->title = $template["title"];
        $templateObject->imageUrl = $template["imageUrl"];
        $templateObject->description = $template["description"];
        $templateObject->created = $template["created"];
        if(empty($get_stored_templates)){
            update_option( "templates", [$templateObject] );
        }
        else{
            array_push($get_stored_templates, $templateObject);
            update_option( "templates",  $get_stored_templates);
        }
        return rest_ensure_response( array(
            'data'   => $template,
        ), 200 );
    }
    // Form submissions
    public function get_form_submissions( $request ) {
        $submissions = get_option( "submissions" );
        if ( !is_array( $submissions ) ) {
            return new WP_REST_Response( array(
                'data'   => [],
            ), 200 );
        }
        return new WP_REST_Response( array(
            'data'   => $submissions,
        ), 200 );
    }
    
    public function get_form_submission( $request ) {
        $form_submission_id = $request->get_param( 'id' );
        // Do some external function call that returns product data or empty array on error
        $submission_data = get_option( $form_submission_id );
        if ( empty( $submission_data ) ) {
            return new WP_REST_Response( [
                'message' => 'Form submission was not found',
            ], 400 );
        }
        return new WP_REST_Response( array("data"=> $submission_data), 200 );
    }


    public function save_form_submissions( $req ) {
        $formData = sanitize_post($req['form']);
        $formData["created"] = date('d-m-y h:i:s');
        $updated = update_option( $formData["id"], $formData );
        $get_stored_submissions = get_option( 'submissions');
        unset($formData['ID']);
        if(empty($get_stored_submissions)){
            update_option( "submissions", [$formData] );
        }
        else{
            array_push($get_stored_submissions, $formData);
            update_option( "submissions",  $get_stored_submissions);
        }
        return rest_ensure_response( array(
            'data'   => $formData,
        ), 200 );
    }

    public function delete_form_submission( $req ) {
        $get_stored_submissions = get_option( 'submissions');
        $submission_id = $req-> get_param( 'id' );
        $new_array = array_filter($get_stored_submissions, function($submission) use ($submission_id){
            if ($submission['id'] == $submission_id) return false;
            return true;
        });
                $deleted = delete_option( $submission_id );
                update_option( "submissions",  $new_array);
        return rest_ensure_response( array(
            'success'=>$deleted
        ));
    }

    public function delete_form_submissions( $req ) {
        $deleted = delete_option( 'submissions');
        return rest_ensure_response( array(
            'success'   => $deleted,
        ));
    }

    public function update_template( $req ) {
        $template = sanitize_post($req['template']);
        $template["created"] = date('d-m-y h:i:s');
        $updated = update_option( $template["id"], $template );
        $get_stored_templates = get_option( 'templates');
        $templateObject = new stdClass();
        $templateObject->id = $template["id"];
        $templateObject->title = $template["title"];
        $templateObject->imageUrl = $template["imageUrl"];
        $templateObject->description = $template["description"];
        $templateObject->created = $template["created"];
        
        $keys = array_column($get_stored_templates, 'id');
        $index = array_search($template["id"], $keys);
        $index2 = array_keys($get_stored_templates);
        $realindex=$index2[$index];
        $templates = [];
        if ($index !== false) {
            //$get_stored_templates[$index] = $templateObject;
            $replaceTemplate = array($realindex => $templateObject);
            $templates = array_replace($get_stored_templates, $replaceTemplate);
            update_option( "templates",  $templates);
        }
        return rest_ensure_response( array(
            'data'   => $templates,
            'index'   => $index,
        ), 200 );
    }

    public function delete_template( $req ) {
        $get_stored_templates = get_option( 'templates');
        $template_id = $req-> get_param( 'id' );
        $new_array = array_filter($get_stored_templates, function($template) use ($template_id){
            if ($template->id == $template_id) return false;
            return true;
        });
        $deleted = delete_option( $template_id );
        update_option( "templates",  $new_array);
        return rest_ensure_response( array(
            'success'   => $deleted,
        ));
    }

    public function delete_templates( $req ) {
        $deleted = delete_option( 'templates');
        return rest_ensure_response( array(
            'success'   => $deleted,
        ));
    }
    
    public function bulk_delete_template( $req ) {
        $get_stored_templates = get_option( 'templates');
        $template_id_array = $req-> get_param( 'templateIds' );
        $new_array = array_filter($get_stored_templates, function($template) use ($template_id_array){
            if (in_array($template->id,$template_id_array)) return false;
            return true;
        });
        foreach ($template_id_array as $id){
            $deleted = delete_option( $id );
        }
        update_option( "templates",  $new_array);
        return rest_ensure_response( array(
            'success'   => $deleted,
            'new'=>$new_array
        ));
    }

    public function bulk_delete_submission( $req ) {
        $get_stored_submissions = get_option( 'submissions');
        $submission_id = $req-> get_param( 'submissionIds' );
        $new_array = array_filter($get_stored_submissions, function($submission) use ($submission_id){
            if (in_array($submission['id'],$submission_id)) return false;
            return true;
        });
        foreach($submission_id as $id){
            $deleted = delete_option( $id );
        }
        update_option( "submissions",  $new_array);
        return rest_ensure_response( array(
           'success'=> $deleted,
           "data"=>$new_array
        ));
    }

    public function handle_webhooks( $req ) {
        $req_data = sanitize_post($req['data']);
        $webhooks = $req_data["webhooks"];
        $form_data = $req_data["form"];
         
        try {
        $body = wp_json_encode( $form_data );
        $api_responses = new stdClass();   
        foreach( $webhooks as $webhook ){
            $options = array(
                'method'        => strtoupper($webhook["method"]),
                'body'        => $body,
                'headers'     => $webhook["headers"],
                'timeout'     => 60,
                'redirection' => 5,
                'blocking'    => true,
                'httpversion' => '1.1',
                'sslverify'   => false,
                'data_format' => 'body',
            );
    
            $response = wp_remote_request( $webhook["url"], $options );
            $responseStatusCode = json_decode(json_encode($response), true)['response']['code'];
            $api_responses->{$webhook["url"]}=$responseStatusCode;
        }
        return rest_ensure_response( array(
            'success'   => $api_responses,
        ));
    }catch(\Exception $ex){
        return rest_ensure_response( array(
            'errors'   => $ex,
        ));
    }

        
    }

    public function admin_permissions_check() {
        return current_user_can( 'publish_posts' );
    }
    
}
new FWFORMS_Rest_Route();