

<?php $__env->startSection('title', 'إدارة أرباح الإحالات'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="h3 mb-0 text-gray-800">
                    <i class="fas fa-dollar-sign text-success"></i>
                    إدارة أرباح الإحالات
                </h1>
                <div class="btn-group">
                    <button type="button" class="btn btn-success" onclick="exportEarnings()">
                        <i class="fas fa-file-excel"></i> تصدير Excel
                    </button>
                    <a href="<?php echo e(route('admin.points.dashboard')); ?>" class="btn btn-outline-primary">
                        <i class="fas fa-arrow-right"></i> العودة للوحة الرئيسية
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- إحصائيات الأرباح -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                إجمالي الأرباح
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                <?php echo e(number_format($stats['total_earnings'], 2)); ?> دينار
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                الأرباح المعلقة
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                <?php echo e(number_format($stats['pending_earnings'], 2)); ?> دينار
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clock fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                الأرباح المدفوعة
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                <?php echo e(number_format($stats['paid_earnings'], 2)); ?> دينار
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                أرباح اليوم
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                <?php echo e(number_format($stats['today_earnings'], 2)); ?> دينار
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar-day fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- رسوم بيانية للأرباح -->
    <div class="row mb-4">
        <div class="col-xl-6 col-md-12 mb-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-chart-line"></i> توزيع الأرباح حسب الحالة
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="earningsStatusChart" height="100"></canvas>
                </div>
            </div>
        </div>
        <div class="col-xl-6 col-md-12 mb-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-chart-pie"></i> توزيع الأرباح حسب نوع الطلب
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="earningsTypeChart" height="100"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- جدول الأرباح -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">قائمة الأرباح</h6>
                </div>
                <div class="card-body">
                    <!-- فلتر البحث -->
                    <form method="GET" action="<?php echo e(route('admin.points.earnings')); ?>" class="mb-3">
                        <div class="row">
                            <div class="col-md-2">
                                <label class="small text-muted">الحالة</label>
                                <select name="status" class="form-control">
                                    <option value="">جميع الحالات</option>
                                    <option value="pending" <?php echo e(request('status') == 'pending' ? 'selected' : ''); ?>>معلق</option>
                                    <option value="approved" <?php echo e(request('status') == 'approved' ? 'selected' : ''); ?>>موافق</option>
                                    <option value="paid" <?php echo e(request('status') == 'paid' ? 'selected' : ''); ?>>مدفوع</option>
                                    <option value="cancelled" <?php echo e(request('status') == 'cancelled' ? 'selected' : ''); ?>>ملغي</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="small text-muted">نوع الطلب</label>
                                <select name="order_type" class="form-control">
                                    <option value="">جميع الأنواع</option>
                                    <option value="food" <?php echo e(request('order_type') == 'food' ? 'selected' : ''); ?>>طعام</option>
                                    <option value="gas" <?php echo e(request('order_type') == 'gas' ? 'selected' : ''); ?>>غاز</option>
                                    <option value="taxi" <?php echo e(request('order_type') == 'taxi' ? 'selected' : ''); ?>>تاكسي</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="small text-muted">اسم المدعو</label>
                                <input type="text" name="referrer" class="form-control" placeholder="اسم المدعو" value="<?php echo e(request('referrer')); ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="small text-muted">من تاريخ</label>
                                <input type="date" name="start_date" class="form-control" value="<?php echo e(request('start_date')); ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="small text-muted">إلى تاريخ</label>
                                <input type="date" name="end_date" class="form-control" value="<?php echo e(request('end_date')); ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="small text-muted d-block">&nbsp;</label>
                                <button type="submit" class="btn btn-primary btn-block">
                                    <i class="fas fa-search"></i> بحث
                                </button>
                                <a href="<?php echo e(route('admin.points.earnings')); ?>" class="btn btn-secondary btn-block mt-1">
                                    <i class="fas fa-redo"></i> إعادة تعيين
                                </a>
                            </div>
                        </div>
                    </form>

                    <?php if($earnings->count() > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>من دعا</th>
                                        <th>من تم دعوته</th>
                                        <th>نوع الطلب</th>
                                        <th>رقم الطلبية</th>
                                        <th>قيمة الطلبية</th>
                                        <th>الربح</th>
                                        <th>الحالة</th>
                                        <th>التاريخ</th>
                                        <th>الإجراءات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $__currentLoopData = $earnings; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $earning): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <tr>
                                            <td><?php echo e($earning->id); ?></td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="mr-2">
                                                        <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                                            <span class="text-white font-weight-bold"><?php echo e(substr($earning->referrer->name, 0, 1)); ?></span>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <div class="font-weight-bold">
                                                            <a href="<?php echo e(route('admin.points.user-report', $earning->referrer_id)); ?>" class="text-primary" title="عرض التقرير المفصل">
                                                                <?php echo e($earning->referrer->name); ?>

                                                                <i class="fas fa-external-link-alt fa-sm"></i>
                                                            </a>
                                                        </div>
                                                        <small class="text-muted"><?php echo e($earning->referrer->phone); ?></small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="mr-2">
                                                        <div class="bg-info rounded-circle d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                                            <span class="text-white font-weight-bold"><?php echo e(substr($earning->referred->name, 0, 1)); ?></span>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <div class="font-weight-bold"><?php echo e($earning->referred->name); ?></div>
                                                        <small class="text-muted"><?php echo e($earning->referred->phone); ?></small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <?php if($earning->order_type == 'food'): ?>
                                                    <span class="badge badge-warning">طعام</span>
                                                <?php elseif($earning->order_type == 'gas'): ?>
                                                    <span class="badge badge-danger">غاز</span>
                                                <?php elseif($earning->order_type == 'taxi'): ?>
                                                    <span class="badge badge-primary">تاكسي</span>
                                                <?php else: ?>
                                                    <span class="badge badge-secondary"><?php echo e($earning->order_type); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo e($earning->order_number); ?></td>
                                            <td><?php echo e(number_format($earning->order_total, 2)); ?> دينار</td>
                                            <td>
                                                <span class="font-weight-bold text-success">
                                                    <?php echo e(number_format($earning->earnings, 2)); ?> دينار
                                                </span>
                                                <br>
                                                <small class="text-muted">(<?php echo e(number_format($earning->profit_percentage * 100, 3)); ?>%)</small>
                                            </td>
                                            <td>
                                                <?php if($earning->status == 'pending'): ?>
                                                    <span class="badge badge-warning">معلق</span>
                                                <?php elseif($earning->status == 'approved'): ?>
                                                    <span class="badge badge-info">موافق</span>
                                                <?php elseif($earning->status == 'paid'): ?>
                                                    <span class="badge badge-success">مدفوع</span>
                                                <?php else: ?>
                                                    <span class="badge badge-danger">ملغي</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <small><?php echo e($earning->created_at->format('Y-m-d H:i')); ?></small>
                                                <?php if($earning->paid_at): ?>
                                                    <br>
                                                    <small class="text-muted">دفع: <?php echo e($earning->paid_at->format('Y-m-d H:i')); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <?php if($earning->status == 'pending'): ?>
                                                        <form method="POST" action="<?php echo e(route('admin.points.earnings.approve', $earning->id)); ?>" class="d-inline">
                                                            <?php echo csrf_field(); ?>
                                                            <button type="submit" class="btn btn-sm btn-info" title="موافقة" onclick="return confirm('هل أنت متأكد من الموافقة على هذا الربح؟')">
                                                                <i class="fas fa-check"></i>
                                                            </button>
                                                        </form>
                                                        <button type="button" class="btn btn-sm btn-danger" title="إلغاء" onclick="cancelEarning(<?php echo e($earning->id); ?>)">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    <?php elseif($earning->status == 'approved'): ?>
                                                        <form method="POST" action="<?php echo e(route('admin.points.earnings.pay', $earning->id)); ?>" class="d-inline">
                                                            <?php echo csrf_field(); ?>
                                                            <button type="submit" class="btn btn-sm btn-success" title="دفع للمحفظة" onclick="return confirm('هل أنت متأكد من دفع هذا الربح للمحفظة؟')">
                                                                <i class="fas fa-wallet"></i>
                                                            </button>
                                                        </form>
                                                    <?php endif; ?>
                                                    <button type="button" class="btn btn-sm btn-secondary" title="التفاصيل" onclick="showEarningDetails(<?php echo e($earning->id); ?>)">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <div class="mt-3">
                            <?php echo e($earnings->links()); ?>

                        </div>
                    <?php else: ?>
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-dollar-sign fa-3x mb-3"></i>
                            <p>لا توجد أرباح</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal للتفاصيل -->
<div class="modal fade" id="earningDetailsModal" tabindex="-1" role="dialog" aria-labelledby="earningDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="earningDetailsModalLabel">
                    <i class="fas fa-info-circle"></i> تفاصيل الربح
                </h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="earningDetailsContent">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">جاري التحميل...</span>
                    </div>
                    <p class="mt-2 text-muted">جاري تحميل التفاصيل...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
    // بيانات الرسوم البيانية
    const earningsStatusData = {
        labels: ['معلق', 'موافق', 'مدفوع', 'ملغي'],
        data: [
            <?php echo e($stats['pending_earnings']); ?>,
            <?php echo e($stats['approved_earnings']); ?>,
            <?php echo e($stats['paid_earnings']); ?>,
            <?php echo e($stats['cancelled_earnings']); ?>

        ],
        colors: ['#ffc107', '#17a2b8', '#28a745', '#dc3545']
    };

    // رسم بياني لتوزيع الأرباح حسب الحالة
    const statusCtx = document.getElementById('earningsStatusChart');
    if (statusCtx) {
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: earningsStatusData.labels,
                datasets: [{
                    data: earningsStatusData.data,
                    backgroundColor: earningsStatusData.colors,
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                        rtl: true
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.parsed.toFixed(2) + ' دينار';
                            }
                        }
                    }
                }
            }
        });
    }

    // رسم بياني لتوزيع الأرباح حسب نوع الطلب
    const typeCtx = document.getElementById('earningsTypeChart');
    if (typeCtx) {
        const typeData = {
            food: <?php echo e($stats['earnings_by_type']['food']); ?>,
            gas: <?php echo e($stats['earnings_by_type']['gas']); ?>,
            taxi: <?php echo e($stats['earnings_by_type']['taxi']); ?>

        };

        new Chart(typeCtx, {
            type: 'bar',
            data: {
                labels: ['طعام', 'غاز', 'تاكسي'],
                datasets: [{
                    label: 'الأرباح (دينار)',
                    data: [typeData.food, typeData.gas, typeData.taxi],
                    backgroundColor: ['#ffc107', '#dc3545', '#007bff'],
                    borderColor: ['#ff9800', '#c82333', '#0056b3'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return value.toFixed(2) + ' دينار';
                            }
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'الأرباح: ' + context.parsed.y.toFixed(2) + ' دينار';
                            }
                        }
                    }
                }
            }
        });
    }

    // تصدير البيانات إلى Excel
    function exportEarnings() {
        const params = new URLSearchParams(window.location.search);
        params.append('export', 'excel');
        window.location.href = '<?php echo e(route("admin.points.earnings")); ?>?' + params.toString();
    }

    // إلغاء ربح
    function cancelEarning(id) {
        Swal.fire({
            title: 'هل أنت متأكد؟',
            text: 'سيتم إلغاء هذا الربح',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'نعم، إلغاء',
            cancelButtonText: 'إلغاء',
            input: 'textarea',
            inputPlaceholder: 'ملاحظات (اختياري)',
            inputAttributes: {
                'aria-label': 'ملاحظات'
            },
            showLoaderOnConfirm: true,
            preConfirm: (notes) => {
                return fetch(`<?php echo e(url('/admin/points/earnings')); ?>/${id}/cancel`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ notes: notes || null })
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message || 'حدث خطأ أثناء الإلغاء');
                    }
                    return data;
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire('تم!', 'تم إلغاء الربح بنجاح', 'success').then(() => {
                    location.reload();
                });
            }
        });
    }

    // عرض تفاصيل الربح
    function showEarningDetails(id) {
        const modal = new bootstrap.Modal(document.getElementById('earningDetailsModal'));
        modal.show();
        
        // إعادة تعيين المحتوى
        document.getElementById('earningDetailsContent').innerHTML = `
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">جاري التحميل...</span>
                </div>
                <p class="mt-2 text-muted">جاري تحميل التفاصيل...</p>
            </div>
        `;
        
        fetch(`<?php echo e(url('/admin/points/earnings')); ?>/${id}/details`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('earningDetailsContent').innerHTML = data.html;
                } else {
                    document.getElementById('earningDetailsContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> ${data.message || 'حدث خطأ أثناء تحميل التفاصيل'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                document.getElementById('earningDetailsContent').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i> حدث خطأ أثناء تحميل التفاصيل
                    </div>
                `;
            });
    }
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\wamp64\www\taxi_app\resources\views/admin/points/earnings.blade.php ENDPATH**/ ?>