@extends('layouts.landing')

@section('head')
    @include('layouts._partials.tablaStyle')
@endsection
@section('title',"Inicio")

@section('content')

<div class="container-fluid">
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <div class="d-sm-flex align-items-center justify-content-between">
                <h6 class="m-0 font-weight-bold text-primary">Mis pagos</h6>
            </div>
        </div>

        <div class="card-body">
            <div class="container-fluid">

                    <table id="tcont" class="table table-striped table-bordered nowrap table-hover" style="width:100%;">
                        <thead>
                            <tr>
                                <th>Fecha de pago</th>
                                <th>Concepto</th>
                                <th>Monto</th>
                                <th>Opciones</th>
                            </tr>
                        </thead>
                        <tbody>
                                @forelse ($pagos as $pago)
                                    <tr style="width:100%">
                                        <td>{{$pago->fecha_pago}}</td>
                                        <td>
                                            @foreach ($nombres as $tconcepto)
                                                @if ($pago->concepto == $tconcepto->id)
                                                    {{$tconcepto->name}}
                                                @endif
                                            @endforeach
                                        </td>
                                        <td>{{$pago->monto}}</td>
                                        <td class="row mx-auto">

                                            <select class="form-control" onchange="pagarMetodo(this.value, {{ $pago->id }})">
                                                <option value="">Selecciona método</option>
                                                <option value="card">Tarjeta</option>
                                                <option value="store">OXXO</option>
                                                <option value="spei">Transferencia</option>
                                            </select>
                                        </td>
                                    </tr>
                                @empty
                                    <p>Sin pagos.</p>
                                @endforelse

                        </tbody>
                    </table>



            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="modalPago">
    <div class="modal-dialog">
        <div class="modal-content p-3">

            <h5>Pagar con tarjeta</h5>

            <form id="payment-form">

                <input type="hidden" id="pago_id">

                <input data-openpay-card="holder_name" class="form-control mb-2" placeholder="Nombre">
                <input data-openpay-card="card_number" class="form-control mb-2" placeholder="Tarjeta">
                <input data-openpay-card="expiration_month" class="form-control mb-2" placeholder="MM">
                <input data-openpay-card="expiration_year" class="form-control mb-2" placeholder="AA">
                <input data-openpay-card="cvv2" class="form-control mb-2" placeholder="CVV">

                <button type="submit" class="btn btn-primary">Pagar</button>

            </form>

        </div>
    </div>
</div>

@endsection


@section('scripts')
    @include('layouts._partials.tablaSinOrden')

    @if (session('swal'))
        <script>
            Swal.fire({
                icon: "{{ session('swal.icon') }}",
                title: "{{ session('swal.title') }}",
                text: "{{ session('swal.text') }}",
            });
        </script>
    @endif

    <script>
    function pagarMetodo(metodo, pagoId) {

        if (!metodo) return;

        if (metodo === 'card') {
            document.getElementById('pago_id').value = pagoId;
            $('#modalPago').modal('show');
            return;
        }

        fetch('/pagar/' + pagoId, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                metodo: metodo
            })
        })
        .then(async res => {

            console.log('STATUS:', res.status);

            let text = await res.text(); // 👈 lee como texto SIEMPRE
            console.log('RAW RESPONSE:', text);

            try {
                let data = JSON.parse(text);
                console.log('JSON:', data);

                if (data.referencia) {
                    alert('Referencia OXXO: ' + data.referencia);
                } else if (data.clabe) {
                    alert('CLABE: ' + data.clabe);
                } else {
                    alert('Respuesta recibida');
                }

            } catch (e) {
                console.error('NO ES JSON:', e);
                alert('Error: respuesta no válida');
            }

        })
        .catch(err => {
            console.error('FETCH ERROR:', err);
        });
    }
    </script>

    {{-- OpenPay --}}
    <script src="https://openpay.s3.amazonaws.com/openpay.v1.min.js"></script>
    <script src="https://openpay.s3.amazonaws.com/openpay-data.v1.min.js"></script>

    <script>
        OpenPay.setId("{{ env('OPENPAY_ID') }}");
        OpenPay.setApiKey("{{ env('OPENPAY_PUBLIC_KEY') }}");
        OpenPay.setSandboxMode(true);

        document.addEventListener("DOMContentLoaded", function () {

            let form = document.getElementById('payment-form');

            if (form) {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();

                    OpenPay.token.extractFormAndCreate('payment-form', function(response){

                        let token = response.data.id;
                        let pagoId = document.getElementById('pago_id').value;

                        fetch('/pagar/' + pagoId, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                metodo: 'card',
                                token: token
                            })
                        }).then(() => {
                            alert('Pago procesado');
                            location.reload();
                        });

                    }, function(){
                        alert('Error en tarjeta');
                    });
                });
            }

        });
    </script>
@endsection
