<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmployeeSnapshot;
use App\Models\SnapshotImport;
use App\Models\AuditLog;
use App\Services\SnapshotImportService;
use Illuminate\Http\Request;

class SnapshotController extends Controller
{
    public function index(Request $request)
    {
        $snapshots = EmployeeSnapshot::orderBy('nome_completo')->paginate(50);
        $imports = SnapshotImport::with('importer')->orderByDesc('created_at')->limit(10)->get();
        $totalCount = EmployeeSnapshot::count();

        return view('admin.snapshot.index', compact('snapshots', 'imports', 'totalCount'));
    }

    public function import(Request $request)
    {
        $request->validate([
            'csv_file' => 'required|file|mimes:csv,txt|max:10240',
        ], [
            'csv_file.required' => 'Selecione um ficheiro CSV.',
            'csv_file.max' => 'O ficheiro não pode exceder 10 MB.',
        ]);

        try {
            $import = SnapshotImportService::import(
                $request->file('csv_file'),
                $request->user('admin')->id
            );

            $message = "Importação concluída: {$import->success_count} registos importados.";
            if ($import->error_count > 0) {
                $message .= " {$import->error_count} erros encontrados.";
            }

            return back()->with('success', $message)->with('import_result', $import);
        } catch (\Exception $e) {
            return back()->withErrors(['csv_file' => 'Erro na importação: ' . $e->getMessage()]);
        }
    }

    public function clear(Request $request)
    {
        $count = EmployeeSnapshot::count();
        EmployeeSnapshot::truncate();

        AuditLog::log('snapshot_clear', $request->user('admin')->id, null, null, null, [
            'records_deleted' => $count,
        ]);

        return back()->with('success', "Snapshot limpo ({$count} registos removidos).");
    }
}
