<?php

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

class ThiaAdmin {
    
    private static $plugin = null;
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('add_meta_boxes', array($this, 'add_meta_box_for_posts'));
        add_action('edit_form_after_title', array($this, 'add_ai_buttons_for_products'));
        add_action('admin_footer', array($this, 'add_modal_html'));
    }
    
    public function add_admin_menu() {
        $icon_url = THIAIDE_CREATOR_URL . 'img/thia_avatar.png';
        
        add_menu_page(
            'Thia Creator',
            'Thia Creator',
            'manage_options',
            'thia-ai-settings',
            array($this, 'settings_page_html'),
            $icon_url,
            65
        );

    }
    
public function register_settings() {
    register_setting(
        'thia_ai_settings',
        'thia_api_key',
        array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        )
    );
    
    register_setting(
        'thia_ai_settings',
        'thia_language',
        array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        )
    );
}
    
    public function check_for_updates() {
    return true;
}

public function get_api_stats($period) {
    global $wpdb;
    $stats_table = $wpdb->prefix . 'thiaide_content_api_stats';
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$stats_table'");
    
    if ($table_exists != $stats_table) {
        return array('calls' => 0, 'success_rate' => 0);
    }
    
    $today = current_time('Y-m-d');
    
    switch ($period) {
        case 'day':
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $stats = $wpdb->get_row($wpdb->prepare("SELECT COALESCE(api_calls, 0) as calls, COALESCE(successful_calls, 0) as successful FROM `$stats_table` WHERE date = %s", $today), ARRAY_A);
            break;
        case 'month':
            $first_day = gmdate('Y-m-01', strtotime($today));
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $stats = $wpdb->get_row($wpdb->prepare("SELECT COALESCE(SUM(api_calls), 0) as calls, COALESCE(SUM(successful_calls), 0) as successful FROM `$stats_table` WHERE date >= %s", $first_day), ARRAY_A);
            break;
        default:
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $stats = $wpdb->get_row("SELECT COALESCE(SUM(api_calls), 0) as calls, COALESCE(SUM(successful_calls), 0) as successful FROM `$stats_table`", ARRAY_A);
            break;
    }
    
    if (!$stats) {
        return array('calls' => 0, 'success_rate' => 0);
    }
    
    $success_rate = $stats['calls'] > 0 ? round(($stats['successful'] / $stats['calls']) * 100) : 0;
    
    return array(
        'calls' => (int)$stats['calls'],
        'success_rate' => $success_rate
    );
}
    
