@extends('layouts.app')
@section('title')Manage Subscription @endsection
@section('content')
@if (\Session::has('success'))
    <div class="alert alert-success mt-1 tac">
        <a class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <ul>
            <li>{{ \Session::get('success') }}</li>
        </ul>
    </div>
@endif
@if (session('error'))
    <div class="alert alert-danger mt-1 tac">
        <a class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <ul>
            <li>{{ session('error') }}</li>
        </ul>
    </div>
@endif
@if (isset($error))
    <div class="alert alert-danger mt-1 tac">
        <a class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <ul>
            <li>{{ $error }}</li>
        </ul>
    </div>
@endif
@if(session('updatepaymentinfo'))
    <script>
        // JavaScript to show the modal when the page loads
        $(document).ready(function() {
            $('#updatePaymentModal').modal('show');
        });
    </script>
@endif
<section class="content top-head">
    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary border-no">
                <div class="box-header with-border blue-back">
                    <h3 class="box-title">{{ __('Subscription History') }}</h3>
                </div>
                <!-- /.box-header -->
                <!-- Table -->
                <div class="box-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="subscription-table">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <!-- <th>Email</th> -->
                                    <th>Plan</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Transaction ID</th>                                    
                                    <th>Stripe ID</th>                                    
                                    <th>Billing Method</th>                                    
                                    <th>Last 4</th>                                    
                                    <th>Duration</th>                                    
                                    <th>Created On</th>                                    
                                    @if(Auth::user()->user_role == 1|| Auth::user()->id == 36)<th>Action</th>@endif                                    
                                    <!-- Add more table headers as needed -->
                                </tr>
                            </thead>
                            <tbody>
                            	@if(isset($formattedSubscription) && count($formattedSubscription) > 0)
                                @foreach($formattedSubscription as $charge)
                                <tr>
                                    <td>{{ $charge['name'] }}</td>
                                    <!-- <td>{{ $charge['email'] }}</td> -->
                                    <td>{{ $charge['plan_name'] }}</td>
                                    <td>${{ number_format(bcdiv($charge['amount'],100,2),2) }}</td>
                                    <td><strong>@if(!empty($charge['pause_date']) && $charge['pause_date'] > date('Y-m-d')) Paused till ({{$charge['pause_date']}}) @else {{ ucwords($charge['status']) }} @endif</strong></td>
                                    <td>{{ $charge['transaction_id'] }}</td>
                                    <td>{{ $charge['stripe_id'] }}</td>
                                    <td>{{ $charge['billing'] }}</td>
                                    <td><strong>@if(!empty($charge['last4']))&#183;&#183;&#183;&#183;&nbsp;@endif{{ $charge['last4'] }}</strong></td>
                                    <td>{{ date('Y-m-d', $charge['start']) }} - {{ date('Y-m-d', $charge['end']) }}</td>
                                    <td>{{ date('Y-m-d', $charge['created_at']) }}</td>
                                    @if(Auth::user()->user_role == 1 || Auth::user()->id == 36)
                                    @if($charge['status'] == 'active' || $charge['status'] == 'trialing')
                                    <td>
                                    	<form action="{{ route('transaction.cancel') }}" method="POST">
        							        @csrf
        							        <input type="hidden" name="sub_id" value="{{$charge['transaction_id']}}">
        							        <input type="hidden" name="user_id" value="{{$charge['stripe_id']}}">
        							        <button type="submit" class="btn btn-link">Cancel</button>
        							    </form>
                                        <button type="button" class="btn btn-link pause_button" data-toggle="modal" data-target="#subscription_pause_modal" data-charge="{{ json_encode($charge) }}" @if(!empty($charge['pause_date']) && $charge['pause_date'] > date('Y-m-d')) disabled @endif>Pause</button>
        							  </td>
                                    @elseif($charge['status'] == 'past_due')
                                    <td>Past Due</td>
                                    @else
                                    <td>Subscription Cancelled</td>
                                    @endif
                                    @endif
                                    <!-- Add more table cells as needed -->
                                </tr>
                                @endforeach
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<section class="content top-head">
    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary border-no">
                <div class="box-header with-border blue-back">
                    <h3 class="box-title">{{ __('Transaction History') }}</h3>
                </div>
                <!-- /.box-header -->
                <!-- Table -->
                <div class="box-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <!-- <th>Email</th> -->
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Transaction ID</th>
                                    <th>Transaction Type</th>
                                    <th>Stripe ID</th>
                                    <th>Last 4</th>
                                    <th>Created On</th>
                                    <th>Receipt</th>
                                    <!-- Add more table headers as needed -->
                                </tr>
                            </thead>
                            <tbody>
                                @if(isset($formattedCharges) && count($formattedCharges) > 0)
                                @foreach($formattedCharges as $charge)
                                <tr @if($charge['status'] !='succeeded' ) style="background-color: lightyellow;" @endif>
                                    <td>{{ $charge['name'] }}</td>
                                    <!-- <td>{{ $charge['email'] }}</td> -->
                                    <td>${{ number_format(bcdiv($charge['amount'],100,2),2) }}</td>
                                    <td><strong>{{ ucwords($charge['status']) }}</strong></td>
                                    <td>{{ $charge['transaction_id'] }}</td>
                                    <td>{{ ucwords($charge['transaction_type']) }}</td>
                                    <td>{{ $charge['stripe_id'] }}</td>
                                    <td><strong>@if(!empty($charge['last4']))&#183;&#183;&#183;&#183;&nbsp;@endif{{ $charge['last4'] }}</strong>
                                    </td>
                                    <td>{{ date('Y-m-d',strtotime($charge['created'])) }}</td>
                                    <td><a href="{{ $charge['receipt_url'] }}" target="_blank">Get Receipt</a></td>
                                    <!-- Add more table cells as needed -->
                                </tr>
                                @endforeach
                                @else
                                <tr>
                                    <td colspan="7">No Records Found.</td>
                                </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                    <!-- Pagination Links -->
                    <div class="pagination" style="display:flex;justify-content: space-between;">
                        @if(isset($firstChargeId) && $currentPage > 1)
                            <a href="{{ route('manage-subscription', ['starting_after' => null, 'ending_before' => $firstChargeId,'page' => $currentPage - 1]) }}">Previous Page</a>
                        @else
                        &nbsp;
                        @endif
                        @if(isset($lastChargeId) && count($formattedCharges) == $perPage)
                            <a href="{{ route('manage-subscription', ['starting_after' => $lastChargeId,'page' => $currentPage + 1]) }}">Next Page</a>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<section class="content top-head">
    <div class="row">
        <!-- left column -->
        <div class="col-md-12">
            <!-- general form elements -->
            <div class="box box-primary border-no">
                <div class="box-header with-border blue-back">
                    <h3 class="box-title">{{ __('Account Balance') }}</h3>
                </div>
                <div class="box-body">
                    <div class="row">
                        <div class="col-md-6 text-left">
                            <h4><strong>Account Balance: ${{ isset($totalPendingAmount) ? number_format($totalPendingAmount ,2) : '0'}}</strong></h4>
                        </div>
                        <div class="col-md-6 text-right">
                            @if(isset($totalPendingAmount) && $totalPendingAmount > 0)
                                <button class="btn btn-primary pay-invoice-button" data-user-id="{{ isset($user) ? $user->id : '' }}" data-user-email="{{ isset($user) ? $user->email : '' }}" data-total-amount-due="{{ $totalPendingAmount }}"> Pay Invoice</button>
                            @endif
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered" id="pending-payments-table">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Plan Name</th>
                                    <th>Amount Due</th>
                                    <th>Currency</th>
                                    <th>Due Date</th>
                                    <th>Status</th>
                                    <!-- Add more table headers as needed -->
                                </tr>
                            </thead>
                            <tbody>
                                @if(isset($pendingPayments) && count($pendingPayments) > 0)
                                    @foreach ($pendingPayments as $payment)
                                        <tr>
                                            <th>{{getUserDetails($payment->user_id)->name.' '.getUserDetails($payment->user_id)->last_name}}</th>
                                            <td>{{ $payment->user->subscriptionPlan->name ?? '' }}</td>
                                            <td>{{ $payment->amount_due }}</td>
                                            <td>{{ $payment->currency }}</td>
                                            <td>{{ $payment->due_date }}</td>
                                            <td>{{ ucfirst($payment->status) }}</td>
                                            <!-- <td>
                                                <button class="btn btn-primary pay-button" 
                                                        data-invoice-id="{{ $payment->invoice_id }}" 
                                                        data-amount-due="{{ $payment->amount_due }}" 
                                                        data-toggle="modal" 
                                                        data-target="#addPaymentMethodModal">
                                                    Pay
                                                </button>
                                            </td> -->
                                        </tr>
                                    @endforeach
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<section class="content top-head">
    <div class="row">
        <!-- left column -->
        <div class="col-md-12">
            <!-- general form elements -->
            <div class="box box-primary border-no">
                <div class="box-header with-border blue-back">
                    <h3 class="box-title">{{ __('Update Payment Information') }}</h3>
                </div>
                <!-- /.box-header -->
                <!-- form start -->
                <div class="box-body">
                    <label for="">Default Payment Method Detail:</label>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Payment Method</th>
                                    <th>Brand</th>
                                    <th>Last 4</th>                                  
                                    <!-- Add more table headers as needed -->
                                </tr>
                            </thead>
                            <tbody>
                                @if(isset($defaultPaymentType) && $defaultPaymentType)
                                    <td>{{ $defaultPaymentType }}</td>
                                    <td>{{ isset($defaultPaymentBrand) ? $defaultPaymentBrand : '' }}</td>
                                    <td>@if(isset($defaultPaymentLast4) && !empty($defaultPaymentLast4))&#183;&#183;&#183;&#183;&nbsp;@endif{{ isset($defaultPaymentLast4) ? $defaultPaymentLast4 : '' }}</td>
                                @else
                                <tr>
                                    <td colspan=3>No Records Found</td>
                                </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                    <div class="row m-3" style="float:right;">
                        <div class="col-md-6">
                            @if(isset($user) && $user->stripe_id)
                                <button class="btn btn-primary update-payment-method-button" data-user-id="{{ isset($user) ? $user->id : '' }}" data-user-email="{{ isset($user) ? $user->email : '' }}">Update Payment Method</button>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Payment Modal -->
