<?php

namespace App\Http\Controllers;

use App\Models\Concepto;
use App\Models\Pago;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Openpay\Data\Openpay;

class PagoController extends Controller
{
//  public function __construct() {
//         $this->middleware('can:user.index')->only('index');
//     }
public function index()
{
    $user = Auth::user();

    $prospectoId = $user->alumnos()->value('alumnos.id');

    $pagos = Pago::where('user_id', $prospectoId)->get();

    $nombres = Concepto::where('tipo', '3')->get();

    return view('pago.index',compact('pagos','nombres'));
}

public function pagar(Request $request, $id)
{
    try {

        $pago = Pago::findOrFail($id);

        $openpay = Openpay::getInstance(
            env('OPENPAY_ID'),
            env('OPENPAY_PRIVATE_KEY'),
            'MX',
            false
        );

        $orderId = 'pago_'.$pago->id.'_'.time();

        if ($request->metodo === 'store') {

            $charge = $openpay->charges->create([
                'method' => 'store',
                'amount' => (float)$pago->monto,
                'description' => 'Pago '.$pago->id,
                'order_id' => $orderId,
                'customer' => [
                    'name' => Auth::user()->name,
                    'email' => Auth::user()->email,
                ]
            ]);

            $pago->update([
                'openpay_id' => $charge->id,
                'referencia' => $charge->payment_method->reference ?? null,
                'metodo_pago' => 'store',
                'status' => 'pendiente'
            ]);

            return response()->json([
                'referencia' => $charge->payment_method->reference
            ]);
        }

        if ($request->metodo === 'spei') {

            $charge = $openpay->charges->create([
                'method' => 'bank_account',
                'amount' => (float)$pago->monto,
                'description' => 'Pago '.$pago->id,
                'order_id' => $orderId,
                'customer' => [
                    'name' => Auth::user()->name,
                    'email' => Auth::user()->email,
                ]
            ]);

            $pago->update([
                'openpay_id' => $charge->id,
                'referencia' => $charge->payment_method->clabe ?? null,
                'metodo_pago' => 'spei',
                'status' => 'pendiente'
            ]);

            return response()->json([
                'clabe' => $charge->payment_method->clabe
            ]);
        }

    } catch (\Throwable  $e) {

        return response()->json([
    'error' => $e->getMessage(),
    'line' => $e->getLine(),
    'file' => $e->getFile()
], 500);
    }
}

}
