@extends('layouts.app')

@section('page-title', $user->present()->nameOrEmail)
@section('page-heading', $user->present()->nameOrEmail)

@section('breadcrumbs')
    <li class="breadcrumb-item">
        <a href="{{ route('users.index') }}">@lang('Users')</a>
    </li>
    <li class="breadcrumb-item active">
        {{ $user->present()->nameOrEmail }}
    </li>
@stop

@section('content')

<div class="row">
    <!-- ✅ Details Card - کم پهنا شده -->
    <div class="col-lg-3">
        <div class="card">
            <h6 class="card-header d-flex align-items-center justify-content-between">
                @lang('Details')

                <small>
                    @canBeImpersonated($user)
                    <a href="{{ route('impersonate', $user) }}"
                       data-toggle="tooltip"
                       data-placement="top"
                       title="@lang('Impersonate User')">
                        @lang('Impersonate')
                    </a>
                    <span class="text-muted">|</span>
                    @endCanBeImpersonated

                    <a href="{{ route('users.edit', $user) }}"
                       class="edit"
                       data-toggle="tooltip"
                       data-placement="top"
                       title="@lang('Edit User')">
                        @lang('Edit')
                    </a>
                </small>
            </h6>
            <div class="card-body">
               <div class="d-flex align-items-center flex-column pt-3">
                    <div>
                        <img class="rounded-circle img-thumbnail img-responsive mb-4"
                             width="130"
                             height="130" src="{{ $user->present()->avatar }}">
                    </div>

                    @if ($name = $user->present()->name)
                        <h5>{{ $user->present()->name }}</h5>
                    @endif

                    <a href="mailto:{{ $user->email }}" class="text-muted font-weight-light mb-2">
                        {{ $user->email }}
                    </a>
                </div>

                <ul class="list-group list-group-flush mt-3">
                    @if ($user->phone)
                        <li class="list-group-item">
                            <strong>@lang('Phone'):</strong>
                            <a href="telto:{{ $user->phone }}">{{ $user->phone }}</a>
                        </li>
                    @endif
                    <li class="list-group-item">
                        <strong>@lang('Birthday'):</strong>
                        {{ $user->present()->birthday }}
                    </li>
                    <li class="list-group-item">
                        <strong>@lang('Address'):</strong>
                        {{ $user->present()->fullAddress }}
                    </li>
                    <li class="list-group-item">
                        <strong>@lang('Last Logged In'):</strong>
                        {{ $user->present()->lastLogin }}
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <!-- ✅ Transactions - پهنای بیشتر -->
    <div class="col-lg-9">
        <div class="card">
            <h6 class="card-header">
                @lang('Transactions')
            </h6>
            <div class="card-body">
                <!-- ✅ فیلتر بالای جدول -->
                <div class="row mb-3">
                    <div class="col-md-4">
                        <div class="btn-group" role="group">
                            <button type="button" 
                                    class="btn btn-sm btn-outline-secondary filter-btn active" 
                                    data-filter="all">
                                @lang('All') ({{ count($purchases) + count($voucherRedemptions) }})
                            </button>
                            <button type="button" 
                                    class="btn btn-sm btn-outline-secondary filter-btn" 
                                    data-filter="purchase">
                                @lang('Purchases') ({{ count($purchases) }})
                            </button>
                            <button type="button" 
                                    class="btn btn-sm btn-outline-secondary filter-btn" 
                                    data-filter="voucher">
                                @lang('Vouchers') ({{ count($voucherRedemptions) }})
                            </button>
                        </div>
                    </div>
                </div>

                <!-- ✅ جدول واحد -->
                <div class="table-responsive">
                    @php
                        // Merge تراکنش‌ها
                        $transactions = collect();
                        
                        // اضافه کردن Purchases
                        foreach ($purchases as $purchase) {
                            $transactions->push([
                                'type' => 'purchase',
                                'type_label' => 'خرید',
                                'reference' => $purchase->product_id,
                                'seconds' => $purchase->seconds_added,
                                'price' => $purchase->price,
                                'currency' => $purchase->currency,
                                'status' => $purchase->status,
                                'date' => $purchase->purchased_at,
                                'details' => $purchase,
                            ]);
                        }
                        
                        // اضافه کردن Vouchers
                        foreach ($voucherRedemptions as $redemption) {
                            $transactions->push([
                                'type' => 'voucher',
                                'type_label' => 'کوپن',
                                'reference' => $redemption->code_snapshot,
                                'seconds' => $redemption->voucher?->seconds ?? 0,
                                'price' => null,
                                'currency' => null,
                                'status' => $redemption->status,
                                'date' => $redemption->redeemed_at,
                                'details' => $redemption,
                            ]);
                        }
                        
                        // مرتب کردن به تاریخ (جدیدترین اول)
                        $transactions = $transactions->sortByDesc('date');
                    @endphp

                    @if ($transactions->count() > 0)
                        <table class="table table-striped table-borderless" id="transactions-table">
                            <thead style="background-color: #f8f9fa;">
                                <tr>
                                    <th style="font-weight: 600; color: #495057;">@lang('Type')</th>
                                    <th style="font-weight: 600; color: #495057;">@lang('Reference')</th>
                                    <th style="font-weight: 600; color: #495057;">@lang('Seconds')</th>
                                    <th style="font-weight: 600; color: #495057;">@lang('Price')</th>
                                    <th style="font-weight: 600; color: #495057;">@lang('Status')</th>
                                    <th style="font-weight: 600; color: #495057;">@lang('Date')</th>
                                    <th style="font-weight: 600; color: #495057; text-align: center;">@lang('Details')</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($transactions as $index => $transaction)
                                    <tr class="transaction-row" data-type="{{ $transaction['type'] }}">
                                        <!-- ✅ نوع تراکنش -->
                                        <td>
                                            @if ($transaction['type'] === 'purchase')
                                                <span class="badge badge-primary">🛒 @lang('Purchase')</span>
                                            @else
                                                <span class="badge badge-success">🎫 @lang('Voucher')</span>
                                            @endif
                                        </td>

                                        <!-- ✅ مرجع (Product ID یا Voucher Code) -->
                                        <td>
                                            <strong>{{ $transaction['reference'] }}</strong>
                                        </td>

                                        <!-- ✅ مقدار شارژ -->
                                        <td>
                                            <span class="badge badge-info">
                                                {{ gmdate('H:i:s', $transaction['seconds']) }}
                                            </span>
                                        </td>

                                        <!-- ✅ قیمت (فقط برای خریدها) -->
                                        <td>
                                            @if ($transaction['price'])
                                                {{ number_format($transaction['price'], 2) }} 
                                                <small>{{ $transaction['currency'] }}</small>
                                            @else
                                                <span class="text-muted">-</span>
                                            @endif
                                        </td>

                                        <!-- ✅ وضعیت -->
                                        <td>
                                            @if ($transaction['status'] === 'success')
                                                <span class="badge badge-success">✓ @lang('Success')</span>
                                            @elseif ($transaction['status'] === 'pending')
                                                <span class="badge badge-warning">⏳ @lang('Pending')</span>
                                            @else
                                                <span class="badge badge-danger">✗ @lang('Failed')</span>
                                            @endif
                                        </td>

                                        <!-- ✅ تاریخ با Timezone عمان +4 -->
                                        <td>
                                            <small>{{ $transaction['date']?->setTimezone('+04:00')->format('Y-m-d H:i') ?? '-' }}</small>
                                        </td>

                                        <!-- ✅ دکمه چشم برای جزئیات -->
                                        <td style="text-align: center;">
                                            <button type="button" 
                                                    class="btn btn-sm btn-link view-details-btn"
                                                    data-toggle="modal"
                                                    data-target="#detailsModal"
                                                    data-transaction="{{ json_encode($transaction) }}"
                                                    title="@lang('View Details')">
                                                <i class="fas fa-eye text-primary"></i>
                                            </button>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    @else
                        <div class="alert alert-info" role="alert">
                            @lang('No transactions found.')
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ✅ Modal جزئیات تراکنش - Modern Design -->
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px;">
            <div class="modal-header border-bottom" style="background: linear-gradient(135deg, #27ae60 0%, #229954 100%); color: white;">
                <h5 class="modal-title" id="detailsModalLabel" style="font-weight: 600;">@lang('Transaction Details')</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: white; opacity: 0.8;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="modal-details-content" style="padding: 30px;">
                <!-- محتویات بر اساس نوع تراکنش قرار می‌گیرد -->
            </div>
            <div class="modal-footer border-top">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">@lang('Close')</button>
            </div>
        </div>
    </div>