<!-- <div class="modal fade" id="updatePaymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 50%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" style="color:white;">Pay Invoice</h4>
            </div>
            <div class="modal-body">
                <form id="add-payment-method-form" method="POST" action="{{ route('account.pay') }}">
                    @csrf
                    <div class="modal-body">
                        <input type="hidden" name="user_id" value="{{ isset($user) ? $user['id'] : '' }}">
                        <input type="hidden" name="user_email" value="{{ isset($user) ? $user['email'] : '' }}">
                        <input type="hidden" value="{{isset($totalPendingAmount) ? $totalPendingAmount : 0}}" id="total_amount_due" name="total_amount_due">
                        <div class="form-group">
                            <label for="payment-method-update">Select Payment Method</label>
                            <select class="form-control" id="payment-method-update" name="payment_method">
                                <option value="null">Select Payment Method</option>
                                <option value="card">Credit or Debit Card</option>
                                <option value="ach">ACH Bank Transfer</option>
                            </select>
                            <span class="information" style="color:red;font-size:14px;">**Please note a 3.5% processing fee will be added to your total for card payments.</span>
                        </div>
                        <div id="card-payment-update" class="payment-method-details" style="display: none;">
                            <div class="form-group">
                                <label for="card-holder-name-update">Card Holder Name</label>
                                <input id="card-holder-name-update" type="text" class="form-control">
                            </div>
                            <div class="form-row">
                                <label for="card-element-update">Credit or debit card</label>
                                <div id="card-element-update" class="form-control"></div>
                                <div id="card-errors-update" role="alert"></div>
                            </div>
                        </div>
                        <div id="ach-payment-update" class="payment-method-details" style="display: none;">
                            <div class="form-group">
                                <label for="account-holder-name-update">Account Holder Name</label>
                                <input id="account-holder-name-update" type="text" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="account-holder-type-update">Account Holder Type</label>
                                <select id="account-holder-type-update" class="form-control">
                                    <option value="individual">Individual</option>
                                    <option value="company">Company</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="routing-number-update">Routing Number</label>
                                <input id="routing-number-update" type="text" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="account-number-update">Account Number</label>
                                <input id="account-number-update" type="text" class="form-control">
                            </div>
                            <div id="ach-errors-update" role="alert"></div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" data-secret="{{ isset($intent->client_secret) ? $intent->client_secret : '' }}" id="submitUpdateMethod">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div> -->

