<?php

namespace Unlockafe_Addons\Admin;

require_once __DIR__ . '/Store_Credit_List_Table.php';

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

/**
 * Class Store_Credit_Admin
 * @package Unlockafe_Addons\Admin
 */
class Store_Credit_Admin {

    private $store_credit_manager;
    private static $instance = null;

    /**
     * Store_Credit_Admin constructor.
     */
    public function __construct($store_credit_manager) {
        $this->store_credit_manager = $store_credit_manager;
        add_action('admin_init', [$this, 'process_gift_card_actions']);
        add_action('admin_notices', [$this, 'show_admin_notices']);
        add_action('admin_init', [$this, 'process_gift_card_generation']);
    }

    /**
     * Render the admin page content.
     */
    public function process_gift_card_actions() {
        if (empty($_GET['page']) || 'unlock-gift-cards' !== $_GET['page']) {
            return;
        }

        $list_table = new Store_Credit_List_Table($this->store_credit_manager);
        $action = $list_table->current_action();

        if (!$action) {
            return;
        }

        $nonce = $_REQUEST['_wpnonce'] ?? null;

        // Single delete action
        if ('delete' === $action) {
            $gift_card_id = absint($_GET['gift_card']);
            if (!wp_verify_nonce($nonce, 'unlockafe_delete_gift_card_' . $gift_card_id)) {
                wp_die(__('Security check failed', 'unlock-addons-for-elementor'));
            }

            $deleted_count = $this->store_credit_manager->delete_gift_cards([$gift_card_id]);
            wp_redirect(admin_url('admin.php?page=unlock-gift-cards&deleted=' . $deleted_count));
            exit;
        }

        // Bulk delete action
        if ('bulk-delete' === $action) {
            if (!wp_verify_nonce($nonce, 'bulk-gift-cards')) {
                wp_die(__('Security check failed', 'unlock-addons-for-elementor'));
            }

            $gift_card_ids = array_map('absint', $_REQUEST['gift_card']);
            $deleted_count = $this->store_credit_manager->delete_gift_cards($gift_card_ids);
            wp_redirect(admin_url('admin.php?page=unlock-gift-cards&deleted=' . $deleted_count));
            exit;
        }
    }

    public function show_admin_notices() {
        if (empty($_GET['page']) || 'unlock-gift-cards' !== $_GET['page']) {
            return;
        }

        if (!empty($_GET['deleted'])) {
            $count = intval($_GET['deleted']);
            if ($count > 0) {
                $message = sprintf(
                    _n(
                        '%s gift card deleted.',
                        '%s gift cards deleted.',
                        $count,
                        'unlock-addons-for-elementor'
                    ),
                    number_format_i18n($count)
                );
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($message) . '</p></div>';
            }
        }
    }

