<?php
// File: admin/class-admin.php

if (!defined('ABSPATH')) {
    exit;
}

class PC_HFAP_Admin {
    
    private $page_hook;
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('admin_post_pc_hfap_save_snippet', array($this, 'handle_save_snippet'));
    }
    
    public function add_admin_menu() {
        $this->page_hook = add_menu_page(
            __('Headers & Footers Code', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            __('Headers & Footers', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            'manage_options',
            'pc-hfap-snippets',
            array($this, 'render_snippets_page'),
            'dashicons-code-standards',
            30
        );
        
        add_submenu_page(
            'pc-hfap-snippets',
            __('All Snippets', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            __('All Snippets', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            'manage_options',
            'pc-hfap-snippets',
            array($this, 'render_snippets_page')
        );
        
        add_submenu_page(
            'pc-hfap-snippets',
            __('Add New Snippet', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            __('Add New', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            'manage_options',
            'pc-hfap-add-snippet',
            array($this, 'render_add_snippet_page')
        );
        
        add_submenu_page(
            'pc-hfap-snippets',
            __('Settings', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            __('Settings', 'pc-headers-and-footers-and-ad-pixels-5ake'),
            'manage_options',
            'pc-hfap-settings',
            array($this, 'render_settings_page')
        );
    }
    
    public function handle_save_snippet() {
        // Check nonce
        if (!isset($_POST['pc_hfap_nonce']) || !wp_verify_nonce($_POST['pc_hfap_nonce'], 'pc_hfap_save_snippet')) {
            wp_redirect(admin_url('admin.php?page=pc-hfap-add-snippet&error=nonce'));
            exit;
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_redirect(admin_url('admin.php?page=pc-hfap-add-snippet&error=permission'));
            exit;
        }
        
        // Validate fields
        if (empty($_POST['pc_hfap_title']) || empty($_POST['pc_hfap_location']) || empty($_POST['pc_hfap_code'])) {
            wp_redirect(admin_url('admin.php?page=pc-hfap-add-snippet&error=validation'));
            exit;
        }
        
        // Prepare data
        $data = array(
            'title' => sanitize_text_field($_POST['pc_hfap_title']),
            'location' => in_array($_POST['pc_hfap_location'], array('header', 'footer', 'body')) ? $_POST['pc_hfap_location'] : 'header',
            'code' => wp_unslash($_POST['pc_hfap_code'])
        );
        
        // Check if editing
        $is_edit = !empty($_POST['pc_hfap_id']);
        
        if ($is_edit) {
            $snippet = PC_HFAP_Snippet::get_by_id(intval($_POST['pc_hfap_id']));
            if ($snippet) {
                $snippet->set_title($data['title']);
                $snippet->set_location($data['location']);
                $snippet->set_code($data['code']);
                $result = $snippet->save();
                if ($result !== false) {
                    wp_redirect(admin_url('admin.php?page=pc-hfap-snippets&message=updated'));
                    exit;
                }
            }
            wp_redirect(admin_url('admin.php?page=pc-hfap-add-snippet&id=' . intval($_POST['pc_hfap_id']) . '&error=save'));
            exit;
        } else {
            $snippet = new PC_HFAP_Snippet($data);
            $result = $snippet->save();
            if ($result) {
                wp_redirect(admin_url('admin.php?page=pc-hfap-snippets&message=created'));
                exit;
            }
            wp_redirect(admin_url('admin.php?page=pc-hfap-add-snippet&error=save'));
            exit;
        }
    }
    
    public function enqueue_admin_assets($hook) {
        if ($hook !== $this->page_hook && strpos($hook, 'pc-hfap-') === false) {
            return;
        }
        
        wp_enqueue_style(
            'pc-hfap-admin-style',
            PC_HFAP_PLUGIN_URL . 'admin/css/admin-style.css',
            array(),
            PC_HFAP_VERSION
        );
        
        wp_enqueue_script(
            'pc-hfap-admin-script',
            PC_HFAP_PLUGIN_URL . 'admin/js/admin-script.js',
            array('jquery'),
            PC_HFAP_VERSION,
            true
        );
        
        wp_localize_script('pc-hfap-admin-script', 'pc_hfap_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('pc_hfap_admin_nonce'),
            'confirm_delete' => __('Are you sure you want to delete this snippet?', 'pc-headers-and-footers-and-ad-pixels-5ake')
        ));
    }
    
    public function render_snippets_page() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'pc-headers-and-footers-and-ad-pixels-5ake'));
        }

        // Handle delete BEFORE any HTML output
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
            check_admin_referer('delete_snippet_' . intval($_GET['id']));
            
            if (!current_user_can('manage_options')) {
                wp_die(__('You do not have permission.', 'pc-headers-and-footers-and-ad-pixels-5ake'));
            }
            
            $snippet = PC_HFAP_Snippet::get_by_id(intval($_GET['id']));
            
            if ($snippet) {
                $result = $snippet->delete();
                if ($result) {
                    wp_redirect(admin_url('admin.php?page=pc-hfap-snippets&message=deleted'));
                    exit;
                }
            }
        }

        // Show messages
        $message = isset($_GET['message']) ? $_GET['message'] : '';
        
        if ($message === 'created') {
            echo '<div class="notice notice-success is-dismissible"><p>Snippet created successfully!</p></div>';
        } elseif ($message === 'updated') {
            echo '<div class="notice notice-success is-dismissible"><p>Snippet updated successfully!</p></div>';
        } elseif ($message === 'deleted') {
            echo '<div class="notice notice-success is-dismissible"><p>Snippet deleted successfully!</p></div>';
        }
        
        $snippets = PC_HFAP_Snippet::get_all();
        
        ?>
        <div class="wrap pc-hfap-wrap">
            <h1 class="wp-heading-inline">
                <?php _e('Headers & Footers Code Snippets', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
            </h1>
            <a href="<?php echo admin_url('admin.php?page=pc-hfap-add-snippet'); ?>" class="page-title-action">
                <?php _e('Add New', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
            </a>
            
            <hr class="wp-header-end">
            
            <?php if (empty($snippets)): ?>
                <div class="notice notice-info">
                    <p><?php _e('No snippets found. Add your first header or footer code snippet!', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></p>
                </div>
            <?php else: ?>
                <div class="pc-hfap-snippets-table">
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th scope="col" class="manage-column column-title"><?php _e('Title', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></th>
                                <th scope="col" class="manage-column column-location"><?php _e('Location', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></th>
                                <th scope="col" class="manage-column column-code"><?php _e('Code Preview', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></th>
                                <th scope="col" class="manage-column column-actions"><?php _e('Actions', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($snippets as $snippet): ?>
                                <tr>
                                    <td class="column-title">
                                        <strong><?php echo esc_html($snippet->get_title()); ?></strong>
                                    </td>
                                    <td class="column-location">
                                        <?php
                                        $location = $snippet->get_location();
                                        if ($location === 'header') {
                                            $location_label = __('Header', 'pc-headers-and-footers-and-ad-pixels-5ake');
                                        } elseif ($location === 'body') {
                                            $location_label = __('Body', 'pc-headers-and-footers-and-ad-pixels-5ake');
                                        } else {
                                            $location_label = __('Footer', 'pc-headers-and-footers-and-ad-pixels-5ake');
                                        }
                                        ?>
                                        <span class="pc-hfap-location-badge pc-hfap-location-<?php echo esc_attr($location); ?>">
                                            <?php echo esc_html($location_label); ?>
                                        </span>
                                    </td>
                                    <td class="column-code">
                                        <code class="pc-hfap-code-preview">
                                            <?php 
                                            $code = esc_html($snippet->get_code());
                                            echo strlen($code) > 100 ? substr($code, 0, 100) . '...' : $code;
                                            ?>
                                        </code>
                                    </td>
                                    <td class="column-actions">
                                        <a href="<?php echo admin_url('admin.php?page=pc-hfap-add-snippet&id=' . $snippet->get_id()); ?>" class="button button-small">
                                            <?php _e('Edit', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                        </a>
                                        <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=pc-hfap-snippets&action=delete&id=' . $snippet->get_id()), 'delete_snippet_' . $snippet->get_id()); ?>" 
                                           class="button button-small button-link-delete"
                                           onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete this snippet?', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>');">
                                            <?php _e('Delete', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    public function render_add_snippet_page() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'pc-headers-and-footers-and-ad-pixels-5ake'));
        }
        
        $snippet = null;
        $is_edit = false;
        
        // Check if editing existing
        if (isset($_GET['id']) && is_numeric($_GET['id'])) {
            $snippet = PC_HFAP_Snippet::get_by_id(intval($_GET['id']));
            $is_edit = true;
        }
        
        // Show error messages
        if (isset($_GET['error'])) {
            if ($_GET['error'] === 'nonce') {
                echo '<div class="notice notice-error"><p>Security check failed. Please try again.</p></div>';
            } elseif ($_GET['error'] === 'permission') {
                echo '<div class="notice notice-error"><p>You do not have permission to perform this action.</p></div>';
            } elseif ($_GET['error'] === 'validation') {
                echo '<div class="notice notice-error"><p>Please fill in all required fields.</p></div>';
            } elseif ($_GET['error'] === 'save') {
                echo '<div class="notice notice-error"><p>Failed to save snippet. Please try again.</p></div>';
            }
        }
        
        // Get form values
        $form_title = isset($_POST['pc_hfap_title']) ? $_POST['pc_hfap_title'] : ($snippet ? $snippet->get_title() : '');
        $form_location = isset($_POST['pc_hfap_location']) ? $_POST['pc_hfap_location'] : ($snippet ? $snippet->get_location() : 'header');
        $form_code = isset($_POST['pc_hfap_code']) ? $_POST['pc_hfap_code'] : ($snippet ? $snippet->get_code() : '');
        
        ?>
        <div class="wrap pc-hfap-wrap">
            <h1>
                <?php 
                if ($is_edit && $snippet) {
                    echo esc_html__('Edit Snippet: ', 'pc-headers-and-footers-and-ad-pixels-5ake') . esc_html($snippet->get_title());
                } else {
                    _e('Add New Code Snippet', 'pc-headers-and-footers-and-ad-pixels-5ake');
                }
                ?>
            </h1>
            
            <hr class="wp-header-end">
            
            <div class="pc-hfap-form-container">
                <form method="post" action="<?php echo admin_url('admin-post.php?action=pc_hfap_save_snippet'); ?>" class="pc-hfap-snippet-form">
                    <?php wp_nonce_field('pc_hfap_save_snippet', 'pc_hfap_nonce'); ?>
                    
                    <div class="pc-hfap-form-section">
                        <h2><?php _e('Snippet Details', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></h2>
                        
                        <table class="form-table">
                            <tbody>
                                <tr>
                                    <th scope="row">
                                        <label for="pc_hfap_title">
                                            <?php _e('Snippet Title', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                            <span class="required">*</span>
                                        </label>
                                    </th>
                                    <td>
                                        <input type="text" 
                                               id="pc_hfap_title" 
                                               name="pc_hfap_title" 
                                               class="regular-text" 
                                               value="<?php echo esc_attr($form_title); ?>" 
                                               required>
                                        <p class="description">
                                            <?php _e('A descriptive name for this code snippet', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                        </p>
                                    </td>
                                </tr>
                                
                                <tr>
                                    <th scope="row">
                                        <label for="pc_hfap_location">
                                            <?php _e('Insert Location', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                            <span class="required">*</span>
                                        </label>
                                    </th>
                                    <td>
                                        <select id="pc_hfap_location" name="pc_hfap_location" class="regular-text" required>
                                            <option value="header" <?php selected($form_location, 'header'); ?>>
                                                <?php _e('Header - Insert in <head> section', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                            </option>
                                            <option value="body" <?php selected($form_location, 'body'); ?>>
                                                <?php _e('Body - Insert after <body> tag', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                            </option>
                                            <option value="footer" <?php selected($form_location, 'footer'); ?>>
                                                <?php _e('Footer - Insert before </body> tag', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                            </option>
                                        </select>
                                        <p class="description">
                                            <?php _e('Choose where this code should be inserted.', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                        </p>
                                    </td>
                                </tr>
                                
                                <tr>
                                    <th scope="row">
                                        <label for="pc_hfap_code">
                                            <?php _e('Code Snippet', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                            <span class="required">*</span>
                                        </label>
                                    </th>
                                    <td>
                                        <textarea id="pc_hfap_code" 
                                                  name="pc_hfap_code" 
                                                  rows="15" 
                                                  class="large-text code" 
                                                  placeholder="<?php esc_attr_e('Paste your HTML, JavaScript, or CSS code here...', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>"
                                                  required><?php echo esc_textarea($form_code); ?></textarea>
                                        <p class="description">
                                            <?php _e('Enter the code you want to insert.', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                                        </p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="pc-hfap-form-actions">
                        <?php if ($is_edit && $snippet): ?>
                            <input type="hidden" name="pc_hfap_id" value="<?php echo esc_attr($snippet->get_id()); ?>">
                        <?php endif; ?>
                        
                        <p class="submit">
                            <button type="submit" 
                                    name="submit_snippet" 
                                    class="button button-primary button-large">
                                <?php echo $is_edit ? __('Update Snippet', 'pc-headers-and-footers-and-ad-pixels-5ake') : __('Save Snippet', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                            </button>
                            
                            <a href="<?php echo admin_url('admin.php?page=pc-hfap-snippets'); ?>" class="button button-large">
                                <?php _e('Cancel', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?>
                            </a>
                        </p>
                    </div>
                </form>
            </div>
        </div>
        <?php
    }
    
    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions.', 'pc-headers-and-footers-and-ad-pixels-5ake'));
        }
        
        ?>
        <div class="wrap pc-hfap-wrap">
            <h1><?php _e('Headers & Footers Settings', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></h1>
            
            <hr class="wp-header-end">
            
            <div class="pc-hfap-form-container">
                <p><?php _e('Plugin settings and uninstall options coming soon.', 'pc-headers-and-footers-and-ad-pixels-5ake'); ?></p>
            </div>
        </div>
        <?php
    }
}
