<?php

namespace App\Http\Controllers;

use App\Models\ActivityLog;
use App\Models\DnsRecordChange;
use App\Models\DnsZone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ActivityController extends Controller
{
    /**
     * Afișează pagina cu activitatea utilizatorului
     * Combină activity_logs și dns_record_changes
     */
    public function index(Request $request)
    {
        $user = Auth::user();

        // Query pentru activity_logs
        $activityLogsQuery = ActivityLog::where('user_id', $user->id);

        // Query pentru dns_record_changes cu relația zone
        $dnsChangesQuery = DnsRecordChange::where('user_id', $user->id)
            ->with('dnsZone:id,domain');

        // Filtrare după tip acțiune
        if ($request->filled('action')) {
            $activityLogsQuery->where('action', $request->action);
            $dnsChangesQuery->where('action', $request->action);
        }

        // Filtrare după dată
        if ($request->filled('date_from')) {
            $activityLogsQuery->whereDate('created_at', '>=', $request->date_from);
            $dnsChangesQuery->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $activityLogsQuery->whereDate('created_at', '<=', $request->date_to);
            $dnsChangesQuery->whereDate('created_at', '<=', $request->date_to);
        }

        // Filtrare după zonă (doar pentru dns_record_changes)
        $filterByZone = $request->filled('zone_id');
        if ($filterByZone) {
            $dnsChangesQuery->where('dns_zone_id', $request->zone_id);
        }

        // Obținem rezultatele
        $activityLogs = $filterByZone ? collect() : $activityLogsQuery->get()->map(function($item) {
            $item->source = 'activity';
            $item->domain = null;
            $item->record_name = null;
            $item->record_type = null;
            $item->old_values = null;
            $item->new_values = null;
            return $item;
        });

        $dnsChanges = $dnsChangesQuery->get()->map(function($item) {
            $item->source = 'dns';
            $item->domain = $item->dnsZone?->domain;
            $item->user_agent = null;
            return $item;
        });

        // Combinăm și sortăm
        $allResults = $activityLogs->concat($dnsChanges)
            ->sortByDesc('created_at')
            ->values();

        // Paginare manuală
        $page = $request->get('page', 1);
        $perPage = 25;
        $total = $allResults->count();
        $items = $allResults->forPage($page, $perPage);

        $activities = new \Illuminate\Pagination\LengthAwarePaginator(
            $items,
            $total,
            $perPage,
            $page,
            ['path' => $request->url(), 'query' => $request->query()]
        );

        // Obține tipurile de acțiuni pentru dropdown (din ambele tabele)
        $activityTypes = ActivityLog::where('user_id', $user->id)
            ->distinct()
            ->pluck('action')
            ->filter();

        $dnsActionTypes = DnsRecordChange::where('user_id', $user->id)
            ->distinct()
            ->pluck('action')
            ->filter();

        $actionTypes = $activityTypes->merge($dnsActionTypes)->unique()->sort()->values();

        // Obține zonele pentru dropdown
        $zones = $user->dnsZones()->orderBy('domain')->get(['id', 'domain']);

        // Statistici combinate
        $activityTotal = ActivityLog::where('user_id', $user->id)->count();
        $dnsTotal = DnsRecordChange::where('user_id', $user->id)->count();

        $activityToday = ActivityLog::where('user_id', $user->id)->whereDate('created_at', today())->count();
        $dnsToday = DnsRecordChange::where('user_id', $user->id)->whereDate('created_at', today())->count();

        $activityWeek = ActivityLog::where('user_id', $user->id)->whereBetween('created_at', [now()->startOfWeek(), now()])->count();
        $dnsWeek = DnsRecordChange::where('user_id', $user->id)->whereBetween('created_at', [now()->startOfWeek(), now()])->count();

        $activityMonth = ActivityLog::where('user_id', $user->id)->whereMonth('created_at', now()->month)->count();
        $dnsMonth = DnsRecordChange::where('user_id', $user->id)->whereMonth('created_at', now()->month)->count();

        $stats = [
            'total' => $activityTotal + $dnsTotal,
            'today' => $activityToday + $dnsToday,
            'this_week' => $activityWeek + $dnsWeek,
            'this_month' => $activityMonth + $dnsMonth,
        ];

        return view('activity.index', compact('activities', 'actionTypes', 'zones', 'stats'));
    }

    /**
     * Exportă activitatea în CSV
     * Combină activity_logs și dns_record_changes
     */
    public function export(Request $request)
    {
        $user = Auth::user();

        // Query pentru activity_logs
        $activityLogsQuery = ActivityLog::where('user_id', $user->id)
            ->select([
                'action',
                'description',
                'ip_address',
                'user_agent',
                'created_at',
                DB::raw('NULL as record_name'),
                DB::raw('NULL as record_type'),
            ]);

        // Query pentru dns_record_changes
        $dnsChangesQuery = DnsRecordChange::where('user_id', $user->id)
            ->select([
                'action',
                'description',
                'ip_address',
                DB::raw('NULL as user_agent'),
                'created_at',
                'record_name',
                'record_type',
            ]);

        // Aplică filtrele
        if ($request->filled('action')) {
            $activityLogsQuery->where('action', $request->action);
            $dnsChangesQuery->where('action', $request->action);
        }
        if ($request->filled('date_from')) {
            $activityLogsQuery->whereDate('created_at', '>=', $request->date_from);
            $dnsChangesQuery->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $activityLogsQuery->whereDate('created_at', '<=', $request->date_to);
            $dnsChangesQuery->whereDate('created_at', '<=', $request->date_to);
        }
        if ($request->filled('zone_id')) {
            $activityLogsQuery->whereRaw('1 = 0');
            $dnsChangesQuery->where('dns_zone_id', $request->zone_id);
        }

        // Combinăm și sortăm
        $combinedQuery = $activityLogsQuery->unionAll($dnsChangesQuery);
        $activities = DB::table(DB::raw("({$combinedQuery->toSql()}) as combined"))
            ->mergeBindings($combinedQuery->getQuery())
            ->orderBy('created_at', 'desc')
            ->get();

        $csvContent = "Data,Acțiune,Descriere,Record,Tip,IP,User Agent\n";

        foreach ($activities as $activity) {
            $csvContent .= sprintf(
                '"%s","%s","%s","%s","%s","%s","%s"' . "\n",
                $activity->created_at,
                $activity->action ?? '',
                str_replace('"', '""', $activity->description ?? ''),
                $activity->record_name ?? '',
                $activity->record_type ?? '',
                $activity->ip_address ?? '',
                str_replace('"', '""', $activity->user_agent ?? '')
            );
        }

        $filename = 'activitate_' . now()->format('Y-m-d_H-i-s') . '.csv';

        return response($csvContent)
            ->header('Content-Type', 'text/csv; charset=UTF-8')
            ->header('Content-Disposition', "attachment; filename=\"{$filename}\"");
    }

    /**
     * Șterge activitatea mai veche de X zile
     * Curăță atât activity_logs cât și dns_record_changes
     */
    public function cleanup(Request $request)
    {
        $request->validate([
            'days' => 'required|integer|min:7|max:365',
        ]);

        $user = Auth::user();
        $days = $request->days;
        $cutoffDate = now()->subDays($days);

        // Șterge din activity_logs
        $deletedActivity = ActivityLog::where('user_id', $user->id)
            ->where('created_at', '<', $cutoffDate)
            ->delete();

        // Șterge din dns_record_changes
        $deletedDns = DnsRecordChange::where('user_id', $user->id)
            ->where('created_at', '<', $cutoffDate)
            ->delete();

        $totalDeleted = $deletedActivity + $deletedDns;

        return back()->with('success', "Au fost șterse {$totalDeleted} înregistrări mai vechi de {$days} zile ({$deletedActivity} activități generale + {$deletedDns} modificări DNS).");
    }
}
