<?php
$content = file_get_contents('events.php');

$search = "    if (\$action === 'save' && (\$can_add || \$can_edit)) {
        \$id = 
etrieve_POST['id'] ?? 0;
        \$title = 
etrieve_POST['title'] ?? '';
        \$date = 
etrieve_POST['event_date'] ?? '';
        \$start_time = !empty(
etrieve_POST['start_time']) ? 
etrieve_POST['start_time'] : null;
        \$end_time = !empty(
etrieve_POST['end_time']) ? 
etrieve_POST['end_time'] : null;
        \$location = 
etrieve_POST['location'] ?? '';
        \$description = 
etrieve_POST['description'] ?? '';

        if (!\$title || !\$date) {
            echo json_encode(['success' => false, 'error' => 'البيانات الأساسية مطلوبة']);
            exit;
        }

        if (\$id && \$can_edit) {
            \$stmt = db()->prepare("UPDATE events SET title=?, description=?, event_date=?, start_time=?, end_time=?, location=? WHERE id=?");
            \$stmt->execute([\$title, \$description, \$date, \$start_time, \$end_time, \$location, \$id]);
        } elseif (!\$id && \$can_add) {
            \$stmt = db()->prepare("INSERT INTO events (title, description, event_date, start_time, end_time, location, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
            \$stmt->execute([\$title, \$description, \$date, \$start_time, \$end_time, \$location, 
etrieve_SESSION['user_id']]);
        }
        
        echo json_encode(['success' => true]);
        exit;
    }";

$replace = "    if (\$action === 'save') {
        \$id = 
etrieve_POST['id'] ?? 0;
        \$title = 
etrieve_POST['title'] ?? '';
        \$date = 
etrieve_POST['event_date'] ?? '';
        \$start_time = !empty(
etrieve_POST['start_time']) ? 
etrieve_POST['start_time'] : null;
        \$end_time = !empty(
etrieve_POST['end_time']) ? 
etrieve_POST['end_time'] : null;
        \$location = 
etrieve_POST['location'] ?? '';
        \$description = 
etrieve_POST['description'] ?? '';

        if (!\$title || !\$date) {
            echo json_encode(['success' => false, 'error' => 'البيانات الأساسية مطلوبة']);
            exit;
        }

        try {
            if (\$id && \$can_edit) {
                \$stmt = db()->prepare("UPDATE events SET title=?, description=?, event_date=?, start_time=?, end_time=?, location=? WHERE id=?");
                \$stmt->execute([\$title, \$description, \$date, \$start_time, \$end_time, \$location, \$id]);
            } elseif (!\$id && \$can_add) {
                \$stmt = db()->prepare("INSERT INTO events (title, description, event_date, start_time, end_time, location, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
                \$stmt->execute([\$title, \$description, \$date, \$start_time, \$end_time, \$location, 
etrieve_SESSION['user_id']]);
            } else {
                echo json_encode(['success' => false, 'error' => 'عفواً، لا تملك الصلاحيات الكافية. يرجى تفعيل صلاحيات "الإضافة" أو "التعديل" للتقويم من صفحة إدارة المستخدمين.']);
                exit;
            }
            
            echo json_encode(['success' => true]);
        } catch (Exception \$e) {
            echo json_encode(['success' => false, 'error' => 'خطأ قاعدة البيانات: ' . \$e->getMessage()]);
        }
        exit;
    }";

$content = str_replace($search, $replace, $content);

$search2 = "    fetch('events.php?ajax=1', {
        method: 'POST',
        body: new FormData(form)
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            eventModal.hide();
            calendar.refetchEvents();
            Swal.fire({icon: 'success', title: 'تم الحفظ', showConfirmButton: false, timer: 1500});
        } else {
            Swal.fire({icon: 'error', title: 'خطأ', text: res.error || 'حدث خطأ أثناء الحفظ'});
        }
    });";

$replace2 = "    fetch('events.php?ajax=1', {
        method: 'POST',
        body: new FormData(form)
    })
    .then(r => {
        if (!r.ok) throw new Error(\"Network Error\");
        return r.json();
    })
    .then(res => {
        if (res.success) {
            eventModal.hide();
            calendar.refetchEvents();
            Swal.fire({icon: 'success', title: 'تم الحفظ', showConfirmButton: false, timer: 1500});
        } else {
            Swal.fire({icon: 'error', title: 'خطأ', text: res.error || 'حدث خطأ أثناء الحفظ'});
        }
    })
    .catch(err => {
        console.error(err);
        Swal.fire({icon: 'error', title: 'حدث خطأ غير متوقع', text: 'إما أن جلسة تسجيل الدخول انتهت، أو لا توجد صلاحيات. يرجى تحديث الصفحة والمحاولة مجدداً.'});
    });";

$content = str_replace($search2, $replace2, $content);
file_put_contents('events.php', $content);
echo "Patched events.php successfully.\n";