    public function render_admin_page() {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Store Credit & Gift Cards', 'unlock-addons-for-elementor'); ?></h1>
            <p><?php esc_html_e('Manage customer store credit and generate gift cards.', 'unlock-addons-for-elementor'); ?></p>

            <div id="poststuff">
                <div id="post-body" class="metabox-holder columns-2">
                    <div id="post-body-content">
                        <div class="meta-box-sortables ui-sortable">
                            <div class="postbox">
                                <h2 class="hndle"><span><?php esc_html_e('Generate New Gift Card', 'unlock-addons-for-elementor'); ?></span></h2>
                                <div class="inside">
                                    <form method="post" action="">
                                        <?php wp_nonce_field('unlockafe_create_gift_card_nonce', '_wpnonce_unlockafe_gift_card'); ?>
                                        <table class="form-table">
                                            <tbody>
                                                <tr>
                                                    <th scope="row">
                                                        <label for="unlockafe_gc_amount"><?php esc_html_e('Amount', 'unlock-addons-for-elementor'); ?></label>
                                                    </th>
                                                    <td>
                                                        <input type="number" id="unlockafe_gc_amount" name="unlockafe_gc_amount" class="regular-text" step="0.01" min="0.01" required />
                                                        <p class="description"><?php esc_html_e('The value of the gift card.', 'unlock-addons-for-elementor'); ?></p>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th scope="row">
                                                        <label for="unlockafe_gc_recipient_email"><?php esc_html_e('Recipient Email (Optional)', 'unlock-addons-for-elementor'); ?></label>
                                                    </th>
                                                    <td>
                                                        <input type="email" id="unlockafe_gc_recipient_email" name="unlockafe_gc_recipient_email" class="regular-text" />
                                                        <p class="description"><?php esc_html_e('If provided, this gift card will be restricted to this email address.', 'unlock-addons-for-elementor'); ?></p>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th scope="row">
                                                        <label for="unlockafe_gc_expires_at"><?php esc_html_e('Expiry Date (Optional)', 'unlock-addons-for-elementor'); ?></label>
                                                    </th>
                                                    <td>
                                                        <input type="date" id="unlockafe_gc_expires_at" name="unlockafe_gc_expires_at" class="regular-text" />
                                                        <p class="description"><?php esc_html_e('The date the gift card should expire. Leave blank for no expiry.', 'unlock-addons-for-elementor'); ?></p>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                        <?php submit_button(__('Generate Gift Card', 'unlock-addons-for-elementor'), 'primary', 'unlockafe_generate_gift_card'); ?>
                                    </form>
                                </div>
                            </div>

                            <div class="postbox">
                                <h2 class="hndle"><span><?php esc_html_e('Existing Gift Cards', 'unlock-addons-for-elementor'); ?></span></h2>
                                <div class="inside">
                                    <form method="post">
                                        <?php
                                        $list_table = new Store_Credit_List_Table($this->store_credit_manager);
                                        $list_table->prepare_items();
                                        $list_table->display();
                                        ?>
                                    </form>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
                <br class="clear">
            </div>
        </div>
        <?php
    }

    /**
     * Get the singleton instance.
     *
     * @return Store_Credit_Admin
     */
    /**
     * Process the gift card generation form submission.
     */
    public function process_gift_card_generation() {
        if (!isset($_POST['unlockafe_generate_gift_card']) || !isset($_POST['_wpnonce_unlockafe_gift_card'])) {
            return;
        }

        if (!wp_verify_nonce($_POST['_wpnonce_unlockafe_gift_card'], 'unlockafe_create_gift_card_nonce')) {
            wp_die(__('Security check failed.', 'unlock-addons-for-elementor'));
        }

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

        $amount = !empty($_POST['unlockafe_gc_amount']) ? floatval($_POST['unlockafe_gc_amount']) : 0;
        $recipient_email = !empty($_POST['unlockafe_gc_recipient_email']) ? sanitize_email($_POST['unlockafe_gc_recipient_email']) : '';
        $expires_at = !empty($_POST['unlockafe_gc_expires_at']) ? sanitize_text_field($_POST['unlockafe_gc_expires_at']) : '';

        if ($amount <= 0) {
            add_action('admin_notices', function() {
                echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Please enter a valid amount for the gift card.', 'unlock-addons-for-elementor') . '</p></div>';
            });
            return;
        }

        $gift_card_data = [
            'amount'          => $amount,
            'recipient_email' => $recipient_email,
            'expires_at'      => $expires_at,
        ];

        $new_code = $this->store_credit_manager->admin_create_gift_card($gift_card_data);

        if ($new_code) {
            add_action('admin_notices', function() use ($new_code, $amount) {
                $message = sprintf(
                    __('Successfully created gift card <strong>%s</strong> for %s.', 'unlock-addons-for-elementor'),
                    esc_html($new_code),
                    wc_price($amount)
                );
                echo '<div class="notice notice-success is-dismissible"><p>' . $message . '</p></div>';
            });
        } else {
            add_action('admin_notices', function() {
                echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Failed to create the gift card. Please try again.', 'unlock-addons-for-elementor') . '</p></div>';
            });
        }
    }

    /**
     * Get the singleton instance.
     *
     * @return Store_Credit_Admin
     */
    public static function instance($store_credit_manager = null) {
        if (is_null(self::$instance)) {
            if (null === $store_credit_manager) {
                $store_credit_manager = new \Unlockafe_Addons\Classes\Store_Credit_Manager();
            }
            self::$instance = new self($store_credit_manager);
        }
        return self::$instance;
    }
}

// In the main plugin file, this would be instantiated with the manager
// Store_Credit_Admin::instance(\Unlockafe_Addons\Classes\Store_Credit_Manager::instance());
