<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\GdprConsent;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class ComplianceController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();
        $consents = GdprConsent::query()
            ->where('user_id', $user->id)
            ->orderBy('consent_type')
            ->get()
            ->keyBy('consent_type');

        return view('user.compliance', ['consents' => $consents]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'consent_type' => ['required', 'in:privacy_policy,data_processing,marketing_communication'],
            'consent_granted' => ['required', 'boolean'],
        ]);

        GdprConsent::query()->updateOrCreate(
            [
                'user_id' => $request->user()->id,
                'consent_type' => $validated['consent_type'],
            ],
            [
                'consent_granted' => (bool) $validated['consent_granted'],
                'ip_address' => $request->ip(),
                'user_agent' => (string) $request->userAgent(),
                'consented_at' => now(),
            ]
        );

        return back()->with('status', 'Compliance consent updated.');
    }
}
