<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class ActivityLogController extends Controller
{
    // GET /api/logs
    public function index(Request $request)
    {
        $user = Auth::user();
        if (!$user || !in_array($user->role, ['society_admin', 'secretary', 'super_admin'])) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized'], 403);
        }

        $query = DB::table('activity_logs')
            ->leftJoin('users', 'activity_logs.user_id', '=', 'users.id')
            ->select('activity_logs.*', 'users.name as user_name', 'users.role as user_role');

        if ($user->society_id) {
            $query->where(function ($q) use ($user) {
                $q->where('activity_logs.society_id', $user->society_id)
                    ->orWhereNull('activity_logs.society_id'); // Global actions?
            });
        }

        if ($request->has('user_id')) {
            $query->where('activity_logs.user_id', $request->user_id);
        }

        if ($request->has('action')) {
            $query->where('activity_logs.action', 'like', "%{$request->action}%");
        }

        $logs = $query->orderBy('activity_logs.created_at', 'desc')->paginate(20);

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

    // Helper to log actions
    public static function log($action, $description = null, $subject = null)
    {
        try {
            $user = Auth::user();
            if (!$user)
                return;

            $subjectType = null;
            $subjectId = null;

            if ($subject && is_object($subject)) {
                $subjectType = get_class($subject);
                $subjectId = $subject->id ?? null; // Assuming id exists
            }

            DB::table('activity_logs')->insert([
                'society_id' => $user->society_id,
                'user_id' => $user->id,
                'action' => $action,
                'description' => $description,
                'ip_address' => request()->ip(),
                'user_agent' => request()->userAgent(),
                'subject_type' => $subjectType,
                'subject_id' => $subjectId,
                'created_at' => now()
            ]);
        } catch (\Exception $e) {
            // Fail silently to not disrupt flow
        }
    }
}
