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

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

// معالجة البحث
$searchTerm = isset($_GET['search']) ? sanitizeInput($_GET['search']) : '';
$categoryFilter = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$statusFilter = isset($_GET['status']) ? sanitizeInput($_GET['status']) : 'all';
$startDate = isset($_GET['start_date']) ? sanitizeInput($_GET['start_date']) : '';
$endDate = isset($_GET['end_date']) ? sanitizeInput($_GET['end_date']) : '';

// استعلام قائمة الاشتراكات
$query = "SELECT s.*, m.first_name, m.last_name, c.name as category_name, u.full_name as created_by_name 
          FROM subscriptions s 
          JOIN members m ON s.member_id = m.id 
          LEFT JOIN categories c ON m.category_id = c.id 
          LEFT JOIN users u ON s.created_by = u.id 
          WHERE 1=1";
$params = [];

// إضافة شروط البحث
if (!empty($searchTerm)) {
    $query .= " AND (m.first_name LIKE :search OR m.last_name LIKE :search)";
    $params[':search'] = "%$searchTerm%";
}

if ($categoryFilter > 0) {
    $query .= " AND m.category_id = :category_id";
    $params[':category_id'] = $categoryFilter;
}

if ($statusFilter === 'active') {
    $query .= " AND s.end_date >= CURRENT_DATE";
} elseif ($statusFilter === 'expired') {
    $query .= " AND s.end_date < CURRENT_DATE";
}

if (!empty($startDate)) {
    $query .= " AND s.start_date >= :start_date";
    $params[':start_date'] = $startDate;
}

if (!empty($endDate)) {
    $query .= " AND s.end_date <= :end_date";
    $params[':end_date'] = $endDate;
}

// ترتيب النتائج
$query .= " ORDER BY s.start_date DESC";

// تنفيذ الاستعلام
$subscriptions = fetchAll($query, $params);

// الحصول على قائمة الفئات للفلتر
$categories = fetchAll("SELECT id, name FROM categories ORDER BY name");

// حساب إجمالي المبالغ
$totalAmount = 0;
$totalInsurance = 0;
foreach ($subscriptions as $subscription) {
    $totalAmount += $subscription['amount_paid'];
    if ($subscription['is_insurance_paid']) {
        $totalInsurance += $subscription['insurance_amount'];
    }
}

// عنوان الصفحة
$pageTitle = 'إدارة الاشتراكات';

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

<style>
/* Styles pour l'impression */
@media print {
    /* Cacher les éléments qui ne doivent pas être imprimés */
    header, 
    .navbar,
    .sidebar,
    footer,
    .btn,
    form,
    .d-flex.justify-content-between.align-items-center,
    .card-body form,
    #exportBtn,
    #printBtn {
        display: none !important;
    }
    
    /* Assurer que le tableau occupe toute la largeur disponible */
    .table-responsive {
        overflow: visible !important;
    }
    
    /* Styles pour le tableau */
    #subscriptionsTable {
        width: 100% !important;
        page-break-inside: auto !important;
    }
    
    /* Éviter les sauts de page au milieu des lignes */
    #subscriptionsTable tr {
        page-break-inside: avoid !important;
    }
    
    /* Afficher le titre de la page */
    .card-body {
        border: none !important;
        box-shadow: none !important;
    }
    
    /* Supprimer les marges inutiles */
    body {
        margin: 0 !important;
        padding: 0 !important;
    }
    
    /* Assurer que seul le contenu principal est visible */
    .container-fluid, .content-wrapper {
        padding: 0 !important;
        margin: 0 !important;
    }
}

/* Styles pour le reçu */
.receipt-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: Arial, sans-serif;
}

.receipt-header {
    text-align: center;
    margin-bottom: 20px;
    border-bottom: 2px solid #007bff;
    padding-bottom: 10px;
}

.receipt-title {
    font-size: 24px;
    font-weight: bold;
    color: #007bff;
    margin-bottom: 5px;
}

.receipt-subtitle {
    font-size: 16px;
    color: #6c757d;
}

.receipt-body {
    margin-bottom: 20px;
}

.receipt-section {
    margin-bottom: 15px;
}

.receipt-section-title {
    font-weight: bold;
    border-bottom: 1px solid #dee2e6;
    padding-bottom: 5px;
    margin-bottom: 10px;
}

.receipt-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
}

.receipt-label {
    font-weight: bold;
    width: 40%;
}

