<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.0
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 * @author     AI Magic <info@insya.com>
 */
class Ai_Magic_Admin
{

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct($plugin_name, $version)
	{

		$this->plugin_name = $plugin_name;
		$this->version = $version;

	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Ai_Magic_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Ai_Magic_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/ai-magic-admin.css', array(), $this->version . '.1', 'all');

	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts()
	{

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Ai_Magic_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Ai_Magic_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/ai-magic-admin.js', array('jquery'), $this->version . '.1', false);

		// Localize script for AJAX
		wp_localize_script($this->plugin_name, 'ai_magic_admin', array(
			'ajax_url' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('ai_magic_admin_nonce')
		));

	}

	/**
	 * Search history via AJAX
	 * 
	 * @since 1.0.7
	 */
	public function ajax_search_history()
	{
		check_ajax_referer('ai_magic_admin_nonce', 'nonce');

		if (!current_user_can('manage_options')) {
			wp_send_json_error('Unauthorized');
		}

		$search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';

		if (empty($search)) {
			$history = Ai_Magic_History::get_history(array(
				'user_id' => get_current_user_id(),
				'limit' => 20
			));
		} else {
			$history = Ai_Magic_History::search($search);
		}

		ob_start();
		if (empty($history)) {
			?>
			<tr>
				<td colspan="6" style="text-align: center; padding: 40px; color: #666;">
					<span class="dashicons dashicons-search"
						style="font-size: 32px; width: 32px; height: 32px; margin-bottom: 10px; color: #ccc;"></span><br>
					No results found for "<?php echo esc_html($search); ?>"
				</td>
			</tr>
			<?php
		} else {
			foreach ($history as $item) {
				?>
				<tr>
					<td><strong><?php echo esc_html($item->title); ?></strong></td>
					<td><span class="ai-magic-badge"><?php echo esc_html($item->model); ?></span></td>
					<td><?php echo number_format($item->tokens_used); ?></td>
					<td>
						<?php
						echo isset($item->cost) ? '$' . number_format(floatval($item->cost), 4) : '-';
						?>
					</td>
					<td><?php echo number_format($item->generation_time, 2); ?>s</td>
					<td><?php echo date('M d, Y', strtotime($item->created_at)); ?></td>
					<td>
						<button class="button button-small ai-magic-view-btn" data-id="<?php echo $item->id; ?>">View</button>
						<button class="button button-small ai-magic-delete-btn" data-id="<?php echo $item->id; ?>"
							style="color: #b32d2e; border-color: #b32d2e;">Delete</button>
					</td>
				</tr>
				<?php
			}
		}
		$html = ob_get_clean();

		wp_send_json_success(array('html' => $html));
	}

	/**
	 * Delete history item via AJAX
	 * 
	 * @since 1.0.7
	 */
	public function ajax_delete_history()
	{
		check_ajax_referer('ai_magic_admin_nonce', 'nonce');

		if (!current_user_can('manage_options')) {
			wp_send_json_error('Unauthorized');
		}

		$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

		if ($id > 0) {
			$result = Ai_Magic_History::delete($id);
			if ($result) {
				wp_send_json_success();
			}
		}

		wp_send_json_error('Failed to delete');
	}

	/**
	 * Get history item details via AJAX
	 * 
	 * @since 1.0.7
	 */
	public function ajax_get_history_details()
	{
		check_ajax_referer('ai_magic_admin_nonce', 'nonce');

		if (!current_user_can('manage_options')) {
			wp_send_json_error('Unauthorized');
		}

		$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

		if ($id > 0) {
			$item = Ai_Magic_History::get($id);
			if ($item) {
				wp_send_json_success($item);
			}
		}

		wp_send_json_error('Item not found');
	}

}
