<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\TermsAndConditions;
use App\Models\UserTerms;
use Illuminate\Support\Facades\Auth;
use Throwable;
use App\Exceptions\GlobalException;

class TermsAndConditionsController extends Controller
{
    /**
     * Mostrar los términos y condiciones específicos
     */
    public function show($id)
    {
        try {
            $terms = TermsAndConditions::findOrFail($id);
            return view('terms.show', [
                'terms' => $terms
            ]);
        } catch(Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * Procesar la aceptación o rechazo de los términos
     */
    public function process(Request $request, $id)
    {
        try {
            $terms = TermsAndConditions::findOrFail($id);
            $user = Auth::user();
            $action = $request->input('action', 'reject');
            
            // Registrar la acción del usuario
            UserTerms::updateOrCreate(
                ['user_id' => $user->id, 'term_id' => $terms->id],
                [
                    'accepted' => ($action === 'accept'),
                    'accepted_at' => ($action === 'accept') ? now() : null,
                    'ip_address' => $request->ip(),
                    'user_agent' => $request->userAgent()
                ]
            );
            
            // Si rechazó, cerrar sesión
            if ($action !== 'accept') {
                Auth::logout();
                $request->session()->invalidate();
                $request->session()->regenerateToken();
                
                return redirect()->route('authenticate')->with('message', __('terms.rejected_message'));
            }
            
            // Si aceptó, redirigir a donde iba inicialmente o al dashboard
            return redirect()->intended('/admin/dashboard');
        } catch(Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * API para verificar si se requiere aceptación de términos
     */
    public function checkRequired()
    {
        try {
            $user = Auth::user();
            $latestTerms = TermsAndConditions::getActive();
            
            if ($latestTerms && !$user->hasAcceptedLatestTerms()) {
                return response()->json([
                    'required' => true,
                    'terms' => [
                        'id' => $latestTerms->id,
                        'version' => $latestTerms->version,
                        'title' => $latestTerms->getTitle(),
                    ]
                ]);
            }
            
            return response()->json(['required' => false]);
        } catch(Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
}
