<?php

namespace App\Http\Controllers\Backoffice;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Support\BusinessTime;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ActivityLogController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $fromInput = $request->input('date_from');
            $toInput = $request->input('date_to');
            if ($fromInput || $toInput) {
                $from = $fromInput
                    ? Carbon::parse($fromInput, BusinessTime::timezone())
                    : Carbon::parse($toInput, BusinessTime::timezone())->subHours(24);
                $to = $toInput
                    ? Carbon::parse($toInput, BusinessTime::timezone())
                    : Carbon::parse($fromInput, BusinessTime::timezone())->addHours(24);
            } else {
                $to = Carbon::now(BusinessTime::timezone());
                $from = (clone $to)->subHours(24);
            }

            $logs = ActivityLog::with(['user', 'financeUser'])
                ->whereBetween('created_at', [$from, $to])
                ->orderByDesc('created_at')
                ->get()
                ->map(function ($log) {
                    $userName = '-';
                    if ($log->user_type === 'backoffice' && $log->user) {
                        $userName = $log->user->full_name ?? $log->user->name ?? '-';
                    }
                    if ($log->user_type === 'finance' && $log->financeUser) {
                        $userName = $log->financeUser->full_name ?? $log->financeUser->name ?? '-';
                    }

                    return [
                        'id' => $log->id,
                        'user_type' => $log->user_type,
                        'user_name' => $userName,
                        'action' => $log->action,
                        'module' => $log->module,
                        'description' => $log->description,
                        'ip_address' => $log->ip_address,
                        'user_agent' => $log->user_agent,
                        'old_data' => $log->old_data,
                        'new_data' => $log->new_data,
                        'created_at' => optional($log->created_at)->toDateTimeString(),
                    ];
                });

            return response()->json(['data' => $logs]);
        }

        return view('backoffice.activity-logs.index');
    }
}
