<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */

/**
 * Log Repository Class
 *
 * @package Wisewand
 * @subpackage Wisewand/includes/Repositories
 *
 * phpcs:disable WordPress.DB.PreparedSQL.NotPrepared -- False positive from Plugin Checker
 * All queries use $wpdb->prepare() with proper placeholders. The checker incorrectly flags
 * the prepare() method calls themselves. Known PHPCS limitation.
 *
 * phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery -- Repository pattern requirement
 * phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table, no object cache
 */

namespace Wisewand\Repositories;

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

/**
 * Class Log_Repository
 *
 * Handles database interactions for Logs.
 */
class Log_Repository extends Base_Repository {

	/**
	 * Initialize the repository.
	 */
	public function __construct() {
		parent::__construct( 'wisewand_logs' );
	}

	/**
	 * Add a log entry.
	 *
	 * @param string $level   Log level (info, error, debug).
	 * @param string $message Log message.
	 * @param array  $context Context data (optional).
	 * @return int|false Insert ID.
	 */
	public function log( $level, $message, $context = array() ) {
		$data = array(
			'level'      => $level,
			'message'    => $message,
			'context'    => ! empty( $context ) ? wp_json_encode( $context ) : null,
			'request_id' => defined( 'WISEWAND_REQUEST_ID' ) ? WISEWAND_REQUEST_ID : '',
			'timestamp'  => current_time( 'mysql' ),
		);

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query required.
		$result = $this->wpdb->insert(
			$this->table_name,
			$data
		);

		return $result ? $this->wpdb->insert_id : false;
	}

	/**
	 * Get recent logs.
	 *
	 * @param int $limit Number of logs to retrieve.
	 * @return array
	 */
	public function get_recent_logs( $limit = 100 ) {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query required.
		return $this->wpdb->get_results(
			$this->wpdb->prepare(
				'SELECT * FROM %i ORDER BY timestamp DESC LIMIT %d',
				$this->table_name,
				$limit
			),
			ARRAY_A
		);
	}
}
