<?php

namespace App\Traits;

use App\Models\Log;
use Illuminate\Database\Eloquent\Model;

/**
 * LogsAdminActivity Trait
 *
 * Automatically logs admin actions in controllers using the logs table
 *
 * Usage:
 * - Add "use LogsAdminActivity;" to your controller
 * - Call $this->logActivity() in your methods
 */
trait LogsAdminActivity
{
    // Action constants for consistency
    const ACTION_CREATED = 'created';
    const ACTION_UPDATED = 'updated';
    const ACTION_DELETED = 'deleted';
    const ACTION_VIEWED = 'viewed';
    const ACTION_RESTORED = 'restored';
    const ACTION_FORCE_DELETED = 'force_deleted';
    const ACTION_STATUS_CHANGED = 'status_changed';
    const ACTION_EXPORTED = 'exported';
    const ACTION_IMPORTED = 'imported';

    /**
     * Log a simple admin activity
     */
    protected function logActivity(
        string $action,
        ?string $entityType = null,
        ?int $entityId = null,
        ?string $description = null,
        array $properties = [],
        ?int $clientId = null
    ): Log {
        $admin = auth('admin')->user();

        return Log::create([
            'type' => Log::TYPE_ADMIN,
            'observer' => $admin ? $admin->name : 'System',
            'module' => $entityType ?? 'general',
            'method' => $action,
            'admin_id' => $admin?->id,
            'client_id' => $clientId,
            'ip_address' => request()->ip() ?? '0.0.0.0',
            'user_agent' => request()->userAgent(),
            'session_id' => session()->getId(),
            'description' => $description,
            'request' => array_merge(
                ['entity_id' => $entityId],
                $properties
            ),
            'response' => null,
        ]);
    }

    /**
     * Log model creation
     */
    protected function logCreated(
        Model $model,
        ?string $description = null,
        ?int $clientId = null
    ): Log {
        return $this->logActivity(
            action: self::ACTION_CREATED,
            entityType: class_basename($model),
            entityId: $model->id,
            description: $description ?? class_basename($model) . " #{$model->id} created",
            properties: ['attributes' => $model->getAttributes()],
            clientId: $clientId
        );
    }

    /**
     * Log model update
     */
    protected function logUpdated(
        Model $model,
        ?string $description = null,
        ?int $clientId = null
    ): Log {
        $changes = $model->getChanges();
        $original = $model->getRawOriginal();

        return $this->logActivity(
            action: self::ACTION_UPDATED,
            entityType: class_basename($model),
            entityId: $model->id,
            description: $description ?? class_basename($model) . " #{$model->id} updated",
            properties: [
                'old' => array_intersect_key($original, $changes),
                'new' => $changes,
            ],
            clientId: $clientId
        );
    }

    /**
     * Log model deletion
     */
    protected function logDeleted(
        Model $model,
        ?string $description = null,
        ?int $clientId = null
    ): Log {
        return $this->logActivity(
            action: self::ACTION_DELETED,
            entityType: class_basename($model),
            entityId: $model->id,
            description: $description ?? class_basename($model) . " #{$model->id} deleted",
            properties: ['attributes' => $model->getAttributes()],
            clientId: $clientId
        );
    }

    /**
     * Log status change
     */
    protected function logStatusChanged(
        Model $model,
        string $oldStatus,
        string $newStatus,
        ?string $description = null,
        ?int $clientId = null
    ): Log {
        return $this->logActivity(
            action: self::ACTION_STATUS_CHANGED,
            entityType: class_basename($model),
            entityId: $model->id,
            description: $description ?? class_basename($model) . " #{$model->id} status changed from {$oldStatus} to {$newStatus}",
            properties: [
                'old_status' => $oldStatus,
                'new_status' => $newStatus,
            ],
            clientId: $clientId
        );
    }

    /**
     * Log custom action with detailed changes
     */
    protected function logCustomAction(
        string $action,
        Model $model,
        array $changes,
        ?string $description = null,
        ?int $clientId = null
    ): Log {
        return $this->logActivity(
            action: $action,
            entityType: class_basename($model),
            entityId: $model->id,
            description: $description,
            properties: $changes,
            clientId: $clientId
        );
    }

    /**
     * Log bulk operation
     */
    protected function logBulkOperation(
        string $action,
        string $entityType,
        array $entityIds,
        ?string $description = null,
        array $properties = [],
        ?int $clientId = null
    ): Log {
        return $this->logActivity(
            action: $action,
            entityType: $entityType,
            entityId: null,
            description: $description ?? "Bulk {$action} on " . count($entityIds) . " {$entityType}(s)",
            properties: array_merge(['entity_ids' => $entityIds], $properties),
            clientId: $clientId
        );
    }
}
