<?php

namespace App\Http\Controllers;

use App\Models\UserConsent;
use App\Services\SystemConfig\SystemConfigService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class LegalController extends Controller
{
    public function __construct(
        protected SystemConfigService $systemConfig
    ) {}

    /**
     * Display the specified legal/content page.
     */
    public function show(string $type): View
    {
        $validTypes = ['help', 'tos', 'privacy', 'about', 'security'];

        if (! in_array($type, $validTypes)) {
            abort(404);
        }

        $content = $this->systemConfig->get("page_{$type}_content", '');
        $title = $this->getPageTitle($type);

        // Map 'privacy' type to 'pdp' key for versioning and content if needed
        $configKey = ($type === 'privacy' || $type === 'pdp') ? 'pdp' : $type;
        $version = $this->systemConfig->get("{$configKey}_document_version", 1);
        $lastUpdated = $this->systemConfig->get('legal_last_updated');

        return view('pages.public.legal', [
            'type' => $type,
            'title' => $title,
            'content' => $content,
            'version' => $version,
            'lastUpdated' => $lastUpdated,
            'dpo_email' => $this->systemConfig->get('pdp_dpo_email'),
            'company_address' => $this->systemConfig->get('pdp_company_address'),
        ]);
    }

    /**
     * Display the re-agreement page.
     */
    public function reAgree(): View
    {
        $user = Auth::user();

        $missingTos = ! $user->hasAgreedToCurrentLegal('tos');
        $missingPrivacy = ! $user->hasAgreedToCurrentLegal('privacy');

        return view('pages.public.re-agree', [
            'missingTos' => $missingTos,
            'missingPrivacy' => $missingPrivacy,
            'tosContent' => $this->systemConfig->get('page_tos_content'),
            'privacyContent' => $this->systemConfig->get('page_pdp_content') ?? $this->systemConfig->get('page_privacy_content'),
            'tosVersion' => $this->systemConfig->get('tos_document_version', 1),
            'privacyVersion' => $this->systemConfig->get('pdp_document_version', 1),
        ]);
    }

    /**
     * Handle the re-agreement submission.
     */
    public function postReAgree(Request $request): RedirectResponse
    {
        $user = Auth::user();
        $ip = $request->ip();
        $ua = $request->userAgent();

        if ($request->has('agree_tos')) {
            UserConsent::create([
                'user_id' => $user->id,
                'consent_type' => 'tos',
                'version_id' => (int) $this->systemConfig->get('tos_document_version', 1),
                'ip_address' => $ip,
                'user_agent' => $ua,
            ]);
        }

        if ($request->has('agree_privacy')) {
            UserConsent::create([
                'user_id' => $user->id,
                'consent_type' => 'privacy',
                'version_id' => (int) $this->systemConfig->get('pdp_document_version', 1),
                'ip_address' => $ip,
                'user_agent' => $ua,
            ]);
        }

        return redirect()->route('dashboard')->with('success', __('Thank you for keeping your agreements up to date.'));
    }

    /**
     * Map type to human-readable title.
     */
    protected function getPageTitle(string $type): string
    {
        return match ($type) {
            'help' => __('Help Center & FAQ'),
            'tos' => __('Terms of Use'),
            'privacy' => __('Privacy Policy (UU PDP)'),
            'about' => __('About Us'),
            'security' => __('Security Policy'),
            default => __('Legal Document'),
        };
    }
}
