<?php
namespace Formipay\Notification;
use Formipay\Traits\SingletonTrait;
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

class Notification {

    use SingletonTrait;

    protected function __construct() {

        add_action( 'init',                         [$this, 'create_db'] );
        add_filter( 'formipay/global-settings/tab:general',    [$this, 'global_settings_general'], 40 );
        add_filter( 'formipay/global-settings',     [$this, 'add_menu_on_global_setting'], 40 );
        add_filter( 'formipay/form-config',         [$this, 'add_menu_on_product_setting'], 100 );

        add_action( 'formipay/notification/order',  [$this, 'order_trigger'] );
        add_action( 'formipay/notification/access', [$this, 'access_trigger'] );

    }

    public function create_db() {

        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();

        $create[] = "CREATE TABLE `{$wpdb->base_prefix}formipay_notification_log` (
            `id` bigint(20) NOT NULL AUTO_INCREMENT,
            `user_id` int,
            `customer_id` int,
            `order_id` int,
            `recipient_type` text,
            `media` text,
            `notification_data` longtext, 
            `status` text,
            `meta_data` text, 
            PRIMARY KEY (`id`)
        ) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        dbDelta($create);

    }

    public function insert_notification_data($args) {

        $args = wp_parse_args( $args, [
            'order_id'          => 0,
            'recipient_type'    => 'admin',
            'media'             => 'email',
            'notification_data' => [],
            'status'            => 'pending',
            'meta_data'         => []
        ] );

        global $wpdb;
        $table = $wpdb->prefix . 'formipay_notification_log';

        $insert_data = [
            'order_id'          => intval($args['order_id']),
            'recipient_type'    => sanitize_text_field($args['recipient_type']),
            'media'             => sanitize_text_field($args['media']),
            'notification_data' => maybe_serialize($args['notification_data']),
            'status'            => sanitize_text_field($args['status']),
            'meta_data'         => maybe_serialize($args['meta_data'])
        ];

        if($args['order_id'] > 0){
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->insert($table, $insert_data);

            return $wpdb->insert_id;
        }
        
        return false;
    }

    public function get_notification_data_by_id($notification_id) {

        global $wpdb;
        $table = $wpdb->prefix . 'formipay_notification_log';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $get = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM %i WHERE `id` = %d", $table, $notification_id
            )
        );

        return $get;

    }

    public function update_notification_data($notification_id, $args) {

        $recent_data = $this->get_notification_data_by_id($notification_id);

        $args = wp_parse_args( $args, [
            'order_id'          => $recent_data->order_id,
            'recipient_type'    => $recent_data->recipient_type,
            'media'             => $recent_data->media,
            'notification_data' => maybe_unserialize($recent_data->notification_data),
            'status'            => $recent_data->status,
            'meta_data'         => maybe_unserialize($recent_data->meta_data)
        ] );

        global $wpdb;
		$table_name = $wpdb->prefix . 'formipay_notification_log';

        $new_args = [
            'order_id'          => intval($args['order_id']),
            'recipient_type'    => sanitize_text_field($args['recipient_type']),
            'media'             => sanitize_text_field($args['media']),
            'notification_data' => maybe_serialize($args['notification_data']),
            'status'            => sanitize_text_field($args['status']),
            'meta_data'         => maybe_serialize($args['meta_data'])
        ];

		$where = [ 'id' => $notification_id ];
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$update = $wpdb->update( $table_name, $new_args, $where );

		return $update;
	
	}

    public function global_settings_general($fields) {

        $medias = apply_filters('formipay/notification/media', ['email'] );
        $notification_fields = [
            'notification_type_group' => [
                'type'              => 'group_title',
                'label'             => __( 'Notification Type', 'formipay'),
                'group'             => 'started',
            ],
        ];
        foreach($medias as $key => $media){
            $notification_fields['notification_'.$media.'_active'] = [
                'type'              => 'checkbox',
                'label'             => sprintf( __( '%s Notification', 'formipay'), ucfirst($media) ),
                'value'             => true
            ];
        }

        $last_notification_field = count($notification_fields) - 1;
        $notification_fields[$last_notification_field]['group'] = 'ended';
            
        $notification_fields['notification_email_sender_group_header'] = [
                'type'              => 'group_title',
                'label'             => __( 'Email Settings', 'formipay'),
                'group'             => 'started',
                'dependency'        => [
                    'key' => 'notification_email_active',
                    'value' => 'not_empty'
                ]
        ];

        foreach($medias as $key => $media){
            $notification_fields['notification_'.$media.'_admin_recipient'] = [
                'type'              => 'text',
                // translators: %s is the media type name.
                'label'             => sprintf( __( 'Admin\'s %s', 'formipay'), ucfirst($media) ),
                'dependency'        => [
                    'key' => 'notification_email_active',
                    'value' => 'not_empty'
                ]
            ];
        }
        $notification_fields['notification_name_admin_recipient'] = [
            'type'              => 'text',
            'label'             => __( 'Admin\'s Name', 'formipay'),
            'dependency'        => [
                'key' => 'notification_email_active',
                'value' => 'not_empty'
            ]
        ];

        $notification_fields['notification_email_logo'] = [
            'type'              => 'image',
            'label'             => __('Logo Image', 'formipay'),
            'dependency'        => [
                'key' => 'notification_email_active',
                'value' => 'not_empty'
            ]
        ];
        $notification_fields['notification_email_footer'] = [
            'type'              => 'tinymce',
            'label'             => __( 'Email Footer', 'formipay'),
            'dependency'        => [
                'key' => 'notification_email_active',
                'value' => 'not_empty'
            ]
        ];
        $notification_fields['notification_email_footer_links'] = [
            'type'              => 'repeater',
            'label'             => __( 'Icon Links', 'formipay' ),
            'fields'            => [
                'type'  => [
                    'type'      => 'select',
                    'label'     => __( 'Type', 'formipay' ),
                    'is_group_title' => true,
                    'options'   => [
                        'dribbble'  => 'Dribbble',
                        'facebook'  => 'Facebook',
                        'facebook-messenger' => 'Messenger',
                        'github'    => 'Github',
                        'instagram' => 'Instagram',
                        'link'      => 'Link',
                        'linkedin'  => 'Linkedin',
                        'pinterest' => 'Pinterest',
                        'telegram'  => 'Telegram',
                        'tiktok'    => 'Tiktok',
                        'whatsapp'  => 'WhatsApp',
                        'wordpress' => 'WordPress',
                        'x'         => 'X'
                    ],
                ],
                'link'  => [
                    'type'      => 'text',
                    'label'     => __( 'URL', 'formipay' )
                ]
            ],
            'group'             => 'ended',
            'dependency'        => [
                'key' => 'notification_email_active',
                'value' => 'not_empty'
            ]
        ];

        $fields = array_merge($fields, $notification_fields);
        return $fields;

    }

    public function add_menu_on_global_setting($fields) {

        $hints = formipay_editor_hints();
        $statuses = formipay_order_status_list();
        $medias = apply_filters('formipay/notification/media', ['email'] );

        
        $notification_fields = [];

        // access link

        $notification_fields['notification_email_access_link_group'] = [
            'type' => 'group_title',
            'label' => __( 'Access Link', 'formipay' ),
            'description' => __( 'This notification type is for responding request for access when people visit the thankyou page that contain any of your digital access (including files and URLs)', 'formipay' ),
            'group' => 'started',
            'submenu' => __( 'Access Link', 'formipay' ),
            'dependency'        => [
                'key'       => 'notification_email_active',
                'value'     => 'not_empty',
                'section'   => 'General'
            ]
        ];
        $notification_fields['notification_email_access_link_title'] = [
            'type' => 'text',
            'label' => __( 'Title', 'formipay' ),
            'value' => __( 'Your New Purchased Access Link', 'formipay' ),
            'submenu' => __( 'Access Link', 'formipay' ),
            'dependency'        => [
                'key'       => 'notification_email_active',
                'value'     => 'not_empty',
                'section'   => 'General'
            ]
        ];
        $notification_fields['notification_email_access_link_content'] = [
            'type' => 'tinymce',
            'label' => __( 'Content', 'formipay' ),
            'hints' => [
                'buyer_name' => __( 'Buyer Name', 'formipay' ),
                'order_id' => __( 'Order ID', 'formipay' ),
                'access_button' => __( 'Access Button', 'formipay' ),
                'access_link' => __( 'Access Link', 'formipay' ),
            ],
            'submenu' => __( 'Access Link', 'formipay' ),
            'value' => '<p>Hello {{buyer_name}},</p><p><br></p><p>Anyone request to access your purchase order ID&nbsp;<span style="background-color: transparent;">{{order_id}}</span><span style="background-color: transparent;">. Here is the new access link:</span></p><p>{{access_button}}<br></p><p><br></p><p>Here is the raw link if there is issue with the button:</p><p>{{access_link}}</p><p><br></p><p>Do not give access to others to make sure your purcase safe. Please ignore this email if it was not you.</p><p><br></p><p>Best regards,</p><p>Your E-commerce Team</p>',
            'group' => 'ended',
            'dependency'        => [
                'key'       => 'notification_email_active',
                'value'     => 'not_empty',
                'section'   => 'General'
            ]
        ];

        foreach($statuses as $key => $status){
            $status_key = str_replace('-', '_', $key);

            $notification_fields['notification_email_admin_'.$status_key.'_group_header'] = [
                'type'              => 'group_title',
                // translators: %s is the status of order.
                'label'             => sprintf( __( 'Email Notification Admin (%s)', 'formipay' ), $status),
                'group'             => 'started',
                'submenu'           => esc_html($status),
                'dependency'        => [
                    'key'       => 'notification_email_active',
                    'value'     => 'not_empty',
                    'section'   => 'General'
                ]
            ];
            $notification_fields['notification_email_admin_'.$status_key.'_toggle'] = [
                'type'              => 'checkbox',
                'label'             => __('Activate', 'formipay'),
                'submenu'           => esc_html($status),
                'dependency'        => [
                    'key'       => 'notification_email_active',
                    'value'     => 'not_empty',
                    'section'   => 'General'
                ]
            ];
            $notification_fields['notification_email_admin_'.$status_key.'_title'] = [
                'type'              => 'text',
                'label'             => __( 'Title', 'formipay' ),
                'submenu'           => esc_html($status),
                'dependency'        => [
                    [
                        'key'       => 'notification_email_admin_'.$status_key.'_toggle',
                        'value'     => 'not_empty'
                    ],
                    [
                        'key'       => 'notification_email_active',
                        'value'     => 'not_empty',
                        'section'   => 'General'
                    ]
                ],
                'dependencies'      => '&&'
            ];
            $notification_fields['notification_email_admin_'.$status_key.'_content'] = [
                'type'              => 'tinymce',
                'label'             => __( 'Content', 'formipay' ),
                'hints'             => [
                    'order_details'     => __( 'Order Details', 'formipay' ),
                    'order_items'       => __( 'Order Items', 'formipay' ),
                    'buyer_details'     => __( 'Buyer Details', 'formipay' ),
                    'buyer_name'        => __( 'Buyer Name', 'formipay' ),
                    'order_id'          => __( 'Order ID', 'formipay' ),
                    'order_status'      => __( 'Order Status', 'formipay' ),
                    'payment_timeout'   => __( 'Payment Timeout', 'formipay' )
                ],
                'submenu'           => esc_html($status),
                'dependency'        => [
                    [
                        'key'       => 'notification_email_admin_'.$status_key.'_toggle',
                        'value'     => 'not_empty'
                    ],
                    [
                        'key'       => 'notification_email_active',
                        'value'     => 'not_empty',
                        'section'   => 'General'
                    ]
                ],
                'dependencies'      => '&&',
                'group'             => 'ended',
            ];

            $notification_fields['notification_email_buyer_'.$status_key.'_group_header'] = [
                'type'              => 'group_title',
                // translators: %s is the status of order.
                'label'             => sprintf( __( 'Email Notification Buyer (%s)', 'formipay' ), $status),
                'group'             => 'started',
                'submenu'           => esc_html($status),
                'description'       => __( 'Email notification for buyer only available if your form is contain email field type', 'formipay'),
            ];
            $notification_fields['notification_email_buyer_'.$status_key.'_toggle'] = [
                'type'              => 'checkbox',
                'label'             => __('Activate', 'formipay'),
                'submenu'           => esc_html($status),
                'dependency'        => [
                    'key'       => 'notification_email_active',
                    'value'     => 'not_empty',
                    'section'   => 'General'
                ]
            ];
            $notification_fields['notification_email_buyer_'.$status_key.'_title'] = [
                'type'              => 'text',
                'label'             => __( 'Title', 'formipay' ),
                'submenu'           => esc_html($status),
                'dependency'        => [
                    [
                        'key'       => 'notification_email_buyer_'.$status_key.'_toggle',
                        'value'     => 'not_empty'
                    ],
                    [
                        'key'       => 'notification_email_active',
                        'value'     => 'not_empty',
                        'section'   => 'General'
                    ]
                ],
                'dependencies'      => '&&'
            ];
            $notification_fields['notification_email_buyer_'.$status_key.'_content'] = [
                'type'              => 'tinymce',
                'label'             => __( 'Content', 'formipay' ),
                'hints'             => [
                    'order_details'     => __( 'Order Details', 'formipay' ),
                    'order_items'       => __( 'Order Items', 'formipay' ),
                    'buyer_details'     => __( 'Buyer Details', 'formipay' ),
                    'buyer_name'        => __( 'Buyer Name', 'formipay' ),
                    'order_id'          => __( 'Order ID', 'formipay' ),
                    'order_status'      => __( 'Order Status', 'formipay' ),
                    'payment_timeout'   => __( 'Payment Timeout', 'formipay' )
                ],
                'submenu'           => esc_html($status),
                'dependency'        => [
                    [
                        'key'       => 'notification_email_buyer_'.$status_key.'_toggle',
                        'value'     => 'not_empty'
                    ],
                    [
                        'key'       => 'notification_email_active',
                        'value'     => 'not_empty',
                        'section'   => 'General'
                    ]
                ],
                'dependencies'      => '&&',
                'group'             => 'ended',
            ];

            $notification_fields = apply_filters('formipay/settings/notification/fields/'.$status_key, $notification_fields);

        }

        $fields['notification'] = [
            'name' => __('Notification', 'formipay'),
            'fields' => $notification_fields
        ];

        return $fields;

    }

    public function add_menu_on_product_setting($fields) {

        $notification_fields = [];

        $hints = formipay_editor_hints();
        $statuses = formipay_order_status_list();

        foreach($statuses as $key => $status){
            $status_key = str_replace('-', '_', $key);

            $notification_fields['product_notification_email_buyer_'.$status_key.'_group_header'] = [
                'type'              => 'group_title',
                // translators: %s is the status of order.
                'label'             => sprintf( __( 'Email Notification Buyer (%s)', 'formipay' ), $status),
                'group'             => 'started',
                'description'       => __( 'Email notification for buyer only available if your form is contain email field type', 'formipay'),
            ];

            $notification_fields['product_notification_email_buyer_'.$status_key.'_toggle'] = [
                'type'              => 'checkbox',
                'label'             => __('Replace Content', 'formipay'),
            ];

            $notification_fields['product_notification_email_buyer_'.$status_key.'_content'] = [
                'type'              => 'tinymce',
                'label'             => __( 'Email Content', 'formipay' ),
                'hints'             => $hints,
                'dependency'        => [
                    'key'       => 'product_notification_email_buyer_'.$status_key.'_toggle',
                    'value'     => 'not_empty'
                ],
                'group'             => 'ended',
            ];

            $notification_fields = apply_filters('formipay/product/notification/fields/', $notification_fields, $status_key);

        }

        $fields['formipay_form_settings']['notification'] = [
            'name' => __('Notification', 'formipay'),
            'fields' => $notification_fields
        ];

        return $fields;

    }

    public function order_trigger($order_data) {

        $medias = apply_filters('formipay/notification/media', ['email'] );
        $order_status = $order_data['status'];

        if(!empty($medias)){
            foreach($medias as $media){
                do_action(
                    'formipay/notification/order/'.$media, $order_data
                );
            }
        }

    }

    public function access_trigger($order_data) {

        $medias = apply_filters('formipay/notification/media', ['email'] );
         
        if(!empty($medias)){
            foreach($medias as $media){
                do_action(
                    'formipay/notification/access/'.$media, $order_data
                );
            }
        }

    }

}