<?php
require_once '../config.php';

// التحقق من تسجيل الدخول
requireLogin();

// التحقق من وجود معرف المنخرط
if (!isset($_GET['id']) || empty($_GET['id'])) {
    setAlert('danger', 'معرف المنخرط مطلوب');
    header('Location: ' . SITE_URL . '/members/index.php');
    exit;
}

$memberId = (int)$_GET['id'];

// الحصول على بيانات المنخرط
$query = "SELECT m.*, c.name as category_name 
          FROM members m 
          LEFT JOIN categories c ON m.category_id = c.id 
          WHERE m.id = :id";
$member = fetchOne($query, [':id' => $memberId]);

if (!$member) {
    setAlert('danger', 'المنخرط غير موجود');
    header('Location: ' . SITE_URL . '/members/index.php');
    exit;
}

// الحصول على سجل الاشتراكات الشهرية
$query = "SELECT mp.*, u.full_name as created_by_name 
          FROM monthly_payments mp 
          LEFT JOIN users u ON mp.created_by = u.id 
          WHERE mp.member_id = :member_id 
          ORDER BY mp.payment_month DESC";
$monthlyPayments = fetchAll($query, [':member_id' => $memberId]);

// تنسيق التاريخ للعرض
function formatMonthYear($date) {
    $timestamp = strtotime($date);
    return date('m/Y', $timestamp);
}

// عنوان الصفحة
$pageTitle = 'سجل الاشتراكات الشهرية - ' . $member['first_name'] . ' ' . $member['last_name'];