<!-- <div class="modal fade" id="paymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 50%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="paymentModalTitle" style="color:white;">Pay Invoice</h4>
            </div>
            <div class="modal-body">
                <form id="paymentForm" method="POST" action="">
                    @csrf
                    <input type="hidden" name="user_id" id="modalUserId" value="">
                    <input type="hidden" name="user_email" id="modalUserEmail" value="">
                    <input type="hidden" name="total_amount_due" id="modalTotalAmountDue" value="">
                    <div class="row">
                        <div class="form-group" style="margin-left:15px;">
                            <input type="checkbox" id="authorizationCheckbox" required>
                            <label for="authorizationCheckbox" style="display:inline;">
                                I acknowledge and agree to the authorization below.
                            </label>
                        </div>
                        <p style="margin:10px 40px;">
                            I <strong>{{ isset($user) ? $user->name.' '.$user->last_name : ''}}</strong> hereby authorize Spirit Real Estate Group, LLC to charge my credit card for the agreed upon sponsorship dues of <strong>{{ isset($planPrice) ? '$'.$planPrice : '' }} {{ isset($planName) ? '('.$planName.')' : '' }}</strong> Per month for each month of active sponsorship. I understand that my information will be saved for future transactions.
                        </p>
                        <p style="margin:10px 40px;">
                            Please complete all of the fields. You may cancel this authorization at any time by contacting us. This authorization will remain in effect until cancelled.
                        </p>
                    </div>
                    <hr>
                    <div class="form-group">
                        <label for="payment-method">Select Payment Method</label>
                        <select class="form-control" id="payment-method" name="payment_method">
                            <option value="null">Select Payment Method</option>
                            <option value="card">Credit or Debit Card</option>
                            <option value="ach">ACH Bank Transfer</option>
                        </select>
                        <span class="information" style="color:red;font-size:14px;">**Please note a 3.5% processing fee will be added to your total for card payments.</span>
                    </div>
                     <div id="existing-payment-methods" style="margin-bottom:15px; display: none;">
                        <label for="existing-payment-method">Select Existing Payment Method</label>
                        <div id="existing-payment-method-list"></div>
                    </div>
                    <div id="no-existing-payment-methods" style="display: none;">
                        <p>No existing payment methods found.</p>
                    </div>
                    <div id="assign-plan-errors" class="alert alert-danger" style="display: none;"></div>
                    <div id="card-payment" class="payment-method-details" style="display: none;">
                        <div class="form-group">
                            <label for="card-holder-name">Card Holder Name</label>
                            <input id="card-holder-name" type="text" class="form-control">
                        </div>
                        <div class="form-row">
                            <label for="card-element">Credit or debit card</label>
                            <div id="card-element" class="form-control"></div>
                            <div id="card-errors" role="alert"></div>
                        </div>
                    </div>

                    <div id="ach-payment" class="payment-method-details" style="display: none;">
                        <div class="form-group">
                            <label for="account-holder-name">Account Holder Name</label>
                            <input id="account-holder-name" type="text" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="account-holder-type">Account Holder Type</label>
                            <select id="account-holder-type" class="form-control">
                                <option value="individual">Individual</option>
                                <option value="company">Company</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="routing-number">Routing Number</label>
                            <input id="routing-number" type="text" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="account-number">Account Number</label>
                            <input id="account-number" type="text" class="form-control">
                        </div>
                        <div id="ach-errors" role="alert"></div>
                    </div>

                    <div class="modal-footer-" style="display: flex;justify-content: space-between; align-items: center;margin-top: 20px;">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <div class="d-flex">
                            <button type="button" class="btn btn-primary" id="submitPayment" data-secret="{{ isset($intent->client_secret) ? $intent->client_secret : '' }}" disabled>Submit</button>
                            <span id="apLoader" style="display: none;margin-left:5px;"><i class="fa fa-spinner fa-spin" style="font-size:24px"></i></span>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div> -->