</div>

<!-- ✅ Modal View Receipt -->
<div class="modal fade" id="receiptModal" tabindex="-1" role="dialog" aria-labelledby="receiptModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px;">
            <div class="modal-header border-bottom" style="background: linear-gradient(135deg, #27ae60 0%, #229954 100%); color: white;">
                <h5 class="modal-title" id="receiptModalLabel">@lang('Receipt Details')</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: white; opacity: 0.8;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="receipt-content" style="padding: 30px; max-height: 600px; overflow-y: auto;">
                <!-- محتوی رسید JSON -->
            </div>
            <div class="modal-footer border-top">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">@lang('Close')</button>
            </div>
        </div>
    </div>
</div>

@stop

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // ✅ فیلتر کردن
    const filterButtons = document.querySelectorAll('.filter-btn');
    const transactionRows = document.querySelectorAll('.transaction-row');

    filterButtons.forEach(button => {
        button.addEventListener('click', function() {
            const filter = this.getAttribute('data-filter');

            filterButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            transactionRows.forEach(row => {
                if (filter === 'all') {
                    row.style.display = '';
                } else {
                    row.style.display = row.getAttribute('data-type') === filter ? '' : 'none';
                }
            });
        });
    });

    // ✅ Modal جزئیات تراکنش
    const viewDetailsBtns = document.querySelectorAll('.view-details-btn');
    
    viewDetailsBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const transactionData = JSON.parse(this.getAttribute('data-transaction'));
            const modalContent = document.getElementById('modal-details-content');
            const modalTitle = document.getElementById('detailsModalLabel');
            
            let html = '';

            if (transactionData.type === 'purchase') {
                const details = transactionData.details;
                const countryName = details.country ? details.country.name : 'N/A';
                
                html = `
                    <div class="transaction-details">
                        <!-- ✅ Transaction ID و Status -->
                        <div style="margin-bottom: 25px;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div>
                                    <h6 style="color: #667eea; font-weight: 600; margin-bottom: 5px;">@lang('Transaction ID')</h6>
                                    <h3 style="margin: 0; color: #333;">#${details.id}</h3>
                                </div>
                                <div>
                                    ${getStatusBadge(details.status)}
                                </div>
                            </div>
                        </div>

                        <hr style="margin: 20px 0; border-color: #e9ecef;">

                        <!-- ✅ Basic Information -->
                        <div class="row">
                            <div class="col-md-6" style="margin-bottom: 20px;">
                                <h6 style="color: #667eea; font-weight: 600; font-size: 14px; margin-bottom: 15px; text-transform: uppercase;">🛒 @lang('Purchase Information')</h6>
                                
                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Product')</small>
                                    <strong style="color: #333; font-size: 15px;">${details.product_id}</strong>
                                </div>

                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Seconds')</small>
                                    <span class="badge badge-info" style="font-size: 13px; padding: 6px 10px;">
                                        ${formatSeconds(details.seconds_added)}
                                    </span>
                                </div>

                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Price')</small>
                                    <strong style="color: #28a745; font-size: 15px;">${details.price ? (Math.round(details.price * 100) / 100).toFixed(2) + ' ' + details.currency : '-'}</strong>
                                </div>

                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Purchase Date')</small>
                                    <strong style="color: #333; font-size: 14px;">${formatDateWithTimezone(details.purchased_at)}</strong>
                                </div>
                            </div>

                            <div class="col-md-6" style="margin-bottom: 20px;">
                                <h6 style="color: #667eea; font-weight: 600; font-size: 14px; margin-bottom: 15px; text-transform: uppercase;">🌐 @lang('Device Information')</h6>
                                
                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Device ID')</small>
                                    <code style="background: #f8f9fa; padding: 6px 10px; border-radius: 4px; display: block; word-break: break-all; color: #333;">${details.device_id || '-'}</code>
                                </div>

                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('IP Address')</small>
                                    <code style="background: #f8f9fa; padding: 6px 10px; border-radius: 4px; color: #333;">${details.ip || '-'}</code>
                                </div>

                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Country')</small>
                                    <strong style="color: #333; font-size: 14px;">🌍 ${countryName}</strong>
                                </div>
                            </div>
                        </div>

                        <hr style="margin: 20px 0; border-color: #e9ecef;">

                        <!-- ✅ Google Play Information -->
                        <div style="margin-bottom: 20px;">
                            <h6 style="color: #667eea; font-weight: 600; font-size: 14px; margin-bottom: 15px; text-transform: uppercase;">🔐 @lang('Google Play Billing')</h6>
                            
                            <div style="margin-bottom: 12px;">
                                <small style="color: #6c757d; display: block;">@lang('Purchase Token')</small>
                                <code style="background: #f8f9fa; padding: 10px; border-radius: 4px; display: block; word-break: break-all; font-size: 12px; color: #333; max-height: 80px; overflow-y: auto;">${details.purchase_token || '-'}</code>
                            </div>

                            <div style="margin-bottom: 12px;">
                                <small style="color: #6c757d; display: block;">@lang('Receipt')</small>
                                <button type="button" class="btn btn-success btn-sm view-receipt-btn" data-receipt='${details.receipt || ''}' style="margin-top: 5px;">
                                    <i class="fas fa-file-alt mr-2"></i> @lang('View Receipt')
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                modalTitle.textContent = '@lang("Purchase Details") #' + details.id;
            } else {
                const details = transactionData.details;
                html = `
                    <div class="transaction-details">
                        <!-- ✅ Code و Status -->
                        <div style="margin-bottom: 25px;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div>
                                    <h6 style="color: #667eea; font-weight: 600; margin-bottom: 5px;">@lang('Voucher Code')</h6>
                                    <h3 style="margin: 0; color: #333; font-family: monospace;">${details.code_snapshot}</h3>
                                </div>
                                <div>
                                    ${getStatusBadge(details.status)}
                                </div>
                            </div>
                        </div>

                        <hr style="margin: 20px 0; border-color: #e9ecef;">

                        <!-- ✅ Basic Information -->
                        <div class="row">
                            <div class="col-md-6" style="margin-bottom: 20px;">
                                <h6 style="color: #667eea; font-weight: 600; font-size: 14px; margin-bottom: 15px; text-transform: uppercase;">🎫 @lang('Voucher Information')</h6>
                                
                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Seconds')</small>
                                    <span class="badge badge-info" style="font-size: 13px; padding: 6px 10px;">
                                        ${formatSeconds(transactionData.seconds)}
                                    </span>
                                </div>

                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Redeemed At')</small>
                                    <strong style="color: #333; font-size: 14px;">${formatDateWithTimezone(details.redeemed_at)}</strong>
                                </div>
                            </div>

                            <div class="col-md-6" style="margin-bottom: 20px;">
                                <h6 style="color: #667eea; font-weight: 600; font-size: 14px; margin-bottom: 15px; text-transform: uppercase;">🌐 @lang('Device Information')</h6>
                                
                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('Device ID')</small>
                                    <code style="background: #f8f9fa; padding: 6px 10px; border-radius: 4px; display: block; word-break: break-all; color: #333;">${details.device_id || '-'}</code>
                                </div>

                                <div style="margin-bottom: 12px;">
                                    <small style="color: #6c757d; display: block;">@lang('IP Address')</small>
                                    <code style="background: #f8f9fa; padding: 6px 10px; border-radius: 4px; color: #333;">${details.ip || '-'}</code>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                modalTitle.textContent = '@lang("Voucher Details") - ' + details.code_snapshot;
            }

            modalContent.innerHTML = html;
        });
    });

    // ✅ View Receipt Button
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('view-receipt-btn')) {
            const receiptData = e.target.getAttribute('data-receipt');
            
            if (!receiptData || receiptData.trim() === '') {
                alert('@lang("No receipt data available")');
                return;
            }

            try {
                const receipt = JSON.parse(receiptData);
                const receiptContent = document.getElementById('receipt-content');
                
                let html = '<pre style="background: #f8f9fa; padding: 15px; border-radius: 6px; overflow-x: auto;">';
                html += JSON.stringify(receipt, null, 2);
                html += '</pre>';
                
                receiptContent.innerHTML = html;
                
                $('#receiptModal').modal('show');
            } catch (error) {
                // اگر JSON نبود، به صورت plain text نشان بده
                document.getElementById('receipt-content').innerHTML = 
                    '<pre style="background: #f8f9fa; padding: 15px; border-radius: 6px; word-break: break-all;">' + 
                    receiptData + 
                    '</pre>';
                
                $('#receiptModal').modal('show');
            }
        }
    });
});

// ✅ تابع فرمت کردن ثانیه‌ها
function formatSeconds(seconds) {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}

// ✅ تابع نمایش Badge وضعیت
function getStatusBadge(status) {
    if (status === 'success') {
        return '<span class="badge badge-success" style="padding: 8px 12px; font-size: 13px;">✓ @lang("Success")</span>';
    } else if (status === 'pending') {
        return '<span class="badge badge-warning" style="padding: 8px 12px; font-size: 13px;">⏳ @lang("Pending")</span>';
    } else {
        return '<span class="badge badge-danger" style="padding: 8px 12px; font-size: 13px;">✗ @lang("Failed")</span>';
    }
}

// ✅ تابع فرمت تاریخ با Timezone عمان +4
function formatDateWithTimezone(dateString) {
    const date = new Date(dateString);
    
    // عمان UTC+4 = Asia/Dubai
    const formatter = new Intl.DateTimeFormat('en-US', {
        timeZone: 'Asia/Dubai',
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
    
    return formatter.format(date);
}
</script>
@stop