<?php

namespace WPQT\Log;

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

if (!class_exists('WPQT\Log\LogRepository')) {
    class LogRepository
    {
        /**
         * Retrieves a log entry by its ID.
         *
         * This function queries the database to fetch a log entry from the wp_quick_tasks_logs table
         * based on the provided log ID.
         *
         * @param int $logId The ID of the log entry to retrieve.
         * @return object|null The log entry object if found, null otherwise.
         */
        public function getLogById($logId)
        {
            global $wpdb;

            return $wpdb->get_row(
                $wpdb->prepare(
                    'SELECT * FROM ' . TABLE_WP_QUICKTASKS_LOGS . ' WHERE id = %d',
                    $logId
                )
            );
        }

        /**
         * Retrieves logs from the database based on the provided type ID and type.
         *
         * This function queries the logs table and joins with the WordPress users table
         * and the quicktasker users table to fetch log details along with the author's name.
         *
         * @param int $typeId The ID of the log type to filter by.
         * @param string $type The type of the log to filter by.
         * @global wpdb $wpdb WordPress database abstraction object.
         * @return array An array of log objects containing log details and author names.
         */
        public function getLogs($typeId, $type)
        {
            global $wpdb;

            $table_logs = TABLE_WP_QUICKTASKS_LOGS;
            $table_users = $wpdb->users;
            $table_quicktasker_users = TABLE_WP_QUICKTASKER_USERS;

            $sql = "
                SELECT 
                    logs.id,
                    logs.text,
                    logs.type_id,
                    logs.type,
                    logs.created_by,
                    logs.created_by_id,
                    logs.user_id,
                    logs.created_at,
                    logs.log_status,
                    CASE
                        WHEN logs.created_by = 'admin' THEN wp_users.display_name
                        WHEN logs.created_by = 'wp_user' THEN wp_users.display_name
                        WHEN logs.created_by = 'quicktasker_user' THEN quicktasker_users.name
                        ELSE 'system'
                    END AS author_name
                FROM $table_logs AS logs
                LEFT JOIN $table_users AS wp_users ON logs.created_by IN ('admin', 'wp_user') AND logs.user_id = wp_users.ID
                LEFT JOIN $table_quicktasker_users AS quicktasker_users ON logs.created_by = 'quicktasker_user' AND logs.user_id = quicktasker_users.id
                WHERE logs.type_id = %d AND logs.type = %s
                ORDER BY logs.created_at DESC
            ";

            $results = $wpdb->get_results($wpdb->prepare($sql, $typeId, $type));

            return $results;
        }

        /**
         * Retrieves global logs from the database with optional filtering and ordering.
         *
         * @param string|null $logType The type of log to filter by. If null, no filtering by type is applied.
         * @param int|null $typeId The ID of the log type to filter by. If null, no filtering by type ID is applied.
         * @param string|null $logCreatedBy The creator of the log to filter by. If null, no filtering by creator is applied.
         * @param int $numberOfLogs The maximum number of logs to retrieve.
         * @param string $logOrder The order of the logs, either 'ASC' for ascending or 'DESC' for descending.
         * @param string|null $logStatus The status of the log to filter by. If null, no filtering by status is applied.
         * @param string|null $logSearch A search term to filter logs by text.
         * @param string|null $logCreatedById The ID of the creator to filter by.
         * @return array The retrieved logs from the database.
         */
        public function getGlobalLogs($logType, $typeId, $logCreatedBy, $numberOfLogs, $logOrder, $logStatus, $logSearch, $logCreatedById)
        {
            global $wpdb;

            $table_logs = TABLE_WP_QUICKTASKS_LOGS;
            $table_users = $wpdb->users;
            $table_quicktasker_users = TABLE_WP_QUICKTASKER_USERS;
            $table_pipelines = TABLE_WP_QUICKTASKER_PIPELINES;
            $order = 'ASC' === $logOrder ? 'ASC' : 'DESC';

            $sql = "
                SELECT
                    logs.id,
                    logs.text,
                    logs.type_id,
                    logs.type,
                    logs.created_by,
                    logs.created_by_id,
                    logs.user_id,
                    logs.created_at,
                    logs.log_status,
                    logs.pipeline_id,
                    pipelines.name AS pipeline_name,
                    CASE
                        WHEN logs.created_by = 'admin' THEN wp_users.display_name
                        WHEN logs.created_by = 'wp_user' THEN wp_users.display_name
                        WHEN logs.created_by = 'quicktasker_user' THEN quicktasker_users.name
                        ELSE 'system'
                    END AS author_name
                FROM $table_logs AS logs
                LEFT JOIN $table_users AS wp_users ON logs.created_by IN ('admin', 'wp_user') AND logs.user_id = wp_users.ID
                LEFT JOIN $table_quicktasker_users AS quicktasker_users ON logs.created_by = 'quicktasker_user' AND logs.user_id = quicktasker_users.id
                LEFT JOIN $table_pipelines AS pipelines ON logs.pipeline_id = pipelines.id";
            $whereClauses = [];
            $queryParams = [];

            if (null !== $logType) {
                if (WP_QT_LOG_TYPE_AUTOMATION === $logType || WP_QT_LOG_TYPE_API_TOKEN === $logType) {
                    $whereClauses[] = '(logs.type = %s OR logs.created_by = %s)';
                    $queryParams[] = $logType;
                    $queryParams[] = $logType;
                } else {
                    $whereClauses[] = 'logs.type = %s';
                    $queryParams[] = $logType;
                }
            }

            if (null !== $typeId) {
                $whereClauses[] = 'logs.type_id = %d';
                $queryParams[] = $typeId;
            }

            if (null !== $logCreatedBy) {
                $whereClauses[] = 'logs.created_by = %s';
                $queryParams[] = $logCreatedBy;
            }

            if (null !== $logCreatedById) {
                $whereClauses[] = 'logs.created_by_id = %d';
                $queryParams[] = $logCreatedById;
            }

            if (null !== $logStatus) {
                $whereClauses[] = 'logs.log_status = %s';
                $queryParams[] = $logStatus;
            }

            if (null !== $logSearch) {
                $whereClauses[] = 'logs.text LIKE %s';
                $queryParams[] = '%' . $wpdb->esc_like($logSearch) . '%';
            }

            if (!empty($whereClauses)) {
                $sql .= ' WHERE ' . implode(' AND ', $whereClauses);
            }

            $sql .= ' ORDER BY logs.created_at ' . $order;

            if (null !== $numberOfLogs) {
                $sql .= ' LIMIT %d';
                $queryParams[] = (int) $numberOfLogs;
            }

            $results = empty($queryParams)
                ? $wpdb->get_results($sql)
                : $wpdb->get_results($wpdb->prepare($sql, ...$queryParams));

            return $results;
        }
    }
}