<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog" aria-labelledby="paymentModalTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 50%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="paymentModalTitle" style="color:white;">Pay Invoice</h4>
            </div>
            <div class="modal-body">
                <form id="paymentForm" method="POST" action="" autocomplete="off">
                    @csrf
                    <input type="hidden" name="user_id" id="modalUserId" value="">
                    <input type="hidden" name="user_email" id="modalUserEmail" value="">
                    <input type="hidden" name="total_amount_due" id="modalTotalAmountDue" value="">
                    <div class="row">
                        <div class="form-group" style="margin-left:15px;">
                            <input type="checkbox" id="authorizationCheckbox" required>
                            <label for="authorizationCheckbox" style="display:inline;">
                                I acknowledge and agree to the authorization below.
                            </label>
                        </div>
                        <p style="margin:10px 40px;">
                            @if(isset($totalPendingAmount) && $totalPendingAmount > 0)
                                I <strong>{{ isset($user) ? $user->name.' '.$user->last_name : ''}}</strong> hereby authorize Spirit Real Estate Group, LLC to charge my credit card for the agreed upon sponsorship dues of <strong>{{ isset($planPrice) ? '$'.$planPrice : '' }} {{ isset($planName) ? '('.$planName.')' : '' }}</strong> Per month for each month of active sponsorship. I understand that my information will be saved for future transactions.
                            @else
                                I, <strong>{{ isset($user) ? $user->name.' '.$user->last_name : ''}}</strong>, am updating my card information to be used for future transactions with Spirit Real Estate Group, LLC. Your new payment method will be securely saved and used for upcoming payments.
                            @endif
                        </p>
                        <p style="margin:10px 40px;">
                            Please complete all of the fields. You may cancel this authorization at any time by contacting us. This authorization will remain in effect until cancelled.
                        </p>
                        @if(isset($totalPendingAmount) && $totalPendingAmount > 0)
                        <p style="margin:10px 40px;">
                            Account Balance: <strong>${{ number_format($totalPendingAmount, 2) }}</strong>.
                        </p>
                        @endif
                    </div>
                    <hr>
                    <div class="form-group">
                        <label for="payment-method">Select Payment Method</label>
                        <select class="form-control" id="payment-method" name="payment_method" autocomplete="off">
                            <option value="null">Select Payment Method</option>
                            <option value="card">Credit or Debit Card</option>
                            <option value="ach">ACH Bank Transfer</option>
                        </select>
                        <span class="information" style="color:red;font-size:14px;">**Please note a 3.5% processing fee will be added to your total for card payments.</span>
                    </div>
                    <!-- Payment method listing -->
                    <div id="existing-payment-methods" style="margin-bottom:15px; display: none;">
                        <label for="existing-payment-method">Select Existing Payment Method</label>
                        <div id="existing-payment-method-list"></div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="existing_payment_method" id="method-new" value="new">
                            <label class="form-check-label" for="method-new">
                                Add new payment method
                            </label>
                        </div>
                    </div>
                    <div id="no-existing-payment-methods" style="display: none;">
                        <p>No existing payment methods found.</p>
                    </div>
                    <div id="assign-plan-errors" class="alert alert-danger" style="display: none;"></div>
                    <!-- Payment method listing end -->
                    <div id="card-payment" class="payment-method-details" style="display: none;">
                        <div class="form-group">
                            <label for="card-holder-name">Card Holder Name</label>
                            <input id="card-holder-name" type="text" class="form-control" autocomplete="off">
                        </div>
                        <div class="form-row">
                            <label for="card-element">Credit or debit card</label>
                            <div id="card-element" class="form-control"></div>
                            <div id="card-errors" role="alert"></div>
                        </div>
                    </div>
                    <div id="ach-payment" class="payment-method-details" style="display: none;">
                        <div class="form-group">
                            <label for="account-holder-name">Account Holder Name</label>
                            <input id="account-holder-name" type="text" class="form-control" autocomplete="off">
                        </div>
                        <div class="form-group">
                            <label for="account-holder-type">Account Holder Type</label>
                            <select id="account-holder-type" class="form-control" autocomplete="off">
                                <option value="individual">Individual</option>
                                <option value="company">Company</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="routing-number">Routing Number</label>
                            <input id="routing-number" type="text" class="form-control" autocomplete="off">
                        </div>
                        <div class="form-group">
                            <label for="account-number">Account Number</label>
                            <input id="account-number" type="text" class="form-control" autocomplete="off">
                        </div>
                        <div id="ach-errors" role="alert"></div>
                    </div>
                    <div class="modal-footer-" style="display: flex;justify-content: space-between; align-items: center;margin-top: 20px;">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <div class="d-flex">
                            <button type="button" class="btn btn-primary" id="submitPayment" data-secret="{{ isset($intent->client_secret) ? $intent->client_secret : '' }}" disabled>Submit</button>
                            <span id="apLoader" style="display: none;margin-left:5px;"><i class="fa fa-spinner fa-spin" style="font-size:24px"></i></span>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@endsection
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://js.stripe.com/v3/"></script>
<!-- <script>
    $(document).ready(function () {
        var stripe = Stripe('{{ env('STRIPE_KEY') }}');
        var elements = stripe.elements();
        var style = {
            base: {
                color: '#32325d',
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: 'antialiased',
                fontSize: '16px',
                '::placeholder': {
                    color: '#aab7c4'
                }
            },
            invalid: {
                color: '#fa755a',
                iconColor: '#fa755a'
            }
        };

        // Create a single instance of the card element
        var cardElement = elements.create('card', { hidePostalCode: true, style: style });

        // Function to mount the card element
        function mountCardElement() {
            cardElement.mount('#card-element');
        }

        // Function to unmount the card element
        function unmountCardElement() {
            cardElement.unmount();
        }

        // Open the modal for invoice payment
        $('.pay-invoice-button').on('click', function () {
            const userId = $(this).data('user-id');
            const userEmail = $(this).data('user-email');
            const totalAmountDue = $(this).data('total-amount-due');

            // Update modal content
            $('#paymentModalTitle').text('Pay Invoice');
            $('#paymentForm').attr('action', '{{ route('account.pay') }}');
            $('#modalUserId').val(userId);
            $('#modalUserEmail').val(userEmail);
            $('#modalTotalAmountDue').val(totalAmountDue);

            // Show the modal
            $('#paymentModal').modal('show');
        });

        // Open the modal for updating payment method
        $('.update-payment-method-button').on('click', function () {
            const userId = $(this).data('user-id');
            const userEmail = $(this).data('user-email');

            // Update modal content
            $('#paymentModalTitle').text('Update Payment Method');
            $('#paymentForm').attr('action', '{{ route('update-payment-method') }}');
            $('#modalUserId').val(userId);
            $('#modalUserEmail').val(userEmail);
            $('#modalTotalAmountDue').val(''); // Clear total amount due for this context

            // Show the modal
            $('#paymentModal').modal('show');
        });

        // Handle payment method switching
        $('#payment-method').on('change', function () {
            const paymentMethod = $(this).val();
            if (paymentMethod === 'card') {
                $('.information').show();
                $('#card-payment').show();
                $('#ach-payment').hide();
                mountCardElement();
            } else if (paymentMethod === 'ach') {
                $('.information').hide();
                $('#card-payment').hide();
                $('#ach-payment').show();
                unmountCardElement();
            } else {
                $('#card-payment').hide();
                $('#ach-payment').hide();
                unmountCardElement();
            }
        });

        cardElement.addEventListener('change', function (event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
                swal('Error', event.error.message, 'error');
            } else {
                displayError.textContent = '';
            }
        });

        // Handle form submission
        $('#submitPayment').on('click', async function (e) {
            e.preventDefault();
            $('#submitPayment').prop('disabled', true);
            $('#apLoader').show(); 

            const paymentMethod = $('#payment-method').val();
            const clientSecret = $(this).data('secret');

            if (paymentMethod === 'card') {
                const { setupIntent, error } = await stripe.confirmCardSetup(
                    clientSecret, {
                        payment_method: {
                            card: cardElement,
                            billing_details: { name: document.getElementById('card-holder-name').value }
                        }
                    }
                );
                if (error) {
                    $('#submitPayment').prop('disabled', false);
                    $('#apLoader').hide(); 
                    document.getElementById('card-errors').textContent = error.message;
                    swal('Error', error.message, 'error');
                } else {
                    appendPaymentMethodToForm(setupIntent.payment_method);
                }
            } else if (paymentMethod === 'ach') {
                const bankAccount = {
                    country: 'US',
                    currency: 'usd',
                    routing_number: document.getElementById('routing-number').value,
                    account_number: document.getElementById('account-number').value,
                    account_holder_name: document.getElementById('account-holder-name').value,
                    account_holder_type: document.getElementById('account-holder-type').value,
                };
                const { setupIntent, error } = await stripe.confirmUsBankAccountSetup(
                    clientSecret, {
                        payment_method: {
                            us_bank_account: {
                                routing_number: bankAccount.routing_number,
                                account_number: bankAccount.account_number,
                                account_holder_type: bankAccount.account_holder_type,
                            },
                            billing_details: {
                                name: bankAccount.account_holder_name,
                                email: document.getElementById('modalUserEmail').value,
                            },
                        },
                    }
                );
                if (error) {
                    $('#submitPayment').prop('disabled', false);
                    $('#apLoader').hide(); 
                    document.getElementById('ach-errors').textContent = error.message;
                    swal('Error', error.message, 'error');
                } else {
                    appendPaymentMethodToForm(setupIntent.id);
                }
            }
        });

        function appendPaymentMethodToForm(paymentMethodId) {
            var form = document.getElementById('paymentForm');
            var hiddenInput = document.createElement('input');
            hiddenInput.setAttribute('type', 'hidden');
            hiddenInput.setAttribute('name', 'payment_method_id');
            hiddenInput.setAttribute('value', paymentMethodId);
            form.appendChild(hiddenInput);
            form.submit();
        }

        $(document).on('click', '#authorizationCheckbox', function () {
            if ($(this).is(':checked')) {
                $('#submitPayment').prop('disabled', false);
            } else {
                $('#submitPayment').prop('disabled', true);
            }
        })

        $('#subscription-table').DataTable({
            "pageLength": 25
        });

        $('#pending-payments-table').DataTable({
            "pageLength": 25
        });
    });