.receipt-value {
    width: 60%;
    text-align: right;
}

.receipt-footer {
    margin-top: 30px;
    text-align: center;
    font-size: 14px;
    color: #6c757d;
    border-top: 1px solid #dee2e6;
    padding-top: 10px;
}

.receipt-notes {
    background-color: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
    margin-top: 15px;
}

/* Styles pour l'impression du reçu */
@media print {
    body * {
        visibility: hidden;
    }
    
    .modal-content, .modal-content * {
        visibility: visible;
    }
    
    .modal-content {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        box-shadow: none !important;
        border: none !important;
    }
    
    .modal-header .btn-close,
    .modal-footer .btn-secondary {
        display: none !important;
    }
}

/* Styles pour la fenêtre modale */
.modal {
    display: none;
    position: fixed;
    z-index: 1050;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.4);
}

.modal-dialog {
    margin: 30px auto;
    max-width: 800px;
}

.modal-content {
    position: relative;
    background-color: #fff;
    border: 1px solid rgba(0,0,0,.2);
    border-radius: .3rem;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}

.modal-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 1rem;
    border-bottom: 1px solid #dee2e6;
}

.modal-body {
    position: relative;
    flex: 1 1 auto;
    padding: 1rem;
}

.modal-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 1rem;
    border-top: 1px solid #dee2e6;
}
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0"><i class="fas fa-money-check-alt me-2"></i> إدارة الاشتراكات</h1>
    <div>
        <button type="button" class="btn btn-success me-2" id="exportBtn">
            <i class="fas fa-file-excel"></i> تصدير إلى Excel
        </button>
        <button type="button" class="btn btn-info me-2" id="printBtn">
            <i class="fas fa-print"></i> طباعة
        </button>
    </div>
</div>

<!-- فلاتر البحث -->
<div class="card mb-4">
    <div class="card-body">
        <form method="get" action="" class="row g-3">
            <div class="col-md-3">
                <label for="search" class="form-label">بحث</label>
                <input type="text" class="form-control" id="search" name="search" value="<?php echo $searchTerm; ?>" placeholder="اسم المنخرط...">
            </div>
            <div class="col-md-2">
                <label for="category" class="form-label">الفئة</label>
                <select class="form-select" id="category" name="category">
                    <option value="0">جميع الفئات</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?php echo $category['id']; ?>" <?php echo ($categoryFilter == $category['id']) ? 'selected' : ''; ?>>
                            <?php echo $category['name']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label for="status" class="form-label">الحالة</label>
                <select class="form-select" id="status" name="status">
                    <option value="all" <?php echo ($statusFilter === 'all') ? 'selected' : ''; ?>>الكل</option>
                    <option value="active" <?php echo ($statusFilter === 'active') ? 'selected' : ''; ?>>ساري</option>
                    <option value="expired" <?php echo ($statusFilter === 'expired') ? 'selected' : ''; ?>>منتهي</option>
                </select>
            </div>
            <div class="col-md-2">
                <label for="start_date" class="form-label">من تاريخ</label>
                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
            </div>
            <div class="col-md-2">
                <label for="end_date" class="form-label">إلى تاريخ</label>
                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
            </div>
            <div class="col-md-1 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-search"></i> بحث
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ملخص الاشتراكات -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <h5 class="card-title">عدد الاشتراكات</h5>
                <h2><?php echo count($subscriptions); ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card bg-success text-white">
            <div class="card-body">
                <h5 class="card-title">إجمالي مبالغ الاشتراكات</h5>
                <h2><?php echo number_format($totalAmount, 2); ?> درهم</h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card bg-info text-white">
            <div class="card-body">
                <h5 class="card-title">إجمالي مبالغ التأمين</h5>
                <h2><?php echo number_format($totalInsurance, 2); ?> درهم</h2>
            </div>
        </div>
    </div>
</div>

