<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SyncLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class SyncLogsController extends Controller
{
    /** Grouped summary — one row per user. */
    public function index(Request $request): View
    {
        $grouped = SyncLog::select(
                'user_id',
                DB::raw('COUNT(*) as total_syncs'),
                DB::raw("SUM(CASE WHEN direction='upload'   THEN 1 ELSE 0 END) as uploads"),
                DB::raw("SUM(CASE WHEN direction='download' THEN 1 ELSE 0 END) as downloads"),
                DB::raw("SUM(CASE WHEN status='failed'      THEN 1 ELSE 0 END) as failed"),
                DB::raw('COALESCE(SUM(records_count), 0) as total_records'),
                DB::raw('MAX(created_at) as last_sync_at')
            )
            ->with('user:id,name,email,plan')
            ->when($request->q, fn ($q) => $q->whereHas(
                'user', fn ($u) => $u->where('email', 'like', "%{$request->q}%")
                    ->orWhere('name', 'like', "%{$request->q}%")
            ))
            ->groupBy('user_id')
            ->orderByDesc('last_sync_at')
            ->paginate(25)
            ->withQueryString();

        $stats = [
            'total_today'  => SyncLog::whereDate('created_at', today())->count(),
            'failed_today' => SyncLog::whereDate('created_at', today())->where('status', 'failed')->count(),
            'total_week'   => SyncLog::where('created_at', '>=', now()->subWeek())->count(),
        ];

        return view('admin.sync-logs.index', compact('grouped', 'stats'));
    }

    /** Per-user detail — all individual log rows for one user. */
    public function show(string $userId, Request $request): View
    {
        $user = User::findOrFail($userId);

        $logs = SyncLog::where('user_id', $userId)
            ->when($request->status,    fn ($q) => $q->where('status',     $request->status))
            ->when($request->direction, fn ($q) => $q->where('direction',  $request->direction))
            ->when($request->table,     fn ($q) => $q->where('table_name', $request->table))
            ->latest()
            ->paginate(50)
            ->withQueryString();

        return view('admin.sync-logs.show', compact('user', 'logs'));
    }
}
