<?php
/**
 * Plugin
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay\Forms
 */

namespace Wpayme\WordPress\Pay\Forms;

use Wpayme\WordPress\Pay\Forms\CouponAdmin;
use Wpayme\WordPress\Pay\Forms\EmailNotifications;

/**
 * Plugin class
 */
class Plugin {
    /**
     * Instance of this class.
     *
     * @var self
     */
    protected static $instance = null;

    /**
     * Plugin constructor.
     */
    public function __construct() {
        $this->register_hooks();
    }

    /**
     * Return an instance of this class.
     *
     * @return self A single instance of this class.
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Register hooks.
     */
    private function register_hooks() {
        // Add hooks here
        \add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
        \add_action('wp_enqueue_scripts', array($this, 'frontend_enqueue_scripts'));
        
        // AJAX handlers
        \add_action('wp_ajax_wpayme_validate_coupon', array($this, 'ajax_validate_coupon'));
        \add_action('wp_ajax_nopriv_wpayme_validate_coupon', array($this, 'ajax_validate_coupon'));
        
        // Process coupon form submissions
        \add_action('admin_init', array('Wpayme\WordPress\Pay\Forms\CouponPostType', 'process_form_submission'));
        \add_action('admin_init', array('Wpayme\WordPress\Pay\Forms\CouponPostType', 'process_deletion'));
        
        // Initialize the coupon post type
        CouponPostType::instance();
        
        // Initialize the coupon admin for proper menu registration
        new CouponAdmin();
        
        // Initialize email notifications
        EmailNotifications::instance();
        
        // Register async email handler
        \add_action('wpayme_pay_async_email', array($this, 'handle_async_email'));
    }

    /**
     * Enqueue admin scripts and styles.
     *
     * @return void
     */
    public function admin_enqueue_scripts() {
        $screen = \get_current_screen();
        
        // Only load on coupon edit screens
        if ($screen && $screen->post_type === CouponPostType::POST_TYPE) {
            // Enqueues are handled in CouponPostType class to avoid duplication
            /*
            // \wp_enqueue_style('jquery-ui-datepicker');
            \wp_enqueue_script('jquery-ui-datepicker');
            
            // Load Select2
            \wp_enqueue_style('wpayme-select2', \plugins_url('/assets/libs/select2/select2.min.css', \dirname(__DIR__) . '/wp-wpayme-pay-forms.php'), [], '4.1.0-rc.0');
            \wp_enqueue_script('wpayme-select2', \plugins_url('/assets/libs/select2/select2.min.js', \dirname(__DIR__) . '/wp-wpayme-pay-forms.php'), ['jquery'], '4.1.0-rc.0', true);
            
            \wp_enqueue_style('wpayme-pay-admin', \plugins_url('/assets/css/admin-style.css', \dirname(__FILE__)), ['wpayme-select2'], '1.0.0');
            \wp_enqueue_script('wpayme-pay-admin', \plugins_url('/assets/js/coupon-admin.js', \dirname(__FILE__)), ['jquery', 'jquery-ui-datepicker', 'wpayme-select2'], '1.0.0', true);
            
            // Localize script with admin variables
            \wp_localize_script('wpayme-pay-admin', 'wpayme_admin_vars', [
                'currency_symbol' => '€',
                'ajax_url' => \admin_url('admin-ajax.php'),
                'nonce' => \wp_create_nonce('wpayme_admin_nonce')
            ]);
            */
        }
    }

    /**
     * Enqueue frontend scripts and styles.
     *
     * @return void
     */
    public function frontend_enqueue_scripts() {
        \wp_enqueue_style('wpayme-pay-forms', \plugins_url('/assets/css/form-style.css', \dirname(__FILE__)), [], '1.0.0');
        \wp_enqueue_script('wpayme-pay-forms', \plugins_url('/assets/js/form.js', \dirname(__FILE__)), ['jquery'], '1.0.0', true);
        
        // Localize script with AJAX URL and nonce
        \wp_localize_script('wpayme-pay-forms', 'wpayme_form_vars', [
            'ajax_url' => \admin_url('admin-ajax.php'),
            'nonce'    => \wp_create_nonce('wpayme_form_nonce'),
        ]);
    }

