<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Activitylog\Models\Activity;

class AuditLogController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $isSuperAdmin = $user->isSuperAdmin();

        $query = Activity::with(['causer', 'subject'])
            ->orderBy('created_at', 'desc');

        // Non-super-admin users only see activity for their company
        if (!$isSuperAdmin) {
            $query->whereHas('causer', function ($q) use ($user) {
                $q->where('company_id', $user->company_id);
            });
        }

        // Filter by entity type
        if ($request->has('entity_type')) {
            $query->where('subject_type', $request->entity_type);
        }

        // Filter by action
        if ($request->has('action')) {
            $query->where('description', 'like', "%{$request->action}%");
        }

        // Filter by date range
        if ($request->has('from_date')) {
            $query->whereDate('created_at', '>=', $request->from_date);
        }
        if ($request->has('to_date')) {
            $query->whereDate('created_at', '<=', $request->to_date);
        }

        // Filter by user
        if ($request->has('user_id')) {
            $query->where('causer_id', $request->user_id);
        }

        $perPage = $request->get('per_page', 25);
        $logs = $query->paginate($perPage);

        $items = collect($logs->items())->map(function ($log) {
            $props = is_array($log->properties) ? $log->properties : ($log->properties?->toArray() ?? []);
            return [
                'id'          => $log->id,
                'description' => $log->description,
                'event'       => $log->event,
                'causer'      => $log->causer ? ['id' => $log->causer->id, 'name' => $log->causer->name, 'email' => $log->causer->email] : null,
                'subject_type'=> $log->subject_type,
                'subject_id'  => $log->subject_id,
                'ip_address'  => $props['ip_address'] ?? null,
                'user_agent'  => $props['user_agent'] ?? null,
                'properties'  => $props,
                'created_at'  => $log->created_at,
            ];
        });

        return response()->json([
            'data' => $items,
            'meta' => [
                'current_page' => $logs->currentPage(),
                'last_page'    => $logs->lastPage(),
                'per_page'     => $logs->perPage(),
                'total'        => $logs->total(),
            ]
        ]);
    }

    public function employeeAudit(Request $request, $employeeId)
    {
        $user = $request->user();
        $employee = \App\Models\Employee::findOrFail($employeeId);

        if (!$user->canAccessCompany($employee->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $logs = Activity::with(['causer'])
            ->where('subject_type', 'App\Models\Employee')
            ->where('subject_id', $employeeId)
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 25));

        return response()->json($logs);
    }

    public function companyAudit(Request $request)
    {
        $user = $request->user();
        $companyId = $request->get('company_id', $user->company_id);

        if (!$user->canAccessCompany($companyId)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $logs = Activity::with(['causer', 'subject'])
            ->whereHas('causer', function ($q) use ($companyId) {
                $q->where('company_id', $companyId);
            })
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 25));

        return response()->json($logs);
    }

    public function stats(Request $request)
    {
        $user = $request->user();
        $isSuperAdmin = $user->isSuperAdmin();
        $companyId = $request->get('company_id');

        if ($companyId && !$user->canAccessCompany($companyId)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $query = Activity::query();

        if (!$isSuperAdmin) {
            $query->whereHas('causer', function ($q) use ($user) {
                $q->where('company_id', $user->company_id);
            });
        }

        if ($companyId) {
            $query->whereHas('causer', function ($q) use ($companyId) {
                $q->where('company_id', $companyId);
            });
        }

        $today = $query->clone()->whereDate('created_at', today())->count();
        $week = $query->clone()->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count();
        $month = $query->clone()->whereMonth('created_at', now()->month)->count();

        $topUsers = $query->clone()
            ->select('causer_id', DB::raw('count(*) as total'))
            ->groupBy('causer_id')
            ->orderByDesc('total')
            ->limit(5)
            ->with('causer')
            ->get();

        $byType = $query->clone()
            ->select('subject_type', DB::raw('count(*) as total'))
            ->whereNotNull('subject_type')
            ->groupBy('subject_type')
            ->orderByDesc('total')
            ->limit(5)
            ->get();

        return response()->json([
            'today' => $today,
            'week' => $week,
            'month' => $month,
            'top_users' => $topUsers,
            'by_type' => $byType->map(function ($item) {
                $item->subject_type = class_basename($item->subject_type);
                return $item;
            }),
        ]);
    }
}