public function settings_page_html() {
    global $wpdb;
    $table_api = $wpdb->prefix . 'thiaide_content_api_keys';
    $table_settings = $wpdb->prefix . 'thiaide_content_settings';
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $saved_key = $wpdb->get_var("SELECT api_key FROM `$table_api` WHERE id = 1");
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $current_language = $wpdb->get_var("SELECT language FROM `$table_settings` WHERE id = 1");

    if (isset($_POST['save_api_key']) && check_admin_referer('thia_save_key', 'thia_nonce')) {
        // Check if array index exists, unslash, and sanitize
        $new_key = isset($_POST['thia_api_key']) ? sanitize_text_field(wp_unslash($_POST['thia_api_key'])) : '';
        
        if ($saved_key !== null) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update($table_api, array('api_key' => $new_key), array('id' => 1));
        } else {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->insert($table_api, array('api_key' => $new_key));
        }
        echo '<div class="notice notice-success is-dismissible"><p>API Key saved!</p></div>';
        $saved_key = $new_key;
    }

    if (isset($_POST['save_language']) && check_admin_referer('thia_save_language', 'thia_lang_nonce')) {
        // Check if array index exists, unslash, and sanitize
        $new_language = isset($_POST['thia_language']) ? sanitize_text_field(wp_unslash($_POST['thia_language'])) : '';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update(
            $table_settings,
            array('language' => $new_language),
            array('id' => 1)
        );
        
        echo '<div class="notice notice-success is-dismissible"><p>Language saved: ' . esc_html($new_language) . '!</p></div>';
        $current_language = $new_language;
    }

    $stats_today = $this->get_api_stats('day');
    $stats_month = $this->get_api_stats('month');
    $stats_all = $this->get_api_stats('all');
    
    $languages = array(
        'bulgarian' => 'Bulgarian',
        'english' => 'English',
        'spanish' => 'Spanish',
        'french' => 'French',
        'german' => 'German',
        'italian' => 'Italian',
        'portuguese' => 'Portuguese',
        'dutch' => 'Dutch',
        'russian' => 'Russian',
        'chinese' => 'Chinese',
        'japanese' => 'Japanese',
        'korean' => 'Korean',
        'arabic' => 'Arabic',
        'turkish' => 'Turkish',
        'greek' => 'Greek',
        'romanian' => 'Romanian',
        'polish' => 'Polish',
        'czech' => 'Czech',
        'swedish' => 'Swedish',
        'danish' => 'Danish',
        'norwegian' => 'Norwegian',
        'finnish' => 'Finnish'
    );
        
        $this->check_for_updates();
        $header_bg = plugins_url('../img/thiastat.png', __FILE__);
        $logo_url = plugins_url('../img/thaide-support.png', __FILE__);
        
        ?>
        <?php if ( wp_is_mobile() ) { ?>
        <div class="mobile-thiaide-container">
        <div class="mobile-thiaide-header-section" style="background-image: url('<?php echo esc_url($header_bg); ?>')">
        <div class="mobile-thiaide-header-content">
        <?php } else { ?>
        <div class="thiaide-container">
        <div class="thiaide-header-section" style="background-image: url('<?php echo esc_url($header_bg); ?>')">
        <div class="thiaide-header-content">
        <?php } ?>
            <div style="display: flex; align-items: center;">
                <img src="<?php echo esc_url($logo_url); ?>" 
                     alt="Thia Aide AI Content Creator" 
                     border="0" 
                     width="300" 
                     style="margin-right: 15px;">
            </div>
            <?php if ( wp_is_mobile() ) { ?>
            <div class="mobile-thiaide-stats-container">
            <?php } else { ?>
            <div class="thiaide-stats-container">
            <?php } ?>
                <div class="thiaide-stat-item">
                    <div class="thiaide-stat-value" style="color: #007cba;"><?php echo esc_html($stats_today['calls']); ?></div>
                    <div class="thiaide-stat-label">Today</div>
                    <?php if ($stats_today['calls'] == 0): ?>
                    <div class="thiaide-stat-ready">Ready</div>
                    <?php endif; ?>
                </div>
                
                <div class="thiaide-divider"></div>
                
                <div class="thiaide-stat-item">
                    <div class="thiaide-stat-value" style="color: #6f42c1;"><?php echo esc_html($stats_month['calls']); ?></div>
                    <div class="thiaide-stat-label">Month</div>
                    <?php 
                    $today = current_time('Y-m-d');
                    $first_day_of_month = gmdate('Y-m-01', strtotime($today));
                    if ($first_day_of_month == $today && $stats_month['calls'] == 0):
                    ?>
                    <div class="thiaide-stat-ready">New month</div>
                    <?php endif; ?>
                </div>
                
                <div class="thiaide-divider"></div>
                
                <div class="thiaide-stat-item">
                    <div class="thiaide-stat-value" style="color: <?php echo $stats_today['success_rate'] >= 90 ? '#28a745' : ($stats_today['success_rate'] >= 70 ? '#ffc107' : '#dc3545'); ?>;">
                        <?php echo esc_html($stats_today['success_rate']); ?>%
                    </div>
                    <div class="thiaide-stat-label">Success</div>
                </div>
            </div>
        </div>
        </div>
        
        <div class="wrap">
            <div class="thia-api-form">
                <h2>API Configuration</h2>
                <form method="post">
                    <?php wp_nonce_field('thia_save_key', 'thia_nonce'); ?>
                    <table class="form-table">
                        <tr>
                            <th><label>API Key</label></th>
                            <td>
                                <input type="password" name="thia_api_key" value="<?php echo esc_attr($saved_key); ?>" class="regular-text" style="width:100%">
                                <p>Get your key from <a href="https://www.thiaide.com/product/thia-aide-ai-content-creator-wordpress-plugin/" target="_blank">Thiaide</a></p>
                                <?php if ($saved_key): ?>
                                    <p style="color:green">✓ API key configured</p>
                                <?php else: ?>
                                    <p style="color:red">✗ No API key</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                    <?php submit_button('Save API Key', 'primary', 'save_api_key'); ?>
                </form>
            </div>
            
            <div class="thia-api-form">
                <h2>Content Language</h2>
                <form method="post">
                    <?php wp_nonce_field('thia_save_language', 'thia_lang_nonce'); ?>
                    <table class="form-table">
                        <tr>
                            <th><label>Select Language</label></th>
                            <td>
                                <select name="thia_language" style="width: 100%; max-width: 400px;" class="regular-text">
                                    <option value="">-- Select Language --</option>
                                    <?php foreach ($languages as $value => $label): ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($current_language, $value); ?>>
                                            <?php echo esc_html($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p>Choose the language for Thia content generation</p>
                                <?php if (empty($current_language)): ?>
                                    <p style="color:red">No language selected. Please select a language.</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                    <?php submit_button('Save Language', 'primary', 'save_language'); ?>
                </form>
            </div>
        </div>
        <div class="thiaide-footer">
            &copy; <?php echo esc_html(gmdate('Y')); ?> Thia Aide All rights reserved.
        </div>
        </div>
        <?php
    }

    public function enqueue_scripts($hook) {
        wp_enqueue_style('thia-creator-admin-style', THIAIDE_CREATOR_URL . 'assets/css/thia-creator-admin-style.css', array(), THIAIDE_CREATOR_VERSION);
        if ($hook == 'toplevel_page_thia-ai-settings') return;
        if (!in_array($hook, array('post.php', 'post-new.php'))) return;
        
        $screen = get_current_screen();
        if (!$screen || !in_array($screen->post_type, array('product', 'post'))) return;
        
        wp_enqueue_style('thia-creator-styles', THIAIDE_CREATOR_URL . 'assets/css/thia-creator-style.css', array(), THIAIDE_CREATOR_VERSION);
        wp_enqueue_script('thia-creator-scripts', THIAIDE_CREATOR_URL . 'assets/js/thia-creator-script.js', array('jquery'), THIAIDE_CREATOR_VERSION, true);
        wp_localize_script('thia-creator-scripts', 'thia_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('thia_nonce')
        ));
    }
    
    public function add_ai_buttons_for_products($post) {
        $logo_avatar_url = plugins_url('../img/thia_logo.png', __FILE__);
        if ($post->post_type !== 'product') return;
        ?>
        <div class="thia-ai-buttons-wrapper" style="margin: 15px 0 0 0; padding: 12px; background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border: 1px solid #ddd; border-radius: 8px;">
            <span style="font-weight: bold; margin-right: 15px;"><img src="<?php echo esc_url($logo_avatar_url); ?>" 
                     alt="Thia Aide AI Content Creator" 
                     border="0" 
                     width="30"></span>
            <button type="button" class="button button-primary" id="thia-generate-desc">Generate Description</button>
            <button type="button" class="button" id="thia-fix-grammar">Fix Grammar</button>
            <button type="button" class="button" id="thia-format-text">Format</button>
            <button type="button" class="button" id="thia-improve-readability">Improve Readability</button>
            <button type="button" class="button" id="thia-translate">Translate</button>
            <span id="thia-ai-status" style="margin-left: 10px; color: #666;"></span>
        </div>
        <?php
    }
    
    public function add_meta_box_for_posts() {
        $screen = get_current_screen();
        if (!$screen) return;
        
        if ($screen->post_type === 'post') {
            add_meta_box(
                'thia_ai_meta_box',
                'Thia Creator',
                array($this, 'render_ai_buttons_meta_box'),
                'post',
                'normal',
                'high'
            );
        }
    }
    
    public function render_ai_buttons_meta_box($post) {
        $logo_avatar_url = plugins_url('../img/thia_logo.png', __FILE__);
        ?>
        <div class="thia-ai-buttons-wrapper" style="padding: 12px; background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border: 1px solid #ddd; border-radius: 8px;">
            <span style="font-weight: bold; margin-right: 15px;"><img src="<?php echo esc_url($logo_avatar_url); ?>" 
                     alt="Thia Aide AI Content Creator" 
                     border="0" 
                     width="30"></span>
            <button type="button" class="button button-primary" id="thia-generate-desc">Generate Description</button>
            <button type="button" class="button" id="thia-fix-grammar">Fix Grammar</button>
            <button type="button" class="button" id="thia-format-text">Format</button>
            <button type="button" class="button" id="thia-improve-readability">Improve Readability</button>
            <button type="button" class="button" id="thia-translate">Translate</button>
            <span id="thia-ai-status" style="margin-left: 10px; color: #666;"></span>
        </div>
        <?php
    }
    
    public function add_modal_html() {
        $screen = get_current_screen();
        if (!$screen || !in_array($screen->post_type, array('product', 'post'))) return;
        ?>
        <div id="thia-creator-modal" style="display:none;">
            <div class="thia-creator-modal-overlay"></div>
            <div class="thia-creator-modal-box">
                <div class="thia-creator-modal-header">
                    <h3>Thia Creator</h3>
                    <span class="thia-close">&times;</span>
                </div>
                <div class="thia-creator-modal-body">
                    <div class="thia-loading">
                        <div class="thia-spinner"></div>
                        <p>Processing...</p>
                    </div>
                    <div class="thia-result" style="display:none;"></div>
                </div>
            </div>
        </div>
        <?php
    }
}