<?php

declare(strict_types=1);

namespace App\Helpers;

use Core\Auth;
use Core\Database;
use Core\Request;

/**
 * ActivityLogger — records every user action to activity_logs table.
 *
 * Usage:
 *   ActivityLogger::log('created', 'category', $id, 'Burgers');
 *   ActivityLogger::log('login',   'auth');
 */
final class ActivityLogger
{
    // ── Core log method ───────────────────────────────────────────────────────

    public static function log(
        string  $action,
        string  $module,
        ?int    $targetId   = null,
        ?string $targetName = null,
        ?string $description = null
    ): void {
        try {
            $user = Auth::user();

            Database::getInstance()->insert('activity_logs', [
                'user_id'     => Auth::id(),
                'user_name'   => $user['name']      ?? 'System',
                'role'        => $user['role_name']  ?? null,
                'action'      => $action,
                'module'      => $module,
                'target_id'   => $targetId,
                'target_name' => $targetName,
                'description' => $description ?? self::buildDescription($action, $module, $targetName),
                'ip_address'  => Request::ip(),
                'user_agent'  => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255),
            ]);
        } catch (\Throwable) {
            // Never let logging break the application
        }
    }

    // ── Shortcut helpers ──────────────────────────────────────────────────────

    public static function created(string $module, int $id, string $name): void
    {
        self::log('created', $module, $id, $name);
    }

    public static function updated(string $module, int $id, string $name): void
    {
        self::log('updated', $module, $id, $name);
    }

    public static function deleted(string $module, int $id, string $name): void
    {
        self::log('deleted', $module, $id, $name);
    }

    public static function toggled(string $module, int $id, string $name, bool $newState): void
    {
        $state = $newState ? 'activated' : 'deactivated';
        self::log('toggled', $module, $id, $name, ucfirst($module) . " '{$name}' was {$state}.");
    }

    public static function login(string $email): void
    {
        self::log('login', 'auth', null, $email, "User '{$email}' logged in successfully.");
    }

    public static function logout(string $name): void
    {
        self::log('logout', 'auth', null, $name, "User '{$name}' logged out.");
    }

    public static function statusChanged(string $module, int $id, string $orderNumber, string $oldStatus, string $newStatus): void
    {
        self::log('status_changed', $module, $id, $orderNumber,
            "Order {$orderNumber} status changed from '{$oldStatus}' to '{$newStatus}'.");
    }

    // ── Fetch logs (for admin log viewer) ─────────────────────────────────────

    /**
     * @return array<int, array<string,mixed>>
     */
    public static function recent(int $limit = 50, array $filters = []): array
    {
        $where  = ['1=1'];
        $params = [];

        if (!empty($filters['module'])) {
            $where[]  = 'module = ?';
            $params[] = $filters['module'];
        }
        if (!empty($filters['action'])) {
            $where[]  = 'action = ?';
            $params[] = $filters['action'];
        }
        if (!empty($filters['user_id'])) {
            $where[]  = 'user_id = ?';
            $params[] = $filters['user_id'];
        }
        if (!empty($filters['date_from'])) {
            $where[]  = 'DATE(created_at) >= ?';
            $params[] = $filters['date_from'];
        }
        if (!empty($filters['date_to'])) {
            $where[]  = 'DATE(created_at) <= ?';
            $params[] = $filters['date_to'];
        }

        $params[] = $limit;

        return Database::getInstance()->fetchAll(
            "SELECT * FROM activity_logs WHERE " . implode(' AND ', $where) .
            " ORDER BY created_at DESC LIMIT ?",
            $params
        );
    }

    public static function countToday(): int
    {
        return (int) Database::getInstance()->fetchValue(
            "SELECT COUNT(*) FROM activity_logs WHERE DATE(created_at) = CURDATE()"
        );
    }

    // ── Internal ──────────────────────────────────────────────────────────────

    private static function buildDescription(string $action, string $module, ?string $name): string
    {
        $user   = Auth::user()['name'] ?? 'Unknown';
        $label  = $name ? "'{$name}'" : '';
        $mod    = ucfirst(str_replace('_', ' ', $module));

        return match ($action) {
            'created' => "{$user} created {$mod} {$label}.",
            'updated' => "{$user} updated {$mod} {$label}.",
            'deleted' => "{$user} deleted {$mod} {$label}.",
            'toggled' => "{$user} toggled {$mod} {$label}.",
            'login'   => "{$user} logged in.",
            'logout'  => "{$user} logged out.",
            default   => "{$user} performed '{$action}' on {$mod} {$label}.",
        };
    }
}
