<?php

/**
 * The admin-facing functionality of the plugin.
 *
 * @link       https://themeatelier.net
 * @since      1.0.0
 *
 * @package    domain-for-sale
 * @subpackage domain-for-sale/Admin
 * @author     ThemeAtelier <themeatelierbd@gmail.com>
 */

namespace ThemeAtelier\DomainForSale\Admin;

use WP_REST_Server;
use WP_REST_Request;

use ThemeAtelier\DomainForSale\Frontend\Helpers\Helpers;

/**
 * Handles admin functionality for domain offers.
 */
class Offers
{
    /**
     * Constructor.
     *
     * Hooks into WordPress actions and initializes required methods.
     *
     * @since 3.1.0
     */
    function __construct()
    {
        add_action('admin_head', array($this, 'dfs_localize_script'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'), 100);
        add_action('rest_api_init', [$this, 'register_rest_routes']);

        $this->create_domain_for_sale_offers_table();
    }

    /**
     * Localizes frontend strings for use in JavaScript.
     *
     * @since 3.1.0
     */
    public function dfs_localize_script()
    {
    ?>
        <script>
            window.domainForSaleString = <?php echo json_encode(self::domain_for_sale_string()); ?>;
        </script>
<?php
    }

    /**
     * Creates the offers database table if it doesn't exist.
     *
     * @since 3.1.0
     */
    public function create_domain_for_sale_offers_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'domain_for_sale_offers';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        field LONGTEXT NOT NULL,
        meta LONGTEXT NOT NULL,
        verify_email VARCHAR(255) DEFAULT '' NOT NULL,
    	verify_status VARCHAR(20) DEFAULT 'pending' NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (id)
    ) $charset_collate;";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Enqueues scripts and injects localized variables for the Offers page.
     *
     * @param string $hook Current admin page hook.
     *
     * @since 3.1.0
     */
    public static function enqueue_scripts($hook)
    {
        if ($hook === 'toplevel_page_domain-for-sale') {
            add_action('admin_print_scripts', function () {
                $options = get_option('dfs-opt');
                $price_currency = isset($options['price_currency']) ? $options['price_currency'] : 'usd';

                echo wp_print_inline_script_tag(
                    'window.domainForSale = ' . wp_json_encode([
                        'restUrl' => esc_url_raw(rest_url('domain-for-sale/v1')),
                        'nonce'   => wp_create_nonce('wp_rest'),
                        'price_currency'   => $price_currency,
                    ]) . ';'
                );
            });

            wp_enqueue_script(
                'domain-for-sale-admin-ui',
                plugin_dir_url(__FILE__) . 'assets/js/domain-for-sale-admin-ui.js',
                array(),
                DOMAIN_FOR_SALE_VERSION,
                true
            );
        }
    }

    /**
     * Registers REST API routes for Offers.
     *
     * @since 3.1.0
     */
    public function register_rest_routes()
    {
        register_rest_route(
            'domain-for-sale/v1',
            '/offers',
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [$this, 'domain_for_sale_offers'],
                'permission_callback' => [Helpers::class, 'domain_for_sale_dashboard_capability'],
            ]
        );

        // Delete offers by ID
        register_rest_route(
            'domain-for-sale/v1',
            '/offers/(?P<id>\d+)',
            [
                'methods'             => WP_REST_Server::DELETABLE,
                'callback'            => [$this, 'delete_domain_for_sale_offers'],
                'permission_callback' => [Helpers::class, 'domain_for_sale_dashboard_capability'],
                'args'                => [
                    'id' => [
                        'validate_callback' => fn($param) => is_numeric($param),
                    ],
                ],
            ]
        );
    }

    /**
     * Deletes an offer by ID.
     *
     * @param \WP_REST_Request $request REST API request.
     * @return \WP_REST_Response|\WP_Error
     *
     * @since 3.1.0
     */
    public function delete_domain_for_sale_offers(\WP_REST_Request $request)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'domain_for_sale_offers';
        $id = intval($request['id']);

        $deleted = $wpdb->delete($table_name, ['id' => $id], ['%d']);

        if ($deleted === false) {
            return new \WP_Error('db_error', 'Failed to delete offers', ['status' => 500]);
        }

        if ($deleted === 0) {
            return new \WP_Error('not_found', 'Offers not found', ['status' => 404]);
        }

