@extends('adminlte::page')

@section('title', 'Member Details')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Member Information</h3>
                    <div class="card-tools">
                        <a href="{{ route('memberships.edit', $membership) }}" class="btn btn-warning btn-sm">
                            <i class="fas fa-edit"></i> Edit
                        </a>
                        <a href="{{ route('memberships.index') }}" class="btn btn-secondary btn-sm">
                            <i class="fas fa-arrow-left"></i> Back to Members
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <!-- Passport Photo -->
                        <div class="col-md-4">
                            <div class="text-center">
                                @if($membership->passport_photo)
                                    <img src="{{ asset('storage/memberships/' . $membership->passport_photo) }}"
                                         alt="Passport Photo" class="img-fluid rounded" style="max-height: 200px;">
                                @else
                                    <div class="bg-light rounded p-4">
                                        <i class="fas fa-user fa-4x text-muted"></i>
                                        <p class="text-muted mt-2">No photo uploaded</p>
                                    </div>
                                @endif
                            </div>
                        </div>

                        <!-- Member Details -->
                        <div class="col-md-8">
                            <div class="row">
                                <div class="col-md-6">
                                    <h5 class="text-primary">Personal Information</h5>
                                    <table class="table table-sm">
                                        <tr>
                                            <th>Membership Number:</th>
                                            <td>{{ $membership->membership_number }}</td>
                                        </tr>
                                        <tr>
                                            <th>Full Name:</th>
                                            <td>{{ $membership->user->full_name }}</td>
                                        </tr>
                                        <tr>
                                            <th>Gender:</th>
                                            <td>
                                                <span class="badge badge-{{ $membership->gender === 'male' ? 'info' : 'secondary' }}">
                                                    {{ ucfirst($membership->gender) }}
                                                </span>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>ID Number:</th>
                                            <td>{{ $membership->user->id_number }}</td>
                                        </tr>
                                        <tr>
                                            <th>Phone:</th>
                                            <td>{{ $membership->user->phone_number }}</td>
                                        </tr>
                                        <tr>
                                            <th>Email:</th>
                                            <td>{{ $membership->user->email }}</td>
                                        </tr>
                                    </table>

                                    <!-- Registration Fee Section -->
                                    @if($membership->registration_fee_status === 'pending')
                                    <div class="mt-3">
                                        <div class="d-flex align-items-center justify-content-between">
                                            <div>
                                                <strong class="text-primary">Registration Fee:</strong>
                                                <span class="badge badge-warning ml-2">Pending Payment</span>
                                            </div>
                                            <div class="text-right">
                                                <div class="font-weight-bold text-success">KSh {{ number_format($membership->registration_fee, 2) }}</div>
                                            </div>
                                        </div>

                                        <div class="payment-options-container mt-2">
                                            <div class="payment-methods-grid">
                                                <!-- Cash Payment Card -->
                                                <div class="payment-method-card cash-card" onclick="showCashPaymentModal({{ $membership->id }}, {{ $membership->registration_fee }}, '{{ $membership->user->full_name }}')">
                                                    <div class="payment-icon">
                                                        <i class="fas fa-money-bill-wave text-success"></i>
                                                    </div>
                                                    <div class="payment-details">
                                                        <div class="payment-title">Cash</div>
                                                        <span class="payment-badge badge badge-success">Instant</span>
                                                    </div>
                                                    <div class="payment-arrow">
                                                        <i class="fas fa-chevron-right"></i>
                                                    </div>
                                                </div>

                                                <!-- M-Pesa Payment Card -->
                                                <div class="payment-method-card mpesa-card" onclick="showPaymentModal({{ $membership->id }}, {{ $membership->registration_fee }}, '{{ $membership->user->phone_number }}')">
                                                    <div class="payment-icon">
                                                        <i class="fas fa-mobile-alt text-info"></i>
                                                    </div>
                                                    <div class="payment-details">
                                                        <div class="payment-title">M-Pesa</div>
                                                        <span class="payment-badge badge badge-info">STK</span>
                                                    </div>
                                                    <div class="payment-arrow">
                                                        <i class="fas fa-chevron-right"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    @else
                                    <div class="mt-3">
                                        <div class="d-flex align-items-center justify-content-between">
                                            <div>
                                                <strong class="text-primary">Registration Fee:</strong>
                                                <span class="badge badge-success ml-2">Paid</span>
                                            </div>
                                            <div class="text-right">
                                                <div class="font-weight-bold text-success">KSh {{ number_format($membership->registration_fee, 2) }}</div>
                                            </div>
                                        </div>
                                    </div>
                                    @endif
                                </div>

                                <div class="col-md-6">
                                    <h5 class="text-success">Membership Details</h5>
                                    <table class="table table-sm">
                                        <tr>
                                            <th>Branch:</th>
                                            <td>{{ $membership->user->branch->name ?? 'N/A' }}</td>
                                        </tr>
                                        <tr>
                                            <th>Joining Date:</th>
                                            <td>{{ $membership->joining_date->format('d M Y') }}</td>
                                        </tr>
                                        <tr>
                                            <th>Status:</th>
                                            <td>
                                                <span class="badge badge-{{ $membership->status === 'active' ? 'success' : ($membership->status === 'inactive' ? 'warning' : 'danger') }}">
                                                    {{ ucfirst($membership->status) }}
                                                </span>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Share Capital:</th>
                                            <td>KSh {{ number_format($membership->share_capital, 2) }}</td>
                                        </tr>
                                        <tr>
                                            <th>Savings Balance:</th>
                                            <td>KSh {{ number_format($membership->savings_balance, 2) }}</td>
                                        </tr>
                                        @if($membership->notes)
                                        <tr>
                                            <th>Notes:</th>
                                            <td>
                                                <span class="text-muted">{{ $membership->notes }}</span>
                                            </td>
                                        </tr>
                                        @endif
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <div class="row">
                        <div class="col-md-6">
                            <small class="text-muted">
                                <strong>Created:</strong> {{ $membership->created_at->format('d M Y H:i') }} |
                                <strong>Last Updated:</strong> {{ $membership->updated_at->format('d M Y H:i') }}
                            </small>
                        </div>
                        <div class="col-md-6 text-right">
                            <form action="{{ route('memberships.destroy', $membership) }}" method="POST" class="d-inline"
                                  onsubmit="return confirm('Are you sure you want to delete this member? This action cannot be undone.')">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash"></i> Delete Member
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Transactions -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Recent Transactions</h3>
                    <div class="card-tools">
                        <div class="btn-group">
                            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">
                                <i class="fas fa-download"></i> Export
                            </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" href="{{ route('memberships.export-member-activities.csv', $membership) }}" target="_blank">
                                    <i class="fas fa-file-csv text-success"></i> Export as CSV
                                </a>
                                <a class="dropdown-item" href="{{ route('memberships.export-member-activities.excel', $membership) }}" target="_blank">
                                    <i class="fas fa-file-excel text-success"></i> Export as Excel
                                </a>
                                <a class="dropdown-item" href="{{ route('memberships.export-member-activities.pdf', $membership) }}" target="_blank">
                                    <i class="fas fa-file-pdf text-danger"></i> Export as PDF
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body table-responsive p-0">
                    <table class="table table-hover text-nowrap">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Description</th>
                            </tr>
                        </thead>
                        <tbody>
                             @forelse($recentActivities as $activity)
                             <tr>
                                 <td>{{ $activity['date']->format('d M Y') }}</td>
                                 <td>
                                     <span class="badge badge-{{ $activity['module'] === 'savings' ? ($activity['type'] === 'savings_deposit' ? 'success' : 'warning') : 'primary' }}">
                                         {{ ucwords(str_replace('_', ' ', $activity['type'])) }}
                                     </span>
                                 </td>
                                 <td>KSh {{ number_format($activity['amount'], 2) }}</td>
                                 <td>
                                     <span class="badge badge-{{ $activity['status'] === 'completed' ? 'success' : ($activity['status'] === 'pending' ? 'warning' : ($activity['status'] === 'approved' ? 'info' : 'danger')) }}">
                                         {{ ucfirst($activity['status']) }}
                                     </span>
                                 </td>
                                 <td>{{ $activity['description'] }}</td>
                             </tr>
                             @empty
                             <tr>
                                 <td colspan="5" class="text-center py-4">
                                     <div class="text-muted">
                                         <i class="fas fa-history fa-2x mb-2"></i>
                                         <p>No recent activities found</p>
                                     </div>
                                 </td>
                             </tr>
                             @endforelse
                         </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Cash Payment Modal -->
    <div class="modal fade" id="cashPaymentModal" tabindex="-1" role="dialog" aria-labelledby="cashPaymentModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="cashPaymentModalLabel">
                        <i class="fas fa-money-bill-wave text-success mr-2"></i>Record Cash Payment for Registration Fee
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-success">
                        <i class="fas fa-info-circle mr-2"></i>
                        Record cash payment received for the registration fee. This will activate the member account and update all related records.
                    </div>

                    <form id="cash-payment-form">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Amount Received</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">KSh</span>
                                        </div>
                                        <input type="number" class="form-control form-control-lg" id="cash-payment-amount"
                                               min="0.01" step="0.01" required>
                                    </div>
                                    <small class="form-text text-muted">
                                        Required: KSh <span id="required-amount"></span>
                                    </small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Member</label>
                                    <input type="text" class="form-control form-control-lg" id="cash-member-name" readonly>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="cash-payment-notes" class="font-weight-bold">Payment Notes (Optional)</label>
                            <textarea class="form-control" id="cash-payment-notes" rows="2"
                                      placeholder="Enter any additional notes about the cash payment..."></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" id="record-cash-payment-btn">
                        <i class="fas fa-money-bill-wave mr-1"></i>Record Cash Payment
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- M-Pesa Payment Modal -->
    <div class="modal fade" id="mpesaPaymentModal" tabindex="-1" role="dialog" aria-labelledby="mpesaPaymentModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mpesaPaymentModalLabel">
                        <i class="fas fa-mobile-alt text-success mr-2"></i>Pay Registration Fee via M-Pesa
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i>
                        Enter the M-Pesa phone number that will receive the STK push for payment.
                        This number will be recorded in the transaction reports.
                    </div>

                    <form id="mpesa-payment-form">
                        <div class="form-group">
                            <label for="mpesa-phone-number" class="font-weight-bold">
                                M-Pesa Phone Number <span class="text-danger">*</span>
                            </label>
                            <input type="tel" class="form-control form-control-lg" id="mpesa-phone-number"
                                   placeholder="254XXXXXXXXX" required pattern="^254[0-9]{9}$"
                                   title="Enter phone number in format: 254XXXXXXXXX">
                            <small class="form-text text-muted">
                                Enter the phone number in the format: 254XXXXXXXXX (e.g., 254712345678)
                            </small>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Amount to Pay</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">KSh</span>
                                        </div>
                                        <input type="text" class="form-control" id="payment-amount" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Member</label>
                                    <input type="text" class="form-control" id="member-name" readonly>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" id="initiate-payment-btn">
                        <i class="fas fa-mobile-alt mr-1"></i>Initiate STK Push
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentMembershipId = null;
let currentAmount = null;

