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

// Vérification de l'authentification
requireLogin();

// Vérification des permissions
if (!hasPermission('admin')) {
    setAlert('danger', 'ليس لديك صلاحية للوصول إلى هذه الصفحة');
    header('Location: ' . SITE_URL . '/members/subscriptions.php');
    exit;
}

// Vérification de l'ID de l'abonnement
if (!isset($_GET['id']) || empty($_GET['id'])) {
    setAlert('danger', 'معرف الاشتراك غير صالح');
    header('Location: ' . SITE_URL . '/members/subscriptions.php');
    exit;
}

$subscriptionId = $_GET['id'];

// Récupération des données de l'abonnement
$db = getDbConnection();
$query = "SELECT s.*, m.first_name, m.last_name, c.name as category_name 
          FROM subscriptions s 
          JOIN members m ON s.member_id = m.id 
          LEFT JOIN categories c ON m.category_id = c.id 
          WHERE s.id = ?";
$stmt = $db->prepare($query);
$stmt->execute([$subscriptionId]);
$subscription = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$subscription) {
    setAlert('danger', 'الاشتراك غير موجود');
    header('Location: ' . SITE_URL . '/members/subscriptions.php');
    exit;
}

// Traitement du formulaire si soumis
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Récupération et validation des données
    $memberId = $subscription['member_id'];
    $startDate = $_POST['start_date'] ?? '';
    $endDate = $_POST['end_date'] ?? '';
    $amountPaid = $_POST['amount_paid'] ?? '';
    $paymentMethod = $_POST['payment_method'] ?? '';
    $paymentDate = $_POST['payment_date'] ?? '';
    $receiptNumber = $_POST['receipt_number'] ?? '';
    $isInsurancePaid = isset($_POST['is_insurance_paid']) ? 1 : 0;
    $insuranceAmount = $_POST['insurance_amount'] ?? 0;
    $notes = $_POST['notes'] ?? '';
    
    // Validation des données
    $errors = [];
    
    if (empty($startDate)) {
        $errors[] = 'تاريخ البداية مطلوب';
    }
    
    if (empty($endDate)) {
        $errors[] = 'تاريخ النهاية مطلوب';
    }
    
    if (empty($amountPaid) || !is_numeric($amountPaid)) {
        $errors[] = 'المبلغ المدفوع مطلوب ويجب أن يكون رقمًا';
    }
    
    if (empty($paymentMethod)) {
        $errors[] = 'طريقة الدفع مطلوبة';
    }
    
    if (empty($paymentDate)) {
        $errors[] = 'تاريخ الدفع مطلوب';
    }
    
    // Si aucune erreur, mise à jour de l'abonnement
    if (empty($errors)) {
        $query = "UPDATE subscriptions SET 
                  start_date = ?, 
                  end_date = ?, 
                  amount_paid = ?, 
                  payment_method = ?, 
                  payment_date = ?, 
                  receipt_number = ?, 
                  is_insurance_paid = ?, 
                  insurance_amount = ?, 
                  notes = ? 
                  WHERE id = ?";
        
        $db = getDbConnection();
        $stmt = $db->prepare($query);
        $result = $stmt->execute([
            $startDate,
            $endDate,
            $amountPaid,
            $paymentMethod,
            $paymentDate,
            $receiptNumber,
            $isInsurancePaid,
            $insuranceAmount,
            $notes,
            $subscriptionId
        ]);
        
        if ($result) {
            setAlert('success', 'تم تحديث الاشتراك بنجاح');
            header('Location: ' . SITE_URL . '/members/subscriptions.php');
            exit;
        } else {
            $errors[] = 'حدث خطأ أثناء تحديث الاشتراك';
        }
    }
}

// Inclusion de l'en-tête
$pageTitle = 'تعديل الاشتراك';
include_once '../includes/header.php';
?>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0">تعديل الاشتراك</h5>
                </div>
                <div class="card-body">
                    <h6 class="mb-3">تعديل اشتراك المنخرط: <?php echo htmlspecialchars($subscription['first_name'] . ' ' . $subscription['last_name']); ?></h6>
                    
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo $error; ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                    
                    <form action="edit_subscription_form.php?id=<?php echo $subscriptionId; ?>" method="post" class="needs-validation" novalidate>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="start_date" class="form-label">تاريخ البداية</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $subscription['start_date']; ?>" required>
                                <div class="invalid-feedback">يرجى تحديد تاريخ البداية</div>
                            </div>
                            <div class="col-md-6">
                                <label for="end_date" class="form-label">تاريخ النهاية</label>
                                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $subscription['end_date']; ?>" required>
                                <div class="invalid-feedback">يرجى تحديد تاريخ النهاية</div>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="amount_paid" class="form-label">المبلغ المدفوع</label>
                                <div class="input-group">
                                    <input type="number" step="0.01" class="form-control" id="amount_paid" name="amount_paid" value="<?php echo $subscription['amount_paid']; ?>" required>
                                    <span class="input-group-text">درهم</span>
                                </div>
                                <div class="invalid-feedback">يرجى تحديد المبلغ المدفوع</div>
                            </div>
                            <div class="col-md-6">
                                <label for="payment_method" class="form-label">طريقة الدفع</label>
                                <select class="form-select" id="payment_method" name="payment_method" required>
                                    <option value="">اختر طريقة الدفع</option>
                                    <option value="cash" <?php echo $subscription['payment_method'] === 'cash' ? 'selected' : ''; ?>>نقدا</option>
                                    <option value="check" <?php echo $subscription['payment_method'] === 'check' ? 'selected' : ''; ?>>شيك</option>
                                    <option value="transfer" <?php echo $subscription['payment_method'] === 'transfer' ? 'selected' : ''; ?>>تحويل بنكي</option>
                                    <option value="other" <?php echo $subscription['payment_method'] === 'other' ? 'selected' : ''; ?>>طريقة أخرى</option>
                                </select>
                                <div class="invalid-feedback">يرجى اختيار طريقة الدفع</div>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="payment_date" class="form-label">تاريخ الدفع</label>
                                <input type="date" class="form-control" id="payment_date" name="payment_date" value="<?php echo $subscription['payment_date']; ?>" required>
                                <div class="invalid-feedback">يرجى تحديد تاريخ الدفع</div>
                            </div>
                            <div class="col-md-6">
                                <label for="receipt_number" class="form-label">رقم الإيصال</label>
                                <input type="text" class="form-control" id="receipt_number" name="receipt_number" value="<?php echo htmlspecialchars($subscription['receipt_number']); ?>">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-check mt-4">
                                    <input class="form-check-input" type="checkbox" id="is_insurance_paid" name="is_insurance_paid" value="1" <?php echo $subscription['is_insurance_paid'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_insurance_paid">تم دفع التأمين</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label for="insurance_amount" class="form-label">مبلغ التأمين</label>
                                <div class="input-group">
                                    <input type="number" step="0.01" class="form-control" id="insurance_amount" name="insurance_amount" value="<?php echo $subscription['insurance_amount']; ?>">
                                    <span class="input-group-text">درهم</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="notes" class="form-label">ملاحظات</label>
                            <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo htmlspecialchars($subscription['notes']); ?></textarea>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="subscriptions.php" class="btn btn-secondary">إلغاء</a>
                            <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include_once '../includes/footer.php'; ?>