    /**
     * AJAX handler for validating coupons.
     */
    public function ajax_validate_coupon() {
        // Check nonce
        if (!isset($_POST['nonce']) || !\wp_verify_nonce(\sanitize_key(\wp_unslash($_POST['nonce'])), 'wpayme_form_nonce')) {
            \wp_send_json_error(array('message' => \__('Security check failed', 'wpayme')));
            return;
        }
        
        // Get coupon code and form ID
        $coupon_code = isset($_POST['coupon_code']) ? \sanitize_text_field(\wp_unslash($_POST['coupon_code'])) : '';
        $form_id = isset($_POST['form_id']) ? \intval(\wp_unslash($_POST['form_id'])) : 0;
        
        // Validate coupon code
        $coupon = CouponPostType::validate_coupon($coupon_code, $form_id);
        
        if (!$coupon) {
            \wp_send_json_error(array('message' => \__('Invalid coupon code or coupon not applicable to this product', 'wpayme')));
            return;
        }
        
        // Ensure discount_amount is properly cast to float
        $coupon['discount_amount'] = (float) $coupon['discount_amount'];
        
        // Format coupon info for display
        $discount_type = $coupon['discount_type'];
        $discount_amount = $coupon['discount_amount'];
        
        if ($discount_type === 'percentage') {
            /* translators: %s: Discount amount */
            $message = \sprintf(\__('Coupon applied: %s%% discount', 'wpayme'), $discount_amount);
        } else {
            /* translators: %s: Formatted price */
            $message = \sprintf(\__('Coupon applied: %s discount', 'wpayme'), $this->format_price($discount_amount));
        }
        
        // Add message to coupon data
        $coupon['message'] = $message;
        
        \wp_send_json_success($coupon);
    }
    
    /**
     * Format price with currency symbol.
     * 
     * @param float $price The price to format.
     * @return string Formatted price.
     */
    private function format_price($price) {
        return '€' . \number_format($price, 2); // Default to Euro symbol
    }

    /**
     * Initialize plugin components.
     */
    public function initialize() {
        $this->forms_manager = new FormsManager();
        $this->coupon_admin = new CouponAdmin();
        
        // Register assets
        \add_action('wp_enqueue_scripts', array($this, 'register_assets'));
        \add_action('admin_enqueue_scripts', array($this, 'register_admin_assets'));
        
        // Add shortcodes
        \add_shortcode('wpayme_form', array($this, 'shortcode_form'));
        
        // Process form submission
        \add_action('wp_ajax_wpayme_submit_form', array($this, 'handle_form_submission'));
        \add_action('wp_ajax_nopriv_wpayme_submit_form', array($this, 'handle_form_submission'));
        
        // Process coupon validation
        \add_action('wp_ajax_wpayme_validate_coupon', array($this, 'handle_coupon_validation'));
        \add_action('wp_ajax_nopriv_wpayme_validate_coupon', array($this, 'handle_coupon_validation'));
        
        // Register submenu
        \add_action('admin_menu', array($this, 'register_submenus'));
        
        // Process coupon form submission
        \add_action('admin_init', array('Wpayme\WordPress\Pay\Forms\CouponPostType', 'process_form_submission'));
        \add_action('admin_init', array('Wpayme\WordPress\Pay\Forms\CouponPostType', 'process_deletion'));
    }

    /**
     * Register admin submenus.
     */
    public function register_submenus() {
        if (function_exists('add_submenu_page')) {
            \add_submenu_page(
                'wpayme',
                \__('Forms', 'wpayme'),
                \__('Forms', 'wpayme'),
                'manage_options',
                'edit.php?post_type=wpayme_form'
            );
            
            \add_submenu_page(
                'wpayme',
                \__('Coupons', 'wpayme'),
                \__('Coupons', 'wpayme'),
                'manage_options',
                'edit.php?post_type=wpayme_coupon'
            );
        }
    }

    /**
     * Handle async email sending.
     *
     * @param array $email_data Email data including to, subject, body, and headers.
     * @return void
     */
    public function handle_async_email($email_data) {
        if (empty($email_data) || !is_array($email_data)) {
            return;
        }
        
        $to = isset($email_data['to']) ? $email_data['to'] : '';
        $subject = isset($email_data['subject']) ? $email_data['subject'] : '';
        $body = isset($email_data['body']) ? $email_data['body'] : '';
        $headers = isset($email_data['headers']) ? $email_data['headers'] : [];
        
        if (empty($to) || empty($subject) || empty($body)) {
            return;
        }
        
        \wp_mail($to, $subject, $body, $headers);
    }
}

// Initialize the plugin
Plugin::instance();