<?php
namespace Unlockafe_Addons\Classes;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

/**
 * Class Bulk_Coupon_Tools_Controller
 * @package Unlockafe_Addons\Classes
 */
class Bulk_Coupon_Tools_Controller
{
    /**
     * Bulk_Coupon_Tools_Controller constructor.
     */
    public function __construct()
    {
        add_action('admin_menu', [$this, 'register_bulk_tools_page']);
        add_action('admin_init', [$this, 'process_bulk_actions']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('admin_init', [$this, 'handle_coupon_export']);
        add_action('admin_init', [$this, 'handle_coupon_import']);
    }

    /**
     * Enqueue scripts and styles for the admin page.
     */
    public function enqueue_scripts($hook)
    {
        if ($hook !== 'tools_page_unlockafe-coupon-bulk-tools') {
            return;
        }
        wp_enqueue_style('unlockafe-jquery-ui', 'https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css');
        wp_enqueue_script('jquery-ui-accordion');
        wp_enqueue_script('jquery-ui-datepicker');
        wp_add_inline_script('jquery-ui-accordion', 'jQuery(function($) { $("#unlockafe-accordion").accordion({ heightStyle: "content" }); $(".unlockafe-datepicker").datepicker({ dateFormat: "yy-mm-dd" }); });');
    }

    /**
     * Add the admin menu page for bulk tools under the main "Tools" menu.
     */
    public function register_bulk_tools_page()
    {
        add_submenu_page(
            'tools.php', // Parent slug for main Tools menu
            __('Bulk Coupon Tools', 'unlock-addons-for-elementor'),
            __('Bulk Coupon Tools', 'unlock-addons-for-elementor'),
            'manage_woocommerce',
            'unlockafe-coupon-bulk-tools',
            [$this, 'render_bulk_tools_page']
        );
    }

    /**
     * Render the HTML for the tools page by including the view file.
     */
    public function render_bulk_tools_page()
    {
        require_once UNLOCKAFE_ADDONS_PATH . 'includes/Admin/views/bulk-coupon-generator.php';
    }

    /**
     * Process form submissions from the bulk tools page.
     */
    public function process_bulk_actions()
    {
        if (!isset($_POST['unlockafe_bulk_coupon_nonce']) || !wp_verify_nonce($_POST['unlockafe_bulk_coupon_nonce'], 'unlockafe_bulk_coupon_action')) {
            return;
        }

        if (isset($_POST['unlockafe_generate_coupons'])) {
            $this->process_coupon_generation();
        } elseif (isset($_POST['unlockafe_import_coupons'])) {
            // $this->process_csv_import(); // Placeholder for future implementation
        }
    }

    /**
     * Handle the generation of bulk coupons.
     */
    private function process_coupon_generation()
    {
        $count = isset($_POST['coupon_count']) ? absint($_POST['coupon_count']) : 0;
        if ($count <= 0 || $count > 1000) {
            // Add admin notice for invalid count
            return;
        }

        $recipients = isset($_POST['recipients']) ? array_filter(array_map('trim', explode("\n", $_POST['recipients']))) : [];
        if (!empty($recipients) && count($recipients) !== $count) {
            // Add admin notice for mismatch
            return;
        }

        $generated_codes = [];
        for ($i = 0; $i < $count; $i++) {
            $coupon_code = $this->generate_unique_coupon_code();
            $coupon = new \WC_Coupon();
            $coupon->set_code($coupon_code);
            $this->set_coupon_properties($coupon, $_POST);
            if ($coupon->save()) {
                $generated_codes[] = $coupon_code;
            }
        }

        if (!empty($recipients) && !empty($generated_codes)) {
            $this->email_coupon_codes($recipients, $generated_codes, $_POST);
        }

        // Add success notice
        add_action('admin_notices', function () use ($generated_codes) {
            echo '<div class="notice notice-success is-dismissible"><p>' . sprintf(esc_html__('%d coupons generated successfully.', 'unlock-addons-for-elementor'), count($generated_codes)) . '</p></div>';
        });
    }

    /**
     * Set coupon properties from POST data.
     */
    private function set_coupon_properties(&$coupon, $data)
    {
        $coupon->set_discount_type(sanitize_text_field($data['discount_type']));
        $coupon->set_amount(wc_format_decimal($data['coupon_amount']));
        if (!empty($data['expiry_date'])) {
            $coupon->set_date_expires(sanitize_text_field($data['expiry_date']));
        }
        // Add other properties from the form as needed
    }

    /**
     * Generate a unique coupon code based on format settings.
     */
    private function generate_unique_coupon_code()
    {
        $prefix = isset($_POST['prefix']) ? sanitize_text_field($_POST['prefix']) : '';
        $suffix = isset($_POST['suffix']) ? sanitize_text_field($_POST['suffix']) : '';
        $length = isset($_POST['code_length']) ? absint($_POST['code_length']) : 8;

        do {
            // Generate a more readable random string
            $random_part = strtoupper(substr(str_shuffle('abcdefghjkmnpqrstuvwxyz23456789'), 0, $length));
            $code = $prefix . $random_part . $suffix;
            $coupon_id = wc_get_coupon_id_by_code($code);
        } while ($coupon_id);

        return $code;
    }

    /**
     * Email one unique coupon code to each recipient.
     */
    private function email_coupon_codes($recipients, $codes, $coupon_data)
    {
        $subject = sprintf(__('Your Coupon from %s', 'unlock-addons-for-elementor'), get_bloginfo('name'));
        $amount = wc_price($coupon_data['coupon_amount']);
        $discount_type = wc_get_coupon_types()[$coupon_data['discount_type']];

        foreach ($recipients as $index => $email) {
            if (!is_email($email) || !isset($codes[$index])) {
                continue;
            }

            $coupon_code = $codes[$index];
            $message = sprintf(
                __("Hello,\n\nHere is your exclusive coupon:\n\nCode: %s\nValue: %s (%s)\n\nThank you!", 'unlock-addons-for-elementor'),
                $coupon_code,
                $amount,
                $discount_type
            );

            wp_mail(sanitize_email($email), $subject, $message);
        }
    }

    /**
     * Handle coupon export to CSV.
     */
    public function handle_coupon_export()
    {
        if (isset($_GET['action'], $_GET['_wpnonce']) && $_GET['action'] === 'export_coupons' && wp_verify_nonce($_GET['_wpnonce'], 'export_coupons_nonce')) {
            if (!current_user_can('manage_woocommerce')) {
                wp_die(__('You do not have permission to export coupons.', 'unlock-addons-for-elementor'));
            }

            $this->export_coupons_to_csv();
        }
    }

    /**
     * Fetch all coupons and generate a CSV file.
     */
    public function handle_coupon_import()
    {
        if (isset($_POST['unlockafe_import_coupons'], $_POST['unlockafe_import_csv_nonce'])) {
            if (!wp_verify_nonce($_POST['unlockafe_import_csv_nonce'], 'unlockafe_import_csv_action')) {
                wp_die(__('Invalid nonce.', 'unlock-addons-for-elementor'));
            }

            if (!current_user_can('manage_woocommerce')) {
                wp_die(__('You do not have permission to import coupons.', 'unlock-addons-for-elementor'));
            }

            if (isset($_FILES['coupon_csv_file']) && $_FILES['coupon_csv_file']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['coupon_csv_file']['tmp_name'];
                $this->import_coupons_from_csv($file);
            } else {
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Failed to upload CSV file. Please try again.', 'unlock-addons-for-elementor') . '</p></div>';
                });
            }
        }
    }

    private function import_coupons_from_csv($file_path)
    {
        $handle = fopen($file_path, 'r');
        if ($handle === false) {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Could not open the uploaded CSV file.', 'unlock-addons-for-elementor') . '</p></div>';
            });
            return;
        }

        $headers = fgetcsv($handle);
        $required_headers = ['code', 'discount_type', 'amount'];

        if (!$headers || count(array_intersect($required_headers, $headers)) !== count($required_headers)) {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Invalid CSV file. Please ensure it has at least code, discount_type, and amount columns.', 'unlock-addons-for-elementor') . '</p></div>';
            });
            fclose($handle);
            return;
        }

        $imported_count = 0;
        $failed_count = 0;

        while (($row = fgetcsv($handle)) !== false) {
            $coupon_data = array_combine($headers, $row);

            $coupon = new \WC_Coupon();
            $coupon->set_code(sanitize_text_field($coupon_data['code']));
            $coupon->set_discount_type(sanitize_text_field($coupon_data['discount_type']));
            $coupon->set_amount(wc_format_decimal($coupon_data['amount']));

            if (isset($coupon_data['description'])) {
                $coupon->set_description(sanitize_textarea_field($coupon_data['description']));
            }
            if (!empty($coupon_data['expiry_date'])) {
                $coupon->set_date_expires($coupon_data['expiry_date']);
            }
            if (isset($coupon_data['usage_limit'])) {
                $coupon->set_usage_limit((int)$coupon_data['usage_limit']);
            }

            $result = $coupon->save();

            if ($result) {
                $imported_count++;
            } else {
                $failed_count++;
            }
        }

        fclose($handle);

        add_action('admin_notices', function () use ($imported_count, $failed_count) {
            if ($imported_count > 0) {
                echo '<div class="notice notice-success is-dismissible"><p>' . sprintf(esc_html__('%d coupons imported successfully.', 'unlock-addons-for-elementor'), (int)$imported_count) . '</p></div>';
            }
            if ($failed_count > 0) {
                echo '<div class="notice notice-error is-dismissible"><p>' . sprintf(esc_html__('%d coupons failed to import.', 'unlock-addons-for-elementor'), (int)$failed_count) . '</p></div>';
            }
        });
    }

    private function export_coupons_to_csv()
    {
        $filename = 'coupons-' . date('Y-m-d') . '.csv';

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $coupon_posts = get_posts([
            'posts_per_page' => -1,
            'post_type'      => 'shop_coupon',
            'post_status'    => 'publish',
        ]);

        $headers = [
            'code',
            'description',
            'discount_type',
            'amount',
            'expiry_date',
            'usage_limit',
            'usage_count',
        ];

        $file = fopen('php://output', 'w');
        fputcsv($file, $headers);

        foreach ($coupon_posts as $post) {
            $coupon = new \WC_Coupon($post->ID);
            $row = [
                $coupon->get_code(),
                $coupon->get_description(),
                $coupon->get_discount_type(),
                $coupon->get_amount(),
                $coupon->get_date_expires() ? $coupon->get_date_expires()->format('Y-m-d') : '',
                $coupon->get_usage_limit(),
                $coupon->get_usage_count(),
            ];
            fputcsv($file, $row);
        }

        fclose($file);
        exit;
    }
}
