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

$search = <<<'EOD'
    if ($action === 'delete' && $can_delete) {
        $id = $_POST['id'] ?? 0;
        db()->prepare("DELETE FROM events WHERE id=?")->execute([$id]);
        echo json_encode(['success' => true]);
        exit;
    }
EOD;

$replace = <<<'EOD'
    if ($action === 'delete') {
        if (!$can_delete) {
            echo json_encode(['success' => false, 'error' => 'لا تملك صلاحية الحذف.']);
            exit;
        }
        try {
            $id = $_POST['id'] ?? 0;
            db()->prepare("DELETE FROM events WHERE id=?")->execute([$id]);
            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: fd
            })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    eventModal.hide();
                    calendar.refetchEvents();
                    Swal.fire({icon: 'success', title: 'تم الحذف', showConfirmButton: false, timer: 1500});
                }
            });
EOD;

$replace2 = <<<'EOD'
            fetch('events.php?ajax=1', {
                method: 'POST',
                body: fd
            })
            .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 delete in events.php\n";

