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

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

// التحقق من وجود معرف المنخرط
if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'معرف المنخرط مطلوب']);
    exit;
}

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

// الحصول على سجل الاشتراكات الشهرية
$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 
          LIMIT 12";
$monthlyPayments = fetchAll($query, [':member_id' => $memberId]);

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

// إعداد مصفوفة النتائج
$result = [
    'success' => true,
    'payments' => []
];

foreach ($monthlyPayments as $payment) {
    $statusLabels = [
        'paid' => '<span class="badge bg-success">مدفوع</span>',
        'partial' => '<span class="badge bg-warning">مدفوع جزئيا</span>',
        'unpaid' => '<span class="badge bg-danger">غير مدفوع</span>'
    ];
    
    $paymentMethods = [
        'cash' => 'نقدا',
        'bank_transfer' => 'تحويل بنكي',
        'check' => 'شيك'
    ];
    
    $result['payments'][] = [
        'id' => $payment['id'],
        'payment_month' => formatMonthYear($payment['payment_month']),
        'payment_status_raw' => $payment['payment_status'],
        'payment_status' => $statusLabels[$payment['payment_status']] ?? $payment['payment_status'],
        'payment_date' => $payment['payment_date'] ? date('d/m/Y', strtotime($payment['payment_date'])) : '-',
        'amount_paid' => number_format($payment['amount_paid'], 2) . ' درهم',
        'payment_method' => $paymentMethods[$payment['payment_method']] ?? '-',
        'notes' => $payment['notes'] ?: '-',
        'created_by' => $payment['created_by_name'] ?: '-',
        'created_at' => date('d/m/Y', strtotime($payment['created_at']))
    ];
}

// إرجاع النتائج بصيغة JSON
header('Content-Type: application/json');
echo json_encode($result);
?>