<!-- جدول الاشتراكات -->
<div class="card">
    <div class="card-body">
        <?php if (count($subscriptions) > 0): ?>
            <div class="table-responsive">
                <table class="table table-striped table-hover" id="subscriptionsTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>المنخرط</th>
                            <th>الفئة</th>
                            <th>تاريخ البداية</th>
                            <th>تاريخ النهاية</th>
                            <th>المبلغ المدفوع</th>
                            <th>التأمين</th>
                            <th>طريقة الدفع</th>
                            <th>رقم الإيصال</th>
                            <th>تاريخ الدفع</th>
                            <th>الحالة</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($subscriptions as $index => $subscription): ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td>
                                    <a href="<?php echo SITE_URL; ?>/members/view.php?id=<?php echo $subscription['member_id']; ?>">
                                        <?php echo $subscription['first_name'] . ' ' . $subscription['last_name']; ?>
                                    </a>
                                </td>
                                <td><?php echo $subscription['category_name']; ?></td>
                                <td><?php echo formatDate($subscription['start_date']); ?></td>
                                <td><?php echo formatDate($subscription['end_date']); ?></td>
                                <td><?php echo number_format($subscription['amount_paid'], 2); ?> درهم</td>
                                <td>
                                    <?php
                                    if ($subscription['is_insurance_paid']) {
                                        echo '<span class="badge bg-success">مدفوع (' . number_format($subscription['insurance_amount'], 2) . ' درهم)</span>';
                                    } else {
                                        echo '<span class="badge bg-danger">غير مدفوع</span>';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                    $paymentMethods = [
                                        'cash' => 'نقدا',
                                        'bank_transfer' => 'تحويل بنكي',
                                        'check' => 'شيك'
                                    ];
                                    echo $paymentMethods[$subscription['payment_method']] ?? $subscription['payment_method'];
                                    ?>
                                </td>
                                <td><?php echo $subscription['receipt_number']; ?></td>
                                <td><?php echo formatDate($subscription['payment_date']); ?></td>
                                <td>
                                    <?php
                                    $today = date('Y-m-d');
                                    if ($subscription['end_date'] >= $today) {
                                        echo '<span class="badge bg-success">ساري</span>';
                                    } else {
                                        echo '<span class="badge bg-danger">منتهي</span>';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="<?php echo SITE_URL; ?>/members/view.php?id=<?php echo $subscription['member_id']; ?>" class="btn btn-info" title="عرض المنخرط">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php if (hasPermission('admin')): ?>
                                        <button type="button" class="btn btn-primary show-receipt" title="عرض الإيصال" 
                                            data-id="<?php echo $subscription['id']; ?>"
                                            data-member="<?php echo htmlspecialchars($subscription['first_name'] . ' ' . $subscription['last_name']); ?>"
                                            data-category="<?php echo htmlspecialchars($subscription['category_name']); ?>"
                                            data-start-date="<?php echo formatDate($subscription['start_date']); ?>"
                                            data-end-date="<?php echo formatDate($subscription['end_date']); ?>"
                                            data-amount="<?php echo number_format($subscription['amount_paid'], 2); ?>"
                                            data-insurance="<?php echo $subscription['is_insurance_paid'] ? number_format($subscription['insurance_amount'], 2) : '0.00'; ?>"
                                            data-payment-method="<?php echo $paymentMethods[$subscription['payment_method']] ?? $subscription['payment_method']; ?>"
                                            data-receipt-number="<?php echo htmlspecialchars($subscription['receipt_number']); ?>"
                                            data-payment-date="<?php echo formatDate($subscription['payment_date']); ?>"
                                            data-notes="<?php echo htmlspecialchars($subscription['notes']); ?>"
                                            data-created-by="<?php echo htmlspecialchars($subscription['created_by_name']); ?>">
                                            <i class="fas fa-receipt"></i>
                                        </button>
                                        <a href="edit_subscription_form.php?id=<?php echo $subscription['id']; ?>" class="btn btn-warning" title="تعديل الاشتراك">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="delete_subscription.php?id=<?php echo $subscription['id']; ?>" class="btn btn-danger" title="حذف الاشتراك" onclick="return confirm('هل أنت متأكد من رغبتك في حذف اشتراك <?php echo htmlspecialchars($subscription['first_name'] . ' ' . $subscription['last_name']); ?>؟')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i> لا يوجد اشتراكات مطابقة لمعايير البحث.
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // تأكد من تحميل Bootstrap بشكل صحيح
    if (typeof bootstrap === 'undefined') {
        console.error('Bootstrap غير محمل. يرجى التحقق من تضمين مكتبة Bootstrap.');
        return;
    }


    // زر الطباعة
    const printBtn = document.getElementById('printBtn');
    if (printBtn) {
        printBtn.addEventListener('click', function() {
            window.print();
        });
    }
    
    // زر التصدير إلى Excel
    const exportBtn = document.getElementById('exportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', function() {
            // تحويل الجدول إلى Excel
            const table = document.getElementById('subscriptionsTable');
            if (!table) return;
            
            // إنشاء ورقة عمل Excel
            let csv = [];
            const rows = table.querySelectorAll('tr');
            
            for (let i = 0; i < rows.length; i++) {
                let row = [], cols = rows[i].querySelectorAll('td, th');
                
                for (let j = 0; j < cols.length; j++) {
                    // استخراج النص فقط (بدون HTML)
                    let cellText = cols[j].innerText.trim();
                    // تنظيف النص
                    cellText = cellText.replace(/"/g, '""');
                    row.push('"' + cellText + '"');
                }
                
                csv.push(row.join(','));
            }
            
            // تحميل ملف CSV
            const csvContent = csv.join('\n');
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            
            link.setAttribute('href', url);
            link.setAttribute('download', 'subscriptions_' + new Date().toISOString().slice(0, 10) + '.csv');
            link.style.visibility = 'hidden';
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
    }
    
    // زر عرض الإيصال
    const showReceiptBtns = document.querySelectorAll('.show-receipt');
    if (showReceiptBtns) {
        showReceiptBtns.forEach(function(btn) {
            btn.addEventListener('click', function() {
                // الحصول على البيانات من الزر
                const id = btn.getAttribute('data-id');
                const member = btn.getAttribute('data-member');
                const category = btn.getAttribute('data-category');
                const startDate = btn.getAttribute('data-start-date');
                const endDate = btn.getAttribute('data-end-date');
                const amount = btn.getAttribute('data-amount');
                const insurance = btn.getAttribute('data-insurance');
                const paymentMethod = btn.getAttribute('data-payment-method');
                const receiptNumber = btn.getAttribute('data-receipt-number');
                const paymentDate = btn.getAttribute('data-payment-date');
                const notes = btn.getAttribute('data-notes');
                const createdBy = btn.getAttribute('data-created-by');
                
                // إنشاء محتوى الإيصال
                const receiptContent = `
                    <div class="receipt-container">
                        <div class="receipt-header">
                            <h2 class="receipt-title">إيصال الدفع</h2>
                            <p class="receipt-subtitle">المنخرط: ${member}</p>
                        </div>
                        <div class="receipt-body">
                            <div class="receipt-section">
                                <h3 class="receipt-section-title">معلومات الإيصال</h3>
                                <div class="receipt-row">
                                    <span class="receipt-label">رقم الإيصال:</span>
                                    <span class="receipt-value">${receiptNumber}</span>
                                </div>
                                <div class="receipt-row">
                                    <span class="receipt-label">تاريخ الدفع:</span>
                                    <span class="receipt-value">${paymentDate}</span>
                                </div>
                            </div>
                            <div class="receipt-section">
                                <h3 class="receipt-section-title">فترة الاشتراك</h3>
                                <div class="receipt-row">
                                    <span class="receipt-label">الفئة:</span>
                                    <span class="receipt-value">${category}</span>
                                </div>
                                <div class="receipt-row">
                                    <span class="receipt-label">تاريخ بداية الاشتراك:</span>
                                    <span class="receipt-value">${startDate}</span>
                                </div>
                                <div class="receipt-row">
                                    <span class="receipt-label">تاريخ نهاية الاشتراك:</span>
                                    <span class="receipt-value">${endDate}</span>
                                </div>
                            </div>
                            <div class="receipt-section">
                                <h3 class="receipt-section-title">معلومات الدفع</h3>
                                <div class="receipt-row">
                                    <span class="receipt-label">المبلغ المدفوع:</span>
                                    <span class="receipt-value">${amount} درهم</span>
                                </div>
                                <div class="receipt-row">
                                    <span class="receipt-label">التأمين:</span>
                                    <span class="receipt-value">${insurance} درهم</span>
                                </div>
                                <div class="receipt-row">
                                    <span class="receipt-label">طريقة الدفع:</span>
                                    <span class="receipt-value">${paymentMethod}</span>
                                </div>
                            </div>
                            <div class="receipt-section">
                                <h3 class="receipt-section-title">ملاحظات</h3>
                                <p class="receipt-notes">${notes}</p>
                            </div>
                        </div>
                        <div class="receipt-footer">
                            تم إنشاء الإيصال بواسطة: ${createdBy}
                        </div>
                    </div>
                `;
                
                // عرض الإيصال في نافذة محددة
                const modal = document.getElementById('receiptModal');
                if (modal) {
                    modal.querySelector('.modal-body').innerHTML = receiptContent;
                    modal.style.display = 'block';
                }
            });
        });
    }
    
    // زر إغلاق نافذة الإيصال
    const closeModalBtn = document.getElementById('closeModalBtn');
    if (closeModalBtn) {
        closeModalBtn.addEventListener('click', function() {
            const modal = document.getElementById('receiptModal');
            if (modal) {
                modal.style.display = 'none';
            }
        });
    }
    
    // زر إغلاق الثاني
    const closeModalBtn2 = document.getElementById('closeModalBtn2');
    if (closeModalBtn2) {
        closeModalBtn2.addEventListener('click', function() {
            const modal = document.getElementById('receiptModal');
            if (modal) {
                modal.style.display = 'none';
            }
        });
    }
    
    // زر طباعة الإيصال
    const printReceiptBtn = document.getElementById('printReceiptBtn');
    if (printReceiptBtn) {
        printReceiptBtn.addEventListener('click', function() {
            // إعداد نافذة الطباعة
            const printContents = document.querySelector('.receipt-container').innerHTML;
            const originalContents = document.body.innerHTML;
            
            // إنشاء صفحة طباعة مخصصة
            const printPage = `
                <html>
                <head>
                    <title>إيصال الدفع</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            direction: rtl;
                        }
                        .receipt-container {
                            max-width: 800px;
                            margin: 0 auto;
                            padding: 20px;
                        }
                        .receipt-header {
                            text-align: center;
                            margin-bottom: 20px;
                            border-bottom: 2px solid #007bff;
                            padding-bottom: 10px;
                        }
                        .receipt-title {
                            font-size: 24px;
                            font-weight: bold;
                            color: #007bff;
                            margin-bottom: 5px;
                        }
                        .receipt-subtitle {
                            font-size: 16px;
                            color: #6c757d;
                        }
                        .receipt-body {
                            margin-bottom: 20px;
                        }
                        .receipt-section {
                            margin-bottom: 15px;
                        }
                        .receipt-section-title {
                            font-weight: bold;
                            border-bottom: 1px solid #dee2e6;
                            padding-bottom: 5px;
                            margin-bottom: 10px;
                        }
                        .receipt-row {
                            display: flex;
                            justify-content: space-between;
                            margin-bottom: 8px;
                        }
                        .receipt-label {
                            font-weight: bold;
                            width: 40%;
                        }
                        .receipt-value {
                            width: 60%;
                            text-align: right;
                        }
                        .receipt-footer {
                            margin-top: 30px;
                            text-align: center;
                            font-size: 14px;
                            color: #6c757d;
                            border-top: 1px solid #dee2e6;
                            padding-top: 10px;
                        }
                        .receipt-notes {
                            background-color: #f8f9fa;
                            padding: 10px;
                            border-radius: 4px;
                            margin-top: 15px;
                        }
                        @media print {
                            @page {
                                size: A4;
                                margin: 1cm;
                            }
                            body {
                                margin: 0;
                                padding: 0;
                                color: #000;
                            }
                            .receipt-title {
                                color: #000;
                            }
                        }
                    </style>
                </head>
                <body>
                    <div class="receipt-container">
                        ${printContents}
                    </div>
                    <div class="receipt-footer" style="text-align: center; margin-top: 30px;">
                        <p>تم إصدار هذا الإيصال بتاريخ: ${new Date().toLocaleDateString('ar-MA')}</p>
                    </div>
                </body>
                </html>
            `;
            
            // فتح نافذة جديدة للطباعة
            const printWindow = window.open('', '_blank');
            printWindow.document.open();
            printWindow.document.write(printPage);
            printWindow.document.close();
            
            // طباعة المحتوى
            printWindow.onload = function() {
                printWindow.print();
                printWindow.onafterprint = function() {
                    printWindow.close();
                };
            };
        });
    }
});
</script>



<!-- نافذة الإيصال -->
<div id="receiptModal" class="modal" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">إيصال الدفع</h5>
                <button type="button" class="btn-close" id="closeModalBtn"></button>
            </div>
            <div class="modal-body"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="closeModalBtn2">إغلاق</button>
                <button type="button" class="btn btn-primary" id="printReceiptBtn">
                    <i class="fas fa-print"></i> طباعة الإيصال
                </button>
            </div>
        </div>
    </div>
</div>

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