</script> -->
<script>
$(document).ready(function () {
    var stripe = Stripe('{{ env('STRIPE_KEY') }}');
    var elements = stripe.elements();
    var style = {
        base: {
            color: '#32325d',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': { color: '#aab7c4' }
        },
        invalid: { color: '#fa755a', iconColor: '#fa755a' }
    };
    var cardElement = elements.create('card', { hidePostalCode: true, style: style });

    function mountCardElement() { cardElement.mount('#card-element'); }
    function unmountCardElement() { cardElement.unmount(); }

    // Helper: fetch and show payment methods
    async function fetchPaymentMethods(paymentMethodType, userId) {
        $('#existing-payment-method-list').empty();
        $('#existing-payment-methods').hide();
        $('#no-existing-payment-methods').hide();
        $('#card-payment').hide();
        $('#ach-payment').hide();
        unmountCardElement();

        try {
            const response = await fetch(`{{ url('user-payment-methods') }}/${userId}/${paymentMethodType}`, {
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content") }
            });
            const paymentMethods = await response.json();

            if (Array.isArray(paymentMethods) && paymentMethods.length > 0) {
                $('#existing-payment-methods').show();
                paymentMethods.forEach(method => {
                    const div = document.createElement('div');
                    div.className = 'form-check';
                    div.innerHTML = `
                        <input class="form-check-input" type="radio" name="existing_payment_method" id="method-${method.id}" value="${method.id}">
                        <label class="form-check-label" for="method-${method.id}">
                            ${method.card ? method.card.brand + ' ending in ' + method.card.last4 : 'Bank Account ending in ' + method.us_bank_account.last4}
                        </label>
                    `;
                    $('#existing-payment-method-list').append(div);
                });
                // Add "Add new payment method" radio
                if (!document.getElementById('method-new')) {
                    $('#existing-payment-method-list').append(`
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="existing_payment_method" id="method-new" value="new">
                            <label class="form-check-label" for="method-new">Add new payment method</label>
                        </div>
                    `);
                }
                // Listen for radio change
                $('input[name="existing_payment_method"]').off('change').on('change', function() {
                    if ($(this).val() === 'new') {
                        if ($('#payment-method').val() === 'card') {
                            $('#card-payment').show();
                            $('#ach-payment').hide();
                            mountCardElement();
                        } else if ($('#payment-method').val() === 'ach') {
                            $('#card-payment').hide();
                            $('#ach-payment').show();
                            unmountCardElement();
                        }
                    } else {
                        $('#card-payment').hide();
                        $('#ach-payment').hide();
                        unmountCardElement();
                    }
                });
                // Default: select first existing method
                $('input[name="existing_payment_method"]').first().prop('checked', true).trigger('change');
            } else {
                $('#no-existing-payment-methods').show();
                if (paymentMethodType === 'card') {
                    $('#card-payment').show();
                    $('#ach-payment').hide();
                    mountCardElement();
                } else if (paymentMethodType === 'ach') {
                    $('#card-payment').hide();
                    $('#ach-payment').show();
                    unmountCardElement();
                }
            }
        } catch (error) {
            $('#no-existing-payment-methods').show();
            $('#card-payment').hide();
            $('#ach-payment').hide();
            unmountCardElement();
        }
    }

    // Payment method dropdown change
    $('#payment-method').on('change', function () {
        const paymentMethod = $(this).val();
        const userId = $('#modalUserId').val();
        if (paymentMethod === 'card' || paymentMethod === 'ach') {
            fetchPaymentMethods(paymentMethod, userId);
            if (paymentMethod === 'card') $('.information').show();
            else $('.information').hide();
        } else {
            $('#existing-payment-methods').hide();
            $('#no-existing-payment-methods').hide();
            $('#card-payment').hide();
            $('#ach-payment').hide();
            unmountCardElement();
        }
    });

    cardElement.addEventListener('change', function (event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
            swal('Error', event.error.message, 'error');
        } else {
            displayError.textContent = '';
        }
    });

    // Handle form submission securely
    $('#submitPayment').on('click', async function (e) {
        e.preventDefault();
        $('#submitPayment').prop('disabled', true);
        $('#apLoader').show();

        const paymentMethodType = $('#payment-method').val();
        const selectedExisting = $('input[name="existing_payment_method"]:checked').val();
        const clientSecret = $(this).data('secret');

        // Use existing payment method if selected and not "new"
        if (selectedExisting && selectedExisting !== 'new') {
            appendPaymentMethodToForm(selectedExisting);
            return;
        }

        if (paymentMethodType === 'card') {
            const { setupIntent, error } = await stripe.confirmCardSetup(
                clientSecret, {
                    payment_method: {
                        card: cardElement,
                        billing_details: { name: $('#card-holder-name').val() }
                    }
                }
            );
            if (error) {
                $('#submitPayment').prop('disabled', false);
                $('#apLoader').hide();
                document.getElementById('card-errors').textContent = error.message;
                swal('Error', error.message, 'error');
            } else {
                appendPaymentMethodToForm(setupIntent.payment_method);
            }
        } else if (paymentMethodType === 'ach') {
            const bankAccount = {
                country: 'US',
                currency: 'usd',
                routing_number: $('#routing-number').val(),
                account_number: $('#account-number').val(),
                account_holder_name: $('#account-holder-name').val(),
                account_holder_type: $('#account-holder-type').val(),
            };
            const { setupIntent, error } = await stripe.confirmUsBankAccountSetup(
                clientSecret, {
                    payment_method: {
                        us_bank_account: {
                            routing_number: bankAccount.routing_number,
                            account_number: bankAccount.account_number,
                            account_holder_type: bankAccount.account_holder_type,
                        },
                        billing_details: {
                            name: bankAccount.account_holder_name,
                            email: $('#modalUserEmail').val(),
                        },
                    },
                }
            );
            if (error) {
                $('#submitPayment').prop('disabled', false);
                $('#apLoader').hide();
                document.getElementById('ach-errors').textContent = error.message;
                swal('Error', error.message, 'error');
            } else {
                appendPaymentMethodToForm(setupIntent.id);
            }
        }
    });

    function appendPaymentMethodToForm(paymentMethodId) {
        var form = document.getElementById('paymentForm');
        // Remove any previous hidden input for security
        $('input[name="payment_method_id"]').remove();
        var hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'payment_method_id');
        hiddenInput.setAttribute('value', paymentMethodId);
        form.appendChild(hiddenInput);
        form.submit();
    }

    $(document).on('click', '#authorizationCheckbox', function () {
        $('#submitPayment').prop('disabled', !$(this).is(':checked'));
    });

    // DataTables initialization (unchanged)
    $('#subscription-table').DataTable({ "pageLength": 25 });
    $('#pending-payments-table').DataTable({ "pageLength": 25 });

    // Modal open handlers (unchanged)
    $('.pay-invoice-button').on('click', function () {
        const userId = $(this).data('user-id');
        const userEmail = $(this).data('user-email');
        const totalAmountDue = $(this).data('total-amount-due');
        $('#paymentModalTitle').text('Pay Invoice');
        $('#paymentForm').attr('action', '{{ route('account.pay') }}');
        $('#modalUserId').val(userId);
        $('#modalUserEmail').val(userEmail);
        $('#modalTotalAmountDue').val(totalAmountDue);
        $('#paymentModal').modal('show');
    });

    $('.update-payment-method-button').on('click', function () {
        const userId = $(this).data('user-id');
        const userEmail = $(this).data('user-email');
        $('#paymentModalTitle').text('Update Payment Method');
        $('#paymentForm').attr('action', '{{ route('update-payment-method') }}');
        $('#modalUserId').val(userId);
        $('#modalUserEmail').val(userEmail);
        $('#modalTotalAmountDue').val('');
        $('#paymentModal').modal('show');
    });
});
</script>