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

$search = <<<'EOD'
    if ($action === 'save' && ($can_add || $can_edit)) {
        $id = $_POST['id'] ?? 0;
        $title = $_POST['title'] ?? '';
        $date = $_POST['event_date'] ?? '';
        $start_time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
        $end_time = !empty($_POST['end_time']) ? $_POST['end_time'] : null;
        $location = $_POST['location'] ?? '';
        $description = $_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, $_SESSION['user_id']]);
        }
        
        echo json_encode(['success' => true]);
        exit;
    }
EOD;

$replace = <<<'EOD'
    if ($action === 'save') {
        $id = $_POST['id'] ?? 0;
        $title = $_POST['title'] ?? '';
        $date = $_POST['event_date'] ?? '';
        $start_time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
        $end_time = !empty($_POST['end_time']) ? $_POST['end_time'] : null;
        $location = $_POST['location'] ?? '';
        $description = $_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, $_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;
    }
EOD;

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

$search2 = <<<'EOD'
    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 || 'حدث خطأ أثناء الحفظ'});
        }
    });
EOD;

$replace2 = <<<'EOD'
    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: 'إما أن جلسة تسجيل الدخول انتهت، أو لا توجد صلاحيات (راجع سجل وحدة التحكم). يرجى تحديث الصفحة والمحاولة مجدداً.'});
    });
EOD;

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

