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

// Vérifier si l'utilisateur est connecté et a les permissions nécessaires
checkUserLogin();
if (!hasPermission('admin')) {
    setFlashMessage('error', 'ليس لديك صلاحية للوصول إلى هذه الصفحة');
    header('Location: ' . SITE_URL . '/dashboard.php');
    exit;
}

// Vérifier si le formulaire a été soumis
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Récupérer et valider les données du formulaire
    $subscriptionId = filter_input(INPUT_POST, 'subscription_id', FILTER_VALIDATE_INT);
    $memberId = filter_input(INPUT_POST, 'member_id', FILTER_VALIDATE_INT);
    $startDate = filter_input(INPUT_POST, 'start_date', FILTER_SANITIZE_STRING);
    $endDate = filter_input(INPUT_POST, 'end_date', FILTER_SANITIZE_STRING);
    $amountPaid = filter_input(INPUT_POST, 'amount_paid', FILTER_VALIDATE_FLOAT);
    $paymentMethod = filter_input(INPUT_POST, 'payment_method', FILTER_SANITIZE_STRING);
    $paymentDate = filter_input(INPUT_POST, 'payment_date', FILTER_SANITIZE_STRING);
    $receiptNumber = filter_input(INPUT_POST, 'receipt_number', FILTER_SANITIZE_STRING);
    $isInsurancePaid = isset($_POST['is_insurance_paid']) ? 1 : 0;
    $insuranceAmount = filter_input(INPUT_POST, 'insurance_amount', FILTER_VALIDATE_FLOAT);
    $notes = filter_input(INPUT_POST, 'notes', FILTER_SANITIZE_STRING);
    
    // Valider les données requises
    if (!$subscriptionId || !$memberId || !$startDate || !$endDate || !$amountPaid || !$paymentMethod || !$paymentDate) {
        setFlashMessage('error', 'يرجى ملء جميع الحقول المطلوبة');
        header('Location: ' . SITE_URL . '/members/subscriptions.php');
        exit;
    }
    
    // Vérifier que la date de fin est postérieure à la date de début
    if (strtotime($endDate) <= strtotime($startDate)) {
        setFlashMessage('error', 'يجب أن يكون تاريخ النهاية بعد تاريخ البداية');
        header('Location: ' . SITE_URL . '/members/subscriptions.php');
        exit;
    }
    
    try {
        $db = getDB();
        
        // Mettre à jour l'abonnement dans la base de données
        $query = "UPDATE subscriptions SET 
                    start_date = :start_date,
                    end_date = :end_date,
                    amount_paid = :amount_paid,
                    payment_method = :payment_method,
                    payment_date = :payment_date,
                    receipt_number = :receipt_number,
                    is_insurance_paid = :is_insurance_paid,
                    insurance_amount = :insurance_amount,
                    notes = :notes,
                    updated_at = NOW(),
                    updated_by = :updated_by
                  WHERE id = :subscription_id";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':subscription_id', $subscriptionId, PDO::PARAM_INT);
        $stmt->bindParam(':start_date', $startDate);
        $stmt->bindParam(':end_date', $endDate);
        $stmt->bindParam(':amount_paid', $amountPaid);
        $stmt->bindParam(':payment_method', $paymentMethod);
        $stmt->bindParam(':payment_date', $paymentDate);
        $stmt->bindParam(':receipt_number', $receiptNumber);
        $stmt->bindParam(':is_insurance_paid', $isInsurancePaid, PDO::PARAM_INT);
        $stmt->bindParam(':insurance_amount', $insuranceAmount);
        $stmt->bindParam(':notes', $notes);
        $stmt->bindParam(':updated_by', $_SESSION['user_id'], PDO::PARAM_INT);
        
        if ($stmt->execute()) {
            // Mettre à jour le statut du membre si nécessaire
            updateMemberStatus($memberId);
            
            setFlashMessage('success', 'تم تحديث الاشتراك بنجاح');
        } else {
            setFlashMessage('error', 'حدث خطأ أثناء تحديث الاشتراك');
        }
        
    } catch (PDOException $e) {
        setFlashMessage('error', 'خطأ في قاعدة البيانات: ' . $e->getMessage());
    }
    
    // Rediriger vers la page des abonnements
    header('Location: ' . SITE_URL . '/members/subscriptions.php');
    exit;
} else {
    // Si la page est accédée directement sans soumission de formulaire, rediriger vers la page des abonnements
    header('Location: ' . SITE_URL . '/members/subscriptions.php');
    exit;
}

/**
 * Met à jour le statut du membre en fonction de ses abonnements
 * 
 * @param int $memberId ID du membre
 * @return bool
 */
function updateMemberStatus($memberId) {
    try {
        $db = getDB();
        
        // Vérifier si le membre a un abonnement actif
        $query = "SELECT COUNT(*) FROM subscriptions 
                  WHERE member_id = :member_id 
                  AND end_date >= CURDATE()";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':member_id', $memberId, PDO::PARAM_INT);
        $stmt->execute();
        
        $hasActiveSubscription = ($stmt->fetchColumn() > 0);
        
        // Mettre à jour le statut du membre
        $status = $hasActiveSubscription ? 'active' : 'inactive';
        
        $updateQuery = "UPDATE members SET 
                        status = :status,
                        updated_at = NOW() 
                        WHERE id = :member_id";
        
        $updateStmt = $db->prepare($updateQuery);
        $updateStmt->bindParam(':status', $status);
        $updateStmt->bindParam(':member_id', $memberId, PDO::PARAM_INT);
        
        return $updateStmt->execute();
        
    } catch (PDOException $e) {
        error_log('Erreur lors de la mise à jour du statut du membre: ' . $e->getMessage());
        return false;
    }
}