function showCashPaymentModal(membershipId, amount, memberName) {
    currentMembershipId = membershipId;
    currentAmount = amount;

    // Set form values
    document.getElementById('cash-payment-amount').value = amount;
    document.getElementById('required-amount').textContent = amount.toLocaleString();
    document.getElementById('cash-member-name').value = memberName;
    document.getElementById('cash-payment-notes').value = '';

    // Show modal
    $('#cashPaymentModal').modal('show');
}

function showPaymentModal(membershipId, amount, defaultPhone) {
    currentMembershipId = membershipId;
    currentAmount = amount;

    // Set form values
    document.getElementById('mpesa-phone-number').value = defaultPhone;
    document.getElementById('payment-amount').value = amount.toLocaleString();
    document.getElementById('member-name').value = '{{ $membership->user->full_name }}';

    // Show modal
    $('#mpesaPaymentModal').modal('show');
}

// Handle cash payment recording
document.getElementById('record-cash-payment-btn').addEventListener('click', function() {
    const amount = document.getElementById('cash-payment-amount').value;
    const notes = document.getElementById('cash-payment-notes').value;

    if (!amount || amount <= 0) {
        alert('Please enter a valid payment amount.');
        return;
    }

    // Disable button and show loading
    const button = this;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Processing...';
    button.disabled = true;

    // Make AJAX request to record cash payment
    fetch('/memberships/' + currentMembershipId + '/pay-cash-registration-fee', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({
            amount: parseFloat(amount),
            notes: notes
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            $('#cashPaymentModal').modal('hide');
            alert('Cash payment recorded successfully! Member account has been activated.');
            // Reload page to show updated status
            window.location.reload();
        } else {
            alert('Error: ' + (data.message || 'Failed to record cash payment'));
            button.innerHTML = originalText;
            button.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while recording the payment.');
        button.innerHTML = originalText;
        button.disabled = false;
    });
});

// Handle payment initiation
document.getElementById('initiate-payment-btn').addEventListener('click', function() {
    const phoneNumber = document.getElementById('mpesa-phone-number').value;
    const phonePattern = /^254[0-9]{9}$/;

    if (!phoneNumber) {
        alert('Please enter a phone number.');
        return;
    }

    if (!phonePattern.test(phoneNumber)) {
        alert('Please enter a valid phone number in the format: 254XXXXXXXXX');
        return;
    }

    // Disable button and show loading
    const button = this;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Processing...';
    button.disabled = true;

    // Make AJAX request to initiate M-Pesa payment
    fetch('/memberships/' + currentMembershipId + '/pay-registration-fee', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({
            amount: currentAmount,
            mpesa_phone_number: phoneNumber
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            $('#mpesaPaymentModal').modal('hide');
            alert('M-Pesa STK push initiated successfully! Please check your phone (' + phoneNumber + ') for the payment prompt.');
            // Reload page after 5 seconds to check payment status
            setTimeout(() => {
                window.location.reload();
            }, 5000);
        } else {
            alert('Error: ' + (data.message || 'Failed to initiate payment'));
            button.innerHTML = originalText;
            button.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while processing the payment.');
        button.innerHTML = originalText;
        button.disabled = false;
    });
});

// Reset modals when closed
$('#cashPaymentModal').on('hidden.bs.modal', function () {
    document.getElementById('cash-payment-amount').value = '';
    document.getElementById('cash-payment-notes').value = '';
    document.getElementById('record-cash-payment-btn').innerHTML = '<i class="fas fa-money-bill-wave mr-1"></i>Record Cash Payment';
    document.getElementById('record-cash-payment-btn').disabled = false;
});

$('#mpesaPaymentModal').on('hidden.bs.modal', function () {
    document.getElementById('mpesa-phone-number').value = '';
    document.getElementById('initiate-payment-btn').innerHTML = '<i class="fas fa-mobile-alt mr-1"></i>Initiate STK Push';
    document.getElementById('initiate-payment-btn').disabled = false;
});
</script>

<style>
/* Payment Methods UI - Compact Inline */
.payment-options-container {
    background: transparent;
    border-radius: 6px;
    padding: 0.5rem 0;
    border: none;
    margin-top: 0.25rem;
    display: inline-block;
}

.payment-methods-grid {
    display: flex;
    gap: 0.5rem;
    align-items: center;
}

.payment-method-card {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 3px;
    padding: 0.375rem 0.5rem;
    cursor: pointer;
    transition: all 0.15s ease;
    display: flex;
    align-items: center;
    text-decoration: none;
    color: inherit;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
    min-width: 110px;
    justify-content: center;
}

.payment-method-card:hover {
    border-color: #007bff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transform: translateY(-1px);
}

.cash-card:hover {
    border-color: #28a745;
}

.mpesa-card:hover {
    border-color: #17a2b8;
}

.payment-icon {
    flex-shrink: 0;
    margin-right: 0.375rem;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    background: rgba(0,0,0,0.05);
    border-radius: 50%;
    font-size: 0.7rem;
}

.payment-details {
    flex: 1;
    min-width: 0;
    text-align: left;
}

.payment-title {
    margin: 0;
    font-weight: 600;
    color: #495057;
    font-size: 0.75rem;
    line-height: 1.2;
}

.payment-description {
    margin: 0;
    color: #6c757d;
    font-size: 0.7rem;
    line-height: 1.2;
    display: none; /* Hide description for compact design */
}

.payment-badge {
    font-size: 0.55rem;
    padding: 0.08rem 0.25rem;
    border-radius: 6px;
    margin-left: 0.2rem;
    display: inline-block;
}

.payment-arrow {
    flex-shrink: 0;
    margin-left: 0.2rem;
    color: #adb5bd;
    transition: color 0.15s ease;
    font-size: 0.65rem;
}

.payment-method-card:hover .payment-arrow {
    color: #495057;
}

/* Enhanced modal styling */
.modal-content {
    border-radius: 12px;
    border: none;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.modal-header {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
    border-radius: 12px 12px 0 0;
    border-bottom: none;
    padding: 1.5rem;
}

.modal-header .close {
    color: white;
    opacity: 0.8;
}

.modal-header .close:hover {
    color: white;
    opacity: 1;
}

.modal-body {
    padding: 2rem;
}

.modal-footer {
    border-top: 1px solid #dee2e6;
    padding: 1.5rem 2rem;
    border-radius: 0 0 12px 12px;
}
</style>
@stop

