<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Setting;

/**
 * ITSWEBER CMS – Marketplace Audit-Log Viewer
 *
 * Displays the iw_marketplace_install_log table with filtering and pagination.
 * Only rendered when marketplace_audit_log_enabled = '1'.
 */
class MarketplaceAuditController extends Controller
{
    private const PER_PAGE = 30;

    public function index(Request $request, array $params = []): void
    {
        if (Setting::get('marketplace_audit_log_enabled', '1') !== '1') {
            set_flash('error', __('admin.marketplace_audit.disabled'));
            Response::redirect(admin_url('marketplace'));
            return;
        }

        $page         = max(1, (int) $request->query('page', 1));
        $filterAction = $request->query('action', '') ?: null;
        $filterResult = $request->query('result', '') ?: null;
        $filterSlug   = trim($request->query('slug', ''));

        $db     = $this->db();
        $where  = [];
        $binds  = [];

        if ($filterAction !== null) {
            $where[] = 'action = :action';
            $binds['action'] = $filterAction;
        }
        if ($filterResult !== null) {
            $where[] = 'result = :result';
            $binds['result'] = $filterResult;
        }
        if ($filterSlug !== '') {
            $where[] = 'slug LIKE :slug';
            $binds['slug'] = '%' . $filterSlug . '%';
        }

        $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        $total = (int) $db->fetchOne(
            "SELECT COUNT(*) FROM iw_marketplace_install_log $whereSql",
            $binds
        );

        $pages  = max(1, (int) ceil($total / self::PER_PAGE));
        $page   = min($page, $pages);
        $offset = ($page - 1) * self::PER_PAGE;

        $items = $db->fetchAll(
            "SELECT l.*, u.username AS user_name
               FROM iw_marketplace_install_log l
               LEFT JOIN iw_users u ON u.id = l.user_id
             $whereSql
             ORDER BY l.id DESC
             LIMIT " . self::PER_PAGE . " OFFSET " . $offset,
            $binds
        );

        $this->renderAdmin('marketplace/audit-log', [
            'pageTitle'     => __('admin.marketplace_audit.title'),
            'items'         => $items,
            'total'         => $total,
            'page'          => $page,
            'pages'         => $pages,
            'filterAction'  => $filterAction,
            'filterResult'  => $filterResult,
            'filterSlug'    => $filterSlug,
            'auth'          => $this->auth(),
            'csrf'          => $this->csrf(),
        ]);
    }
}