// تضمين ملف الهيدر
include '../includes/header.php';
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0"><i class="fas fa-money-bill-wave me-2"></i> سجل الاشتراكات الشهرية</h1>
        <div>
            <a href="<?php echo SITE_URL; ?>/members/view.php?id=<?php echo $member['id']; ?>" class="btn btn-secondary me-2">
                <i class="fas fa-arrow-right"></i> العودة إلى بيانات المنخرط
            </a>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPaymentModal">
                <i class="fas fa-plus"></i> تسجيل دفعة جديدة
            </button>
        </div>
    </div>

    <?php displayAlert(); ?>

    <div class="card mb-4">
        <div class="card-header bg-white">
            <div class="d-flex align-items-center">
                <?php
                $photoPath = !empty($member['photo']) 
                    ? SITE_URL . '/uploads/members/' . $member['photo'] 
                    : SITE_URL . '/assets/img/default-user.png';
                ?>
                <img src="<?php echo $photoPath; ?>" alt="صورة المنخرط" class="rounded-circle me-3" style="width: 50px; height: 50px; object-fit: cover;">
                <div>
                    <h5 class="mb-0"><?php echo $member['first_name'] . ' ' . $member['last_name']; ?></h5>
                    <p class="text-muted mb-0"><?php echo $member['category_name']; ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-white">
            <h5 class="mb-0"><i class="fas fa-history me-2"></i> سجل الاشتراكات الشهرية</h5>
        </div>
        <div class="card-body">
            <?php if (empty($monthlyPayments)): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i> لا توجد سجلات للاشتراكات الشهرية لهذا المنخرط.
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>شهر الاشتراك</th>
                                <th>حالة الدفع</th>
                                <th>تاريخ الدفع</th>
                                <th>المبلغ المدفوع</th>
                                <th>طريقة الدفع</th>
                                <th>ملاحظات</th>
                                <th>المسجل</th>
                                <th>تاريخ التسجيل</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($monthlyPayments as $payment): ?>
                                <tr>
                                    <td><?php echo formatMonthYear($payment['payment_month']); ?></td>
                                    <td>
                                        <?php if ($payment['payment_status'] == 'paid'): ?>
                                            <span class="badge bg-success">مدفوع</span>
                                        <?php elseif ($payment['payment_status'] == 'partial'): ?>
                                            <span class="badge bg-warning">مدفوع جزئيا</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">غير مدفوع</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $payment['payment_date'] ? date('d/m/Y', strtotime($payment['payment_date'])) : '-'; ?></td>
                                    <td><?php echo number_format($payment['amount_paid'], 2) . ' درهم'; ?></td>
                                    <td><?php echo getPaymentMethodName($payment['payment_method']); ?></td>
                                    <td><?php echo htmlspecialchars($payment['notes'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($payment['created_by_name'] ?? '-'); ?></td>
                                    <td><?php echo date('d/m/Y', strtotime($payment['created_at'])); ?></td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-info edit-payment" 
                                            data-id="<?php echo $payment['id']; ?>"
                                            data-payment-month="<?php echo $payment['payment_month']; ?>"
                                            data-payment-status="<?php echo $payment['payment_status']; ?>"
                                            data-payment-date="<?php echo $payment['payment_date']; ?>"
                                            data-amount-paid="<?php echo $payment['amount_paid']; ?>"
                                            data-payment-method="<?php echo $payment['payment_method']; ?>"
                                            data-notes="<?php echo htmlspecialchars($payment['notes'] ?? ''); ?>">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-danger delete-payment" data-id="<?php echo $payment['id']; ?>">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal إضافة دفعة جديدة -->
<div class="modal fade" id="addPaymentModal" tabindex="-1" aria-labelledby="addPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addPaymentModalLabel">تسجيل دفعة اشتراك شهري جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="../monthly_payments/save_payment.php" method="post" class="needs-validation" novalidate>
                <input type="hidden" name="member_id" value="<?php echo $member['id']; ?>">
                <input type="hidden" name="redirect_url" value="<?php echo SITE_URL; ?>/monthly_payments/member_payments.php?id=<?php echo $member['id']; ?>">
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="payment_month" class="form-label">شهر الاشتراك <span class="text-danger">*</span></label>
                            <input type="month" class="form-control" id="payment_month" name="payment_month" 
                                   value="<?php echo date('Y-m'); ?>" required>
                            <div class="invalid-feedback">يرجى تحديد شهر الاشتراك</div>
                        </div>
                        <div class="col-md-6">
                            <label for="payment_status" class="form-label">حالة الدفع <span class="text-danger">*</span></label>
                            <select class="form-select" id="payment_status" name="payment_status" required>
                                <option value="paid">مدفوع</option>
                                <option value="partial">مدفوع جزئيا</option>
                                <option value="unpaid">غير مدفوع</option>
                            </select>
                            <div class="invalid-feedback">يرجى تحديد حالة الدفع</div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6 payment-date-container">
                            <label for="payment_date" class="form-label">تاريخ الدفع</label>
                            <input type="date" class="form-control" id="payment_date" name="payment_date" 
                                   value="<?php echo date('Y-m-d'); ?>">
                            <div class="invalid-feedback">يرجى تحديد تاريخ الدفع</div>
                        </div>
                        <div class="col-md-6 amount-container">
                            <label for="amount_paid" class="form-label">المبلغ المدفوع</label>
                            <input type="number" class="form-control" id="amount_paid" name="amount_paid" step="0.01" value="0">
                            <div class="invalid-feedback">يرجى إدخال المبلغ المدفوع</div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6 payment-method-container">
                            <label for="payment_method" class="form-label">طريقة الدفع</label>
                            <select class="form-select" id="payment_method" name="payment_method">
                                <option value="">اختر طريقة الدفع</option>
                                <option value="cash">نقدا</option>
                                <option value="bank_transfer">تحويل بنكي</option>
                                <option value="check">شيك</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="notes" class="form-label">ملاحظات</label>
                            <textarea class="form-control" id="notes" name="notes" rows="1"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal تعديل دفعة -->
<div class="modal fade" id="editPaymentModal" tabindex="-1" aria-labelledby="editPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editPaymentModalLabel">تعديل دفعة اشتراك شهري</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="../monthly_payments/update_payment.php" method="post" class="needs-validation" novalidate>
                <input type="hidden" id="edit_payment_id" name="payment_id">
                <input type="hidden" name="member_id" value="<?php echo $member['id']; ?>">
                <input type="hidden" name="redirect_url" value="<?php echo SITE_URL; ?>/monthly_payments/member_payments.php?id=<?php echo $member['id']; ?>">
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="edit_payment_month" class="form-label">شهر الاشتراك <span class="text-danger">*</span></label>
                            <input type="month" class="form-control" id="edit_payment_month" name="payment_month" required>
                            <div class="invalid-feedback">يرجى تحديد شهر الاشتراك</div>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_payment_status" class="form-label">حالة الدفع <span class="text-danger">*</span></label>
                            <select class="form-select" id="edit_payment_status" name="payment_status" required>
                                <option value="paid">مدفوع</option>
                                <option value="partial">مدفوع جزئيا</option>
                                <option value="unpaid">غير مدفوع</option>
                            </select>
                            <div class="invalid-feedback">يرجى تحديد حالة الدفع</div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6 edit-payment-date-container">
                            <label for="edit_payment_date" class="form-label">تاريخ الدفع</label>
                            <input type="date" class="form-control" id="edit_payment_date" name="payment_date">
                            <div class="invalid-feedback">يرجى تحديد تاريخ الدفع</div>
                        </div>
                        <div class="col-md-6 edit-amount-container">
                            <label for="edit_amount_paid" class="form-label">المبلغ المدفوع</label>
                            <input type="number" class="form-control" id="edit_amount_paid" name="amount_paid" step="0.01">
                            <div class="invalid-feedback">يرجى إدخال المبلغ المدفوع</div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6 edit-payment-method-container">
                            <label for="edit_payment_method" class="form-label">طريقة الدفع</label>
                            <select class="form-select" id="edit_payment_method" name="payment_method">
                                <option value="">اختر طريقة الدفع</option>
                                <option value="cash">نقدا</option>
                                <option value="bank_transfer">تحويل بنكي</option>
                                <option value="check">شيك</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_notes" class="form-label">ملاحظات</label>
                            <textarea class="form-control" id="edit_notes" name="notes" rows="1"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal حذف دفعة -->
<div class="modal fade" id="deletePaymentModal" tabindex="-1" aria-labelledby="deletePaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deletePaymentModalLabel">تأكيد الحذف</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>هل أنت متأكد من حذف هذه الدفعة؟ لا يمكن التراجع عن هذا الإجراء.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <form action="../monthly_payments/delete_payment.php" method="post">
                    <input type="hidden" id="delete_payment_id" name="payment_id">
                    <input type="hidden" name="redirect_url" value="<?php echo SITE_URL; ?>/monthly_payments/member_payments.php?id=<?php echo $member['id']; ?>">
                    <button type="submit" class="btn btn-danger">حذف</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // تحديث حقول النموذج بناءً على حالة الدفع
    function updateFormFields(status, prefix = '') {
        const paymentDateContainer = document.querySelector(prefix ? `.${prefix}-payment-date-container` : '.payment-date-container');
        const amountContainer = document.querySelector(prefix ? `.${prefix}-amount-container` : '.amount-container');
        const paymentMethodContainer = document.querySelector(prefix ? `.${prefix}-payment-method-container` : '.payment-method-container');
        const paymentDateInput = document.getElementById(`${prefix ? prefix + '_' : ''}payment_date`);
        const amountPaidInput = document.getElementById(`${prefix ? prefix + '_' : ''}amount_paid`);
        const paymentMethodInput = document.getElementById(`${prefix ? prefix + '_' : ''}payment_method`);
        
        if (status === 'paid' || status === 'partial') {
            paymentDateContainer.style.display = 'block';
            amountContainer.style.display = 'block';
            paymentMethodContainer.style.display = 'block';
            
            if (status === 'paid') {
                paymentDateInput.setAttribute('required', '');
                amountPaidInput.setAttribute('required', '');
                paymentMethodInput.setAttribute('required', '');
            } else {
                paymentDateInput.setAttribute('required', '');
                amountPaidInput.setAttribute('required', '');
            }
        } else {
            paymentDateContainer.style.display = 'none';
            amountContainer.style.display = 'none';
            paymentMethodContainer.style.display = 'none';
            
            paymentDateInput.removeAttribute('required');
            amountPaidInput.removeAttribute('required');
            paymentMethodInput.removeAttribute('required');
        }
    }
    
    // تحديث الحقول عند تغيير حالة الدفع في نموذج الإضافة
    const paymentStatusSelect = document.getElementById('payment_status');
    if (paymentStatusSelect) {
        paymentStatusSelect.addEventListener('change', function() {
            updateFormFields(this.value);
        });
        
        // تحديث الحقول عند تحميل الصفحة
        updateFormFields(paymentStatusSelect.value);
    }
    
    // تحديث الحقول عند تغيير حالة الدفع في نموذج التعديل
    const editPaymentStatusSelect = document.getElementById('edit_payment_status');
    if (editPaymentStatusSelect) {
        editPaymentStatusSelect.addEventListener('change', function() {
            updateFormFields(this.value, 'edit');
        });
    }
    
    // تعبئة بيانات نموذج التعديل
    const editButtons = document.querySelectorAll('.edit-payment');
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const paymentMonth = this.getAttribute('data-payment-month');
            const paymentStatus = this.getAttribute('data-payment-status');
            const paymentDate = this.getAttribute('data-payment-date');
            const amountPaid = this.getAttribute('data-amount-paid');
            const paymentMethod = this.getAttribute('data-payment-method');
            const notes = this.getAttribute('data-notes');
            
            document.getElementById('edit_payment_id').value = id;
            document.getElementById('edit_payment_month').value = paymentMonth.substring(0, 7); // YYYY-MM
            document.getElementById('edit_payment_status').value = paymentStatus;
            document.getElementById('edit_payment_date').value = paymentDate || '';
            document.getElementById('edit_amount_paid').value = amountPaid || '0';
            document.getElementById('edit_payment_method').value = paymentMethod || '';
            document.getElementById('edit_notes').value = notes || '';
            
            // تحديث الحقول بناءً على حالة الدفع
            updateFormFields(paymentStatus, 'edit');
            
            // فتح النموذج
            const editModal = new bootstrap.Modal(document.getElementById('editPaymentModal'));
            editModal.show();
        });
    });
    
    // تعبئة بيانات نموذج الحذف
    const deleteButtons = document.querySelectorAll('.delete-payment');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            document.getElementById('delete_payment_id').value = id;
            
            // فتح النموذج
            const deleteModal = new bootstrap.Modal(document.getElementById('deletePaymentModal'));
            deleteModal.show();
        });
    });
    
    // تفعيل التحقق من صحة النماذج
    const forms = document.querySelectorAll('.needs-validation');
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
});

// دالة للحصول على اسم طريقة الدفع
function getPaymentMethodName(method) {
    switch(method) {
        case 'cash':
            return 'نقدا';
        case 'bank_transfer':
            return 'تحويل بنكي';
        case 'check':
            return 'شيك';
        default:
            return '-';
    }
}
</script>

<?php
// تضمين ملف الفوتر
include '../includes/footer.php';
?>