        return new \WP_REST_Response(['deleted' => true, 'id' => $id], 200);
    }

    /**
     * Gets all offers.
     *
     * @param \WP_REST_Request $request REST API request.
     * @return \WP_REST_Response
     *
     * @since 3.1.0
     */
    public function domain_for_sale_offers(\WP_REST_Request $request)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'domain_for_sale_offers'; // table name
        $results = $wpdb->get_results("SELECT * FROM {$table_name}", ARRAY_A);

        foreach ($results as &$row) {
            if (!empty($row['field'])) {
                $unserialized = @unserialize($row['field']);
                if ($unserialized !== false) {
                    $row['field'] = $unserialized; // now it's an array
                }
            }
            if (!empty($row['meta'])) {
                $unserialized = @unserialize($row['meta']);
                if ($unserialized !== false) {
                    $row['meta'] = $unserialized; // now it's an array
                }
            }
        }

        return new \WP_REST_Response($results, 200);
    }

    /**
     * Sends verification email to bidder.
     *
     * @param string $verification_token Verification token.
     * @param array  $formData Submitted form data.
     * @param array  $meta     Offer metadata.
     *
     * @since 3.1.0
     */
    public static function verification_mail($formData, $meta, $if_resend = true)
    {
        $options            = get_option('dfs-opt');
        $bidder_email_confirmation = !empty($options['bidder_confirmations']) ? $options['bidder_confirmations'] : [];
        $email_confirmation = in_array('confirmation', $bidder_email_confirmation) ? '1' : '0';
        $bidder_confirmation_form_name = isset($options['bidder_confirmation_form_name']) ? $options['bidder_confirmation_form_name'] : '{siteTitle}';
        $bidder_confirmation_form_email = isset($options['bidder_confirmation_form_email']) ? $options['bidder_confirmation_form_email'] : '{adminEmail}';
        $bidder_confirmation_subject = isset($options['bidder_confirmation_subject']) ? $options['bidder_confirmation_subject'] : 'New Offer For {domain}';

        $bidder_confirmation_message = isset($options['bidder_confirmation_message']) ? $options['bidder_confirmation_message'] : 'Dear {name};\nThanks for your offer. We will review your submission and will back to you soon!\n\nThis was your submission: {name}, {email}, {phone}, {offer}, {proposal}, {domain}';
        $email = isset($formData['email']) ? $formData['email'] : '';

        if ($email_confirmation) {
            $email_template = $bidder_confirmation_message;
        } else {
            $email_template = false;
        }
        $email_body = Helpers::dfs_dynamic_variables($email_template, $formData, '', $meta);
        $email_form_name = Helpers::dfs_dynamic_variables($bidder_confirmation_form_name, $formData);
        $email_form_email = Helpers::dfs_dynamic_variables($bidder_confirmation_form_email, $formData);
        $email_subject = Helpers::dfs_dynamic_variables($bidder_confirmation_subject, $formData);

        if ($email_template) {
            // Send verification email
            $headers = [
                'From: ' . $email_form_name . ' <' . $email_form_email . '>'
            ];

            wp_mail($email, $email_subject, $email_body, $headers);
        }
    }

    /**
     * Returns localized strings for the offers admin UI.
     *
     * @return array
     *
     * @since 3.1.0
     */
    public static function domain_for_sale_string()
    {
        return [
            'contact_form_offers' => esc_html__('Offers', 'domain-for-sale'),
            'all_email' => esc_html__('All Email', 'domain-for-sale'),
            'pending_verification' => esc_html__('Pending Verification', 'domain-for-sale'),
            'verified' => esc_html__('Verified', 'domain-for-sale'),
            'resend' => esc_html__('Resend', 'domain-for-sale'),
            'you_can_resend_again_within' => esc_html__('You can resend again within', 'domain-for-sale'),
            'all_domain' => esc_html__('All Domain', 'domain-for-sale'),
            'all_extension' => esc_html__('All Extension', 'domain-for-sale'),
            'search' => esc_html__('Search', 'domain-for-sale'),
            'loading' => esc_html__('Loading...', 'domain-for-sale'),
            'delete_offer' => esc_html__('Delete Offer', 'domain-for-sale'),
            'are_you_sure_you_want_to_delete_this_offer' => esc_html__('Are you sure you want to delete this offer?', 'domain-for-sale'),
            'cancel' => esc_html__('Cancel', 'domain-for-sale'),
            'yes_delete' => esc_html__('Yes, Delete', 'domain-for-sale'),
            'offers_deleted_successful' => esc_html__('Offer(s) deleted successfully!', 'domain-for-sale'),
            'delete_failed' => esc_html__('Delete failed!', 'domain-for-sale'),
            'failed_to_delete_offer' => esc_html__('Failed to delete offer', 'domain-for-sale'),
            'export' => esc_html__('Export', 'domain-for-sale'),
            'action' => esc_html__('Action', 'domain-for-sale'),
            'date' => esc_html__('Date', 'domain-for-sale'),
            'showing' => esc_html__('Showing', 'domain-for-sale'),
            'per_page' => esc_html__('Per page', 'domain-for-sale'),
            'page' => esc_html__('Page', 'domain-for-sale'),
            'others_information' => esc_html__('Others Information', 'domain-for-sale'),
            'form_submitted_data' => esc_html__('Form Submitted Data', 'domain-for-sale'),
            'show_more' => esc_html__('Show More', 'domain-for-sale'),
            'show_less' => esc_html__('Show Less', 'domain-for-sale'),
            'all' => esc_html__('All', 'domain-for-sale'),
            'of' => esc_html__('of', 'domain-for-sale'),
            'copied' => esc_html__('Copied!', 'domain-for-sale'),
            'no_offers_to_export' => esc_html__('No offers to export', 'domain-for-sale'),
            'no_offers_found' => esc_html__('No offers found.', 'domain-for-sale'),
            'send_purchase_link' => esc_html__('Invite to Buy via Escrow', 'domain-for-sale'),
        ];
    }
}
