<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class CAMANAGER_Admin {

    private $pro_checkout_url;

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'register_menu' ] );
        add_action( 'admin_notices', [ $this, 'show_notices' ] );
        add_action('admin_init', [$this, 'register_notices']);
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
        add_action( 'admin_menu', [ $this, 'fix_support_menu_link' ], 999 );
        add_action( 'admin_post_camanager_export_csv', [ $this, 'export_csv' ] );
        add_action( 'wp_ajax_camanager_import_csv', [ $this, 'ajax_import_csv' ] );
        add_action( 'wp_ajax_camanager_bulk_delete', [ $this, 'ajax_bulk_delete' ] );

        // AJAX
        add_action( 'wp_ajax_camanager_save_attribute', [ $this, 'ajax_save_attribute' ] );
        add_action( 'wp_ajax_camanager_remove_attribute', [ $this, 'ajax_remove_attribute' ] );
        add_action( 'wp_ajax_camanager_update_attribute', [ $this, 'ajax_update_attribute' ] );

        $this->pro_checkout_url = 'https://checkout.freemius.com/plugin/21697/plan/36190/';
    }

    

    public function register_menu() {
       add_menu_page(
            __( 'Custom Attributes', 'custom-attributes-manager' ),
            __( 'Attributes (CAM)', 'custom-attributes-manager' ),
            'manage_options',
            'camanager-attributes',
            [ $this, 'render_page' ],
            'dashicons-universal-access'
        );

        // Submenu - Manage Attributes
        add_submenu_page(
            'camanager-attributes',
            __( 'Manage Attributes', 'custom-attributes-manager' ),
            __( 'Manage Attributes', 'custom-attributes-manager' ),
            'manage_options',
            'camanager-attributes',
            [ $this, 'render_page' ]
        );

        // Submenu - Support (temporary, we’ll override link)
        add_submenu_page(
            'camanager-attributes',
            __( 'Support', 'custom-attributes-manager' ),
            __( 'Support', 'custom-attributes-manager' ),
            'manage_options',
             'camanager-support',
            [ $this, 'render_page' ]
        );
    }

    public function fix_support_menu_link() {
        global $submenu;
        // Replace URL for "Support" submenu
        if ( isset( $submenu['camanager-attributes'] ) ) {
            foreach ( $submenu['camanager-attributes'] as $index => $item ) {
                if ( $item[2] === 'camanager-support' ) {
                    $submenu['camanager-attributes'][$index][2] = 'https://customattributesmanager.com/support';
                }
            }
        }
    }

    private function get_upgrade_message() {
        return __('Free plan limit reached — you can add up to 10 attributes only. Upgrade to Pro to continue adding and managing attributes without limits.', 'custom-attributes-manager');
    }

    public function enqueue_admin_assets( $hook ) {
        if ( $hook !== 'toplevel_page_camanager-attributes' ) {
            return;
        }
        wp_enqueue_style( 'camanager-admin', CAMANAGER_URL . 'assets/css/admin.css', [], CAMANAGER_VERSION );
        wp_enqueue_script( 'camanager-admin', CAMANAGER_URL . 'assets/js/admin.js', [ 'jquery' ], CAMANAGER_VERSION, true );
        $attr_options = $this->get_attr_options();

        wp_localize_script( 'camanager-admin', 'camVars', [
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'camanager_admin_nonce' ),
            'attrOptions' => $attr_options,
        ] );
    }

    public function render_page() {
        $attributes = get_option( 'camanager_attributes', [] );
        $base_limit = 10;
        $limit = apply_filters( 'camanager_attribute_limit', $base_limit );
        $limit_reached = ( count($attributes) >= $limit );
        $attr_options = $this->get_attr_options();
        ?>
        <div class="wrap camanager-wrap">
            <h1><?php esc_html_e( 'Custom Attributes Manager', 'custom-attributes-manager' ); ?></h1>

            <!-- Add new attribute row -->
            <div id="camanager-attribute-form" class="camanager-form-group">
                <h2><?php esc_html_e( 'Add New HTML Attribute', 'custom-attributes-manager' ); ?></h2>

                <div class="camanager-form-row">
                    <div class="camanager-field">
                        <label for="camanager-selector"><?php esc_html_e('CSS Selector', 'custom-attributes-manager'); ?></label>
                        <input type="text" id="camanager-selector" placeholder="<?php esc_attr_e('e.g. .class or #id', 'custom-attributes-manager'); ?>" />
                    </div>

                    <div class="camanager-field">
                        <label for="camanager-attr"><?php esc_html_e('Attribute', 'custom-attributes-manager'); ?></label>
                        <select id="camanager-attr" class="camanager-select">
                            <option value=""><?php esc_html_e('Select attribute...', 'custom-attributes-manager'); ?></option>
                            <?php foreach ( $attr_options as $opt ) : ?>
                                <option value="<?php echo esc_attr($opt); ?>"><?php echo esc_html($opt); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="camanager-field">
                        <label for="camanager-value"><?php esc_html_e('Value', 'custom-attributes-manager'); ?></label>
                        <input type="text" id="camanager-value" placeholder="<?php esc_attr_e('Enter attribute value', 'custom-attributes-manager'); ?>" />
                    </div>

                    <div class="camanager-field camanager-btn">
                        <button id="camanager-addRow" class="button button-primary" <?php disabled( $limit_reached ); ?>>
                            <span class="dashicons dashicons-plus-alt2 v-align-middle mr-4"></span>
                            <?php esc_html_e('Add Attribute', 'custom-attributes-manager'); ?>
                        </button>
                    </div>
                </div>
                <div class="camanager-form-row">
                    <div class="camanager-field">
                        <?php if ( $limit_reached ) : ?>
                            <p class="text-danger m-0 font-weight-bold">
                                <?php echo esc_html( $this->get_upgrade_message() ); ?>
                                <a href="<?php echo esc_url( $this->pro_checkout_url ); ?>" target="_blank" class="button btn-info">
                                    <span class="dashicons dashicons-update v-align-middle mr-4"></span>Upgrade to Pro
                                </a>
                            </p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>


            <!-- Table of saved attributes -->
            <div class="camanager-header-actions">
                <h2 class="m-0">
                    <?php esc_html_e( 'Saved Attributes', 'custom-attributes-manager' ); ?>
                </h2>
                <div class="export-import-wrap">
                    <?php if ( defined( 'CAMANAGER_PRO_ACTIVE' ) && CAMANAGER_PRO_ACTIVE ) : ?>
                    <div class="camanager-bulk-actions">
                        <div class="camanager-dropdown">
                            <button class="button button-primary camanager-dropdown-toggle" type="button">
                                <span class="dashicons dashicons-admin-generic v-align-middle"></span>
                            </button>
                            <div class="camanager-dropdown-menu">
                                <a href="<?php echo esc_url( admin_url( 'admin-post.php?action=camanager_export_csv' ) ); ?>"
                                    class="button">
                                    <span class="dashicons dashicons-upload v-align-middle mr-4"></span>
                                    <?php esc_html_e( 'Export to CSV', 'custom-attributes-manager' ); ?>
                                </a>
                                <hr />
                                <button type="button"  class="button" id="camanager-import-btn">
                                    <span class="dashicons dashicons-download v-align-middle mr-4"></span>
                                    <?php esc_html_e( 'Import CSV', 'custom-attributes-manager' ); ?>
                                </button>
                                <input type="file" id="camanager-import-file" accept=".csv" class="d-none">
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    <button type="button" class="button btn-danger" id="camanager-delete-selected" disabled>
                        <span class="dashicons dashicons-trash v-align-middle"></span>
                        <?php esc_html_e( 'Delete Selected', 'custom-attributes-manager' ); ?>
                    </button>
                </div>
            </div>
            <table class="widefat striped" id="camanager-attributes-table">
                <thead>
                    <tr>
                        <th style="width:20px;">
                            <input type="checkbox" id="camanager-select-all" class="m-0">
                        </th>
                        <th><?php esc_html_e( 'Selector', 'custom-attributes-manager' ); ?></th>
                        <th><?php esc_html_e( 'Attribute', 'custom-attributes-manager' ); ?></th>
                        <th><?php esc_html_e( 'Value', 'custom-attributes-manager' ); ?></th>
                        <th><?php esc_html_e( 'Actions', 'custom-attributes-manager' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if ( ! empty( $attributes ) ) : ?>
                    <?php foreach ( $attributes as $id => $attr ) : ?>
                        <tr data-id="<?php echo esc_attr($id); ?>">
                            <td>
                                <input type="checkbox" class="camanager-row-checkbox"
                                    value="<?php echo esc_attr($id); ?>"
                                >
                            </td>
                            <td class="selector"><?php echo esc_html($attr['selector']); ?></td>
                            <td class="attr">
                                <select class="camanager-edit-attr" disabled>
                                    <option value=""><?php esc_html_e('Select attribute...', 'custom-attributes-manager'); ?></option>
                                    <?php foreach ( $attr_options as $opt ) : ?>
                                        <option value="<?php echo esc_attr($opt); ?>" <?php selected($attr['attr'], $opt); ?>>
                                            <?php echo esc_html($opt); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td class="value"><?php echo esc_html($attr['value']); ?></td>
                            <td>
                                <button class="button button-primary camanager-edit-attribute">
                                    <span class="dashicons dashicons-edit v-align-middle"></span> 
                                </button> | 
                                <button class="button camanager-remove-attribute btn-danger">
                                    <span class="dashicons dashicons-trash v-align-middle"></span>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr><td colspan="4"><?php esc_html_e( 'No attributes saved yet.', 'custom-attributes-manager' ); ?></td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }

    private function get_attr_options() {
        $options = [
            'alt','aria-busy','aria-checked','aria-controls','aria-current','aria-describedby',
            'aria-expanded','aria-hidden','aria-invalid','aria-label','aria-labelledby',
            'aria-live','aria-modal','aria-pressed','aria-required','aria-selected',
            'controls','dir','for','headers','href','id','kind','label','lang','name',
            'required','role','scope','srclang','summary','tabindex','title','type'
        ];

        sort( $options ); // ✅ always alphabetical
        return $options;
    }

    /** ========== AJAX SAVE ATTRIBUTE ========== */
    public function ajax_save_attribute() {
        check_ajax_referer( 'camanager_admin_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'custom-attributes-manager' ) );
        }

        //limit to 10 for free users
        $attributes = get_option( 'camanager_attributes', [] );
        $limit = apply_filters( 'camanager_attribute_limit', 10 );

        if ( count( $attributes ) >= $limit ) {
            wp_send_json_error([
                'message'     => $this->get_upgrade_message(),
                'upgrade_url' => $this->pro_checkout_url,
            ]);
        }

        $selector = sanitize_text_field( wp_unslash( $_POST['selector'] ?? '' ) );
        $attr     = sanitize_text_field( wp_unslash( $_POST['attr'] ?? '' ) );
        $value    = sanitize_text_field( wp_unslash( $_POST['value'] ?? '' ) );

        if ( empty( $selector ) || empty( $attr ) || empty( $value ) ) {
            wp_send_json_error( __( 'All fields are required.', 'custom-attributes-manager' ) );
        }

        $attributes = get_option( 'camanager_attributes', [] );
        $id = uniqid('attr_');

        $attributes[$id] = [
            'selector' => $selector,
            'attr'     => $attr,
            'value'    => $value,
        ];

        update_option( 'camanager_attributes', $attributes );

        wp_send_json_success( [ 'id' => $id ] );
    }

    /** ========== AJAX REMOVE ATTRIBUTE ========== */
    public function ajax_remove_attribute() {
        check_ajax_referer( 'camanager_admin_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'custom-attributes-manager' ) );
        }

        $id = sanitize_text_field( wp_unslash( $_POST['id'] ?? '' ) );
        if ( empty( $id ) ) {
            wp_send_json_error( __( 'Invalid ID.', 'custom-attributes-manager' ) );
        }

        $attributes = get_option( 'camanager_attributes', [] );
        if ( isset( $attributes[$id] ) ) {
            unset( $attributes[$id] );
            update_option( 'camanager_attributes', $attributes );
            wp_send_json_success();
        }

        wp_send_json_error( __( 'Attribute not found.', 'custom-attributes-manager' ) );
    }

    public function ajax_update_attribute() {
        check_ajax_referer( 'camanager_admin_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'custom-attributes-manager' ) );
        }

        $id       = sanitize_text_field( wp_unslash( $_POST['id'] ?? '' ) );
        $selector = sanitize_text_field( wp_unslash( $_POST['selector'] ?? '' ) );
        $attr     = sanitize_text_field( wp_unslash( $_POST['attr'] ?? '' ) );
        $value    = sanitize_text_field( wp_unslash( $_POST['value'] ?? '' ) );


        if ( empty( $id ) || empty( $selector ) || empty( $attr ) || empty( $value ) ) {
            wp_send_json_error( __( 'All fields required.', 'custom-attributes-manager' ) );
        }

        $attributes = get_option( 'camanager_attributes', [] );

        if ( isset( $attributes[ $id ] ) ) {
            $attributes[ $id ] = [
                'selector' => $selector,
                'attr'     => $attr,
                'value'    => $value,
            ];
            update_option( 'camanager_attributes', $attributes );
            wp_send_json_success();
        }

        wp_send_json_error( __( 'Attribute not found.', 'custom-attributes-manager' ) );
    }

    public function show_notices() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( ! isset($_GET['camanager_notice']) ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $notice = sanitize_text_field( wp_unslash( $_GET['camanager_notice'] ) );
         // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $imported_count = isset( $_GET['imported_count'] )
        ? absint( $_GET['imported_count'] )
        : 0;

        $success_notices = [ 'added', 'updated', 'deleted', 'imported' ];

        $notice_type = in_array( $notice, $success_notices, true )
        ? 'success'
        : 'error';

        $messages = [
            'added'   => __( 'Attribute added successfully.', 'custom-attributes-manager' ),
            'updated' => __( 'Attribute updated successfully.', 'custom-attributes-manager' ),
            'deleted' => __( 'Attribute deleted successfully.', 'custom-attributes-manager' ),

            'imported' => $imported_count
                ? sprintf(
                    __( 'Successfully imported %d attribute(s).', 'custom-attributes-manager' ),
                    $imported_count
                )
                : __( 'Attributes imported successfully.', 'custom-attributes-manager' ),

            'export_pro_only' => __( 'Export to CSV is available in the Pro version only.', 'custom-attributes-manager' ),
        ];

        $message = $messages[ $notice ] ?? __( 'Action completed.', 'custom-attributes-manager' );
        ?>
        <div class="camanager-alert-box notice notice-<?php echo esc_attr($notice_type); ?> is-dismissible">
            <p><?php echo esc_html($message); ?></p>
        </div>
        <?php
    }

    public function register_notices() {

        if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Check if user is a free user (only show notice for free tier)
        if ( defined( 'CAMANAGER_PRO_ACTIVE' ) && CAMANAGER_PRO_ACTIVE ) {
            return; // already Pro
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';

        // Add any Freemius pages you want to exclude here
        $excluded_pages = [
            'custom-attributes-manager-pricing',
            'custom-attributes-manager-account',
            'custom-attributes-manager-billing',
            'custom-attributes-manager-contact',
        ];

        if ( in_array( $page, $excluded_pages, true ) ) {
            return;
        }

        if ( $page !== 'camanager-attributes' ) {
            return;
        }
        ?>

        <div class="notice notice-info is-dismissible camanager-upgrade-notice">
            <p class="m-0">
                <strong>Unlock Pro features</strong> — Unlock unlimited attributes and our export/import feature to share attribute rules between websites!
            </p>
            <p class="m-0">
                <a class="button btn-info" href="<?php echo esc_url( $this->pro_checkout_url ); ?>" target="_blank">
                    <span class="dashicons dashicons-update v-align-middle mr-4"></span>Upgrade to Pro
                </a>
            </p>
        </div>
        <?php
    }

    public function export_csv() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( __( 'Permission denied.', 'custom-attributes-manager' ) );
        }
        
        if ( ! defined( 'CAMANAGER_PRO_ACTIVE' ) || ! CAMANAGER_PRO_ACTIVE ) {

            $redirect = wp_get_referer();

            if ( ! $redirect ) {
                $redirect = admin_url( 'admin.php?page=camanager-attributes' );
            }

            wp_safe_redirect(
                add_query_arg(
                    'camanager_notice',
                    'export_pro_only',
                    $redirect
                )
            );
            exit;
        }

        $attributes = get_option( 'camanager_attributes', [] );

        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=camanager-attributes.csv' );

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

        // CSV header
        fputcsv( $output, [ 'Selector', 'Attribute', 'Value' ] );

        foreach ( $attributes as $attr ) {
            fputcsv( $output, [
                $attr['selector'],
                $attr['attr'],
                $attr['value'],
            ] );
        }

        fclose( $output );
        exit;
    }

    public function ajax_import_csv() {
        check_ajax_referer( 'camanager_admin_nonce');

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied.' );
        }

        if ( ! defined( 'CAMANAGER_PRO_ACTIVE' ) || ! CAMANAGER_PRO_ACTIVE ) {
            wp_send_json_error([
                'message' => __( 'Import is available in Pro version only.', 'custom-attributes-manager' ),
                'upgrade_url' => $this->pro_checkout_url,
            ]);
        }

        if ( empty( $_FILES['csv']['tmp_name'] ) ) {
            wp_send_json_error( 'No file uploaded.' );
        }

        $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
        $limit  = 50;

        $handle = fopen( $_FILES['csv']['tmp_name'], 'r' );
        if ( ! $handle ) {
            wp_send_json_error( 'Unable to read CSV file.' );
        }

        // Read header
        $header = fgetcsv( $handle );

        // Validate header ONLY on first chunk
        if ( $offset === 0 ) {
            $validation = $this->validate_csv_header( $header );
            if ( is_wp_error( $validation ) ) {
                fclose( $handle );
                wp_send_json_error( $validation->get_error_message() );
            }
        }

        // Move pointer to correct offset (+1 for header)
        for ( $i = 0; $i < $offset; $i++ ) {
            if ( feof( $handle ) ) break;
            fgetcsv( $handle );
        }

        $attributes = get_option( 'camanager_attributes', [] );
        $imported   = 0;
        $processed  = 0;

        while ( $processed < $limit && ( $row = fgetcsv( $handle ) ) !== false ) {

            if ( count( $row ) < 3 ) {
                $processed++;
                continue;
            }

            $selector = sanitize_text_field( $row[0] );
            $attr     = sanitize_text_field( $row[1] );
            $value    = sanitize_text_field( $row[2] );

            if ( ! $selector || ! $attr || ! $value ) {
                $processed++;
                continue;
            }

            $id = uniqid( 'attr_' );

            $attributes[ $id ] = [
                'selector' => $selector,
                'attr'     => $attr,
                'value'    => $value,
            ];

            $imported++;
            $processed++;
        }

        $done = feof( $handle );

        fclose( $handle );
        update_option( 'camanager_attributes', $attributes );

        wp_send_json_success([
            'imported'    => $imported,
            'next_offset' => $offset + $processed,
            'done'        => $done,
        ]);
    }

    
    private function validate_csv_header( $header ) {

        if ( ! is_array( $header ) || count( $header ) < 3 ) {
            return new WP_Error(
                'invalid_header',
                __( 'CSV must contain at least 3 columns: selector, attribute, value.', 'custom-attributes-manager' )
            );
        }

        $expected = [ 'selector', 'attribute', 'value' ];
        $header   = array_map( 'strtolower', array_map( 'trim', $header ) );

        foreach ( $expected as $index => $column ) {
            if ( ! isset( $header[ $index ] ) || $header[ $index ] !== $column ) {
                return new WP_Error(
                    'invalid_header',
                    sprintf(
                        __( 'Invalid CSV header. Column %d must be "%s".', 'custom-attributes-manager' ),
                        $index + 1,
                        $column
                    )
                );
            }
        }

        return true;
    }

    public function ajax_bulk_delete() {

        check_ajax_referer( 'camanager_admin_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Permission denied.', 'custom-attributes-manager' ) );
        }

        $ids = isset( $_POST['ids'] )
            ? array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['ids'] ) )
            : [];

        if ( empty( $ids ) ) {
            wp_send_json_error( __( 'No attributes selected.', 'custom-attributes-manager' ) );
        }

        $attributes = get_option( 'camanager_attributes', [] );

        foreach ( $ids as $id ) {
            $id = sanitize_text_field( $id );
            unset( $attributes[ $id ] );
        }

        update_option( 'camanager_attributes', $attributes );
        wp_send_json_success();
    }

}
