<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\Enrollment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class CheckoutController extends Controller
{
    private $apiKey;
    private $secretKey;
    private $baseUrl;

    public function __construct()
    {
        $this->apiKey = env('FLOW_API_KEY');
        $this->secretKey = env('FLOW_SECRET_KEY');
        
        $this->baseUrl = env('FLOW_SANDBOX', true) 
            ? 'https://sandbox.flow.cl/api' 
            : 'https://www.flow.cl/api';
    }

    public function initPayment(Course $course)
    {
        $user = auth()->user();

        // 1. Verificar si el usuario ya tiene una inscripción activa
        $enrollment = Enrollment::where('user_id', $user->id)
                                ->where('course_id', $course->id)
                                ->first();

        if ($enrollment && $enrollment->status === 'active') {
            return redirect('/home')->with('info', 'Ya estás inscrito en este programa educativo.');
        }

        // 2. Control de cursos gratuitos
        $price = $course->price_clp ?? $course->price ?? 0;
        
        if ($price == 0) {
            Enrollment::updateOrCreate(
                ['user_id' => $user->id, 'course_id' => $course->id],
                ['status' => 'active', 'amount' => 0]
            );

            return redirect('/home')->with('success', "¡Inscripción exitosa! Te has matriculado correctamente en: {$course->title}");
        }

        // 3. Crear o actualizar la matrícula pendiente de forma segura (Evita errores de clave Unique)
        if (!$enrollment) {
            $enrollment = Enrollment::updateOrCreate(
                ['user_id' => $user->id, 'course_id' => $course->id],
                ['amount' => round($price), 'status' => 'pending']
            );
        }

        // Detectar si estamos en entorno local para engañar a Flow con URLs ficticias válidas
        $isLocal = in_array(request()->getHost(), ['localhost', '127.0.0.1']);
        $urlReturn = $isLocal ? 'https://miplataforma.com/payment/flow/return' : route('payment.flow.return');
        $urlConfirmation = $isLocal ? 'https://miplataforma.com/payment/flow/webhook' : route('payment.flow.webhook');

        // Parámetros obligatorios para Flow
        $params = [
            'apiKey' => $this->apiKey,
            'commerceOrder' => 'EDU-' . $enrollment->id,
            'subject' => 'Inscripción: ' . $course->title,
            'amount' => round($price),
            'email' => $user->email,
            'urlReturn' => $urlReturn,
            'urlConfirmation' => $urlConfirmation,
        ];

        // Construcción de la firma digital
        ksort($params);
        $p = [];
        foreach ($params as $key => $value) {
            $p[] = $key . "=" . $value;
        }
        $stringToSign = implode("&", $p);
        $params['s'] = hash_hmac('sha256', $stringToSign, $this->secretKey);

       // Envío de la petición HTTP POST hacia Flow
        try {
            $response = Http::asForm()->post($this->baseUrl . '/payment/create', $params);

            if ($response->successful()) {
                $data = $response->json();
                
                // Guardamos el token y enviamos a la pasarela
                $enrollment->update(['flow_order_id' => $data['token']]);
                return redirect($data['url'] . '?token=' . $data['token']);
            }

            // En producción: Si Flow falla, registramos el error en el log y volvemos con aviso
            Log::error('Error en pasarela Flow: ', ['response' => $response->body()]);
            return back()->with('error', 'La pasarela de pago rechazó la transacción. Inténtalo más tarde.');

        } catch (\Exception $e) {
            Log::critical('Fallo de conexión con Flow: ' . $e->getMessage());
            return back()->with('error', 'No se pudo establecer comunicación con el centro de pagos.');
        }
    }
